Skip to content

fix: warn instead of error when extra args passed to sampling methods from UI#1369

Draft
mihow wants to merge 2 commits into
mainfrom
fix/captureset-extra-args
Draft

fix: warn instead of error when extra args passed to sampling methods from UI#1369
mihow wants to merge 2 commits into
mainfrom
fix/captureset-extra-args

Conversation

@mihow

@mihow mihow commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator

Fixes #1266 by filtering out unsupported arguments. Also adds support for max number of captures to the interval sampler.

Summary by CodeRabbit

  • New Features

    • Added an optional limit for interval-based image sampling, allowing callers to request a specific maximum number of images.
  • Bug Fixes

    • Sampling now safely ignores unsupported configuration options instead of failing when extra settings are provided.
    • Improved sampling behavior when different sampling methods accept different options.

Copilot AI review requested due to automatic review settings July 14, 2026 00:38
@netlify

netlify Bot commented Jul 14, 2026

Copy link
Copy Markdown

Deploy Preview for antenna-preview canceled.

Name Link
🔨 Latest commit 169f104
🔍 Latest deploy log https://app.netlify.com/projects/antenna-preview/deploys/6a5584ebdaaa0100084aa690

@netlify

netlify Bot commented Jul 14, 2026

Copy link
Copy Markdown

Deploy Preview for antenna-ssec canceled.

Name Link
🔨 Latest commit 169f104
🔍 Latest deploy log https://app.netlify.com/projects/antenna-ssec/deploys/6a5584eb727df40008f8bac6

@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Sampling population now filters stored kwargs against the selected method signature. Interval sampling accepts and forwards an optional max_num limit, with tests covering ignored extras and exact result counts.

Changes

Sampling compatibility

Layer / File(s) Summary
Filter unsupported sampling kwargs
ami/main/models.py, ami/main/tests.py
populate_sample() introspects sampling methods, ignores unsupported kwargs, logs them, and tests the updated behavior.
Forward interval sample limits
ami/main/models.py, ami/main/tests.py
sample_interval() accepts and forwards max_num; tests verify the requested sample count.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested labels: bug, backend

Suggested reviewers: annavik, mohamedelabbas1996, carlosgjs, copilot

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is on-topic but far too sparse and misses the required template sections like Summary, Changes, Related Issues, and Testing. Expand the PR description to include the template sections: Summary, List of Changes, Related Issues, Detailed Description, How to Test, and relevant checklist/deployment notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: handling extra sampling kwargs from the UI without crashing, plus interval sampling support.
Linked Issues check ✅ Passed The code filters unsupported kwargs and adds max_num to sample_interval, satisfying the main requirements from #1266.
Out of Scope Changes check ✅ Passed The edits are limited to sampling kwargs handling and tests, with no clear unrelated or extraneous changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/captureset-extra-args

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses backward/forward compatibility between stored kwargs on SourceImageCollection records and the current sampling method signatures by filtering unsupported kwargs (logging a warning instead of raising). It also extends the interval sampler to accept max_num, preventing failures for legacy capture sets that still store max_num in their JSON config.

Changes:

  • Filter SourceImageCollection.kwargs against the target sampling method’s signature before calling it, and warn on ignored keys.
  • Add max_num support to sample_interval and pass it through to sample_captures_by_interval.
  • Update/extend tests to ensure extra kwargs no longer break population and that interval sampling respects max_num.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
ami/main/models.py Filters stored sampling kwargs by method signature, warns on ignored kwargs, and adds max_num support to interval sampling.
ami/main/tests.py Updates the “extra arguments” test to assert successful population and adds coverage for max_num in interval sampling.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread ami/main/models.py
ignored_kwargs = sorted(set(kwargs) - set(filtered_kwargs))
if ignored_kwargs:
task_logger.warning(
"Ignoring unsupported arguments for samplng method %s: %s",
Comment thread ami/main/models.py
self,
minute_interval: int = 10,
max_num: int | None = None,
exclude_events: list[int] = [],

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
ami/main/models.py (1)

5113-5116: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Enforce max_num limit globally across all deployments.

While passing max_num to sample_captures_by_interval in the loop above is an excellent optimization to avoid fetching unnecessary rows from the database, it only limits the count per deployment. If a project has 5 deployments and max_num=10, the current logic will collect up to 50 captures in total.

To properly enforce the global max_num limit for the collection, slice the combined and chronologically sorted final list before returning it. This guarantees we return the absolute earliest max_num captures across the entire project.

🐛 Proposed fix
         # Return results in a deterministic order. Sort by timestamp (oldest first),
         # then by primary key to stabilize ordering when timestamps are equal.
         captures_list = sorted(captures, key=lambda s: (s.timestamp is None, s.timestamp, s.pk))
+        if max_num is not None:
+            captures_list = captures_list[:max_num]
         return captures_list
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ami/main/models.py` around lines 5113 - 5116, Update the final return path
after sorting captures_list to enforce max_num globally: slice the combined,
chronologically ordered list to at most max_num entries before returning. Keep
the existing deterministic timestamp and primary-key ordering intact.
🧹 Nitpick comments (2)
ami/main/models.py (1)

4927-4931: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Fix typographical error in the log message.

There is a minor typo in the log message ("samplng" instead of "sampling").

♻️ Proposed fix
                 task_logger.warning(
-                    "Ignoring unsupported arguments for samplng method %s: %s",
+                    "Ignoring unsupported arguments for sampling method %s: %s",
                     method_name,
                     ", ".join(ignored_kwargs),
                 )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ami/main/models.py` around lines 4927 - 4931, Correct the typo in the warning
message within the unsupported-arguments logging call, changing “samplng” to
“sampling” while preserving the existing formatting and arguments.
ami/main/tests.py (1)

1435-1447: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Strengthen test to verify global enforcement of max_num.

This test currently passes despite the per-deployment bug in sample_interval because self.project_one only contains a single deployment by default.

To ensure this test correctly validates that max_num applies as a global limit (rather than returning max_num captures per deployment), consider adding a second deployment with its own captures.

♻️ Proposed test update
     def test_interval_sample_accepts_max_num(self):
-        from ami.main.models import SourceImageCollection
+        from ami.main.models import SourceImageCollection, Deployment
+
+        # Add a second deployment to ensure max_num acts as a global limit
+        deployment_two = Deployment.objects.create(name="Test Deployment Two", project=self.project_one)
+        create_captures(deployment=deployment_two, num_nights=1, images_per_night=2, interval_minutes=1)

         collection = SourceImageCollection.objects.create(
             name="Test Interval Sample With Max Num",
             project=self.project_one,
             method="interval",
             kwargs={"minute_interval": 1, "max_num": 1},
         )
         collection.save()
         collection.populate_sample()
 
         self.assertEqual(collection.images.count(), 1)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ami/main/tests.py` around lines 1435 - 1447, Add a second deployment with its
own captures to test_interval_sample_accepts_max_num before populating the
sample, then assert the collection still contains exactly one image. Ensure the
fixtures exercise multiple deployments so max_num is validated as a global limit
rather than a per-deployment limit.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@ami/main/models.py`:
- Around line 5113-5116: Update the final return path after sorting
captures_list to enforce max_num globally: slice the combined, chronologically
ordered list to at most max_num entries before returning. Keep the existing
deterministic timestamp and primary-key ordering intact.

---

Nitpick comments:
In `@ami/main/models.py`:
- Around line 4927-4931: Correct the typo in the warning message within the
unsupported-arguments logging call, changing “samplng” to “sampling” while
preserving the existing formatting and arguments.

In `@ami/main/tests.py`:
- Around line 1435-1447: Add a second deployment with its own captures to
test_interval_sample_accepts_max_num before populating the sample, then assert
the collection still contains exactly one image. Ensure the fixtures exercise
multiple deployments so max_num is validated as a global limit rather than a
per-deployment limit.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7d652d5a-4f38-4cf6-ba72-22154fefc9c6

📥 Commits

Reviewing files that changed from the base of the PR and between 3f85d84 and 169f104.

📒 Files selected for processing (2)
  • ami/main/models.py
  • ami/main/tests.py

@mihow mihow marked this pull request as draft July 14, 2026 04:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Capture set population fails with stored kwargs: sample_interval() rejects max_num

2 participants