Skip to content

fix: bound three-channel captures by the physical buffer - #308

Open
YashAnand69 wants to merge 2 commits into
fossasia:mainfrom
YashAnand69:fix/three-channel-capture-capacity
Open

YashAnand69 wants to merge 2 commits into
fossasia:mainfrom
YashAnand69:fix/three-channel-capture-capacity

Conversation

@YashAnand69

@YashAnand69 YashAnand69 commented Oct 8, 2026 •

Copy link
Copy Markdown

Three-channel captures use CAPTURE_FOUR and discard MIC when returning data. The current MAX_SAMPLES // channels check nevertheless allows up to 3,333 samples per channel, exceeding the shared 10,000-sample buffer once the fourth channel is included.

Validate against four captured channels for this case, limiting it to 2,500 samples per channel. Use the same limit for CLI batches, reject oversized requests before changing channel or trigger settings, and document the per-channel limits. Keep the one-, two- and four-channel limits unchanged. The Python command path and firmware's OSCILLOSCOPE_CaptureFour both confirm four-channel allocation.

Validation:

  • 13 hardware-independent regression cases. The 2,501- and 3,333-sample three-channel cases fail on unchanged main; the other 11 controls pass.
  • 54 tests pass across the capacity, CLI and existing Pico SCPI transport suites.
  • Review follow-ups: the oversized CLI batch fails before its fix; four state-preservation cases fail before early size validation. Valid trigger disabling with a shorter time gap remains covered.
  • Changed-file Black, Flake8, Bandit and pydocstyle checks and the wheel/sdist build pass. Documentation builds with the same seven warnings as baseline.
  • Verified rejection before any device writes, full-buffer boundaries, four-channel command selection and omission of MIC from the three-channel result.

Existing CLI optimization PR #298 applies cleanly alongside these changes; its separate concatenation change is not included.

No physical hardware or firmware integration was tested. No existing issue or overlapping PR found; historical #198 concerned the already-fixed time-gap lookup, not buffer capacity.

AI assistance: developed and tested with OpenAI Codex.

Summary by Sourcery

Enforce physical buffer limits for three-channel oscilloscope captures across the instrument and CLI paths.

Bug Fixes:

  • Correct buffer-capacity validation for three-channel oscilloscope captures by accounting for the internally captured MIC channel.
  • Reject oversized captures before modifying channel or trigger configuration.

Enhancements:

  • Document per-channel oscilloscope sample limits and apply the corrected three-channel limit consistently to CLI captures.

Tests:

  • Add hardware-independent regression coverage for capture boundaries, command selection, returned channels, CLI limits, and state preservation.

Summary by CodeRabbit

  • Bug Fixes
    • Oscilloscope captures now enforce per-channel sample limits: 10,000 samples for one channel, 5,000 for two, and 2,500 for three or four. Requests that exceed these limits are rejected before communicating with the device.
    • Three-channel captures use the four-channel sampling allocation and remain within the available buffer capacity.
  • Documentation
    • Clarified supported channel counts and sample limits, including that three-channel captures sample the microphone internally.

@sourcery-ai

sourcery-ai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR fixes three-channel oscilloscope captures by validating against their actual four-channel firmware allocation, reducing their maximum to 2,500 samples per channel while preserving existing limits for other modes. Documentation and focused mock-based regression tests cover rejection timing, boundary capacities, command selection, internal MIC allocation, and returned-channel behavior.

Sequence diagram for bounded three-channel oscilloscope capture

sequenceDiagram
    participant Caller
    participant Oscilloscope
    participant Firmware

    Caller->>Oscilloscope: capture(channels, samples, timegap)
    Oscilloscope->>Oscilloscope: _check_args(channels, samples, timegap)
    alt channels == 3
        Oscilloscope->>Oscilloscope: capture_channels = 4
        alt samples > 2500
            Oscilloscope-->>Caller: ValueError
        else samples <= 2500
            Oscilloscope->>Firmware: OSCILLOSCOPE_CaptureFour(samples, ...)
            Firmware-->>Oscilloscope: CH1, CH2, CH3, MIC data
            Oscilloscope-->>Caller: CH1, CH2, CH3 data
        end
    else channels == 1, 2, or 4
        Oscilloscope->>Firmware: capture command for requested channels
        Firmware-->>Oscilloscope: captured data
        Oscilloscope-->>Caller: requested channel data
    end
Loading

File-Level Changes

Change Details Files
Adjust three-channel sample validation to account for the internally captured MIC channel.
  • Treat three-channel requests as four-channel buffer allocations during capacity checks.
  • Limit three-channel captures to 2,500 samples per channel while preserving one-, two-, and four-channel limits.
  • Update API documentation and validation errors to describe the effective capacity.
pslab/instrument/oscilloscope.py
Add hardware-independent regression coverage for capacity boundaries and capture-channel behavior.
  • Verify over-capacity requests are rejected before device writes for all channel counts.
  • Verify exact buffer-capacity requests and channel buffer bounds.
  • Verify three-channel captures select CAPTURE_FOUR, retain the first three returned channels, and allocate MIC internally.
tests/test_oscilloscope_capacity.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 96493c3a-6cda-4936-b37d-0caf0e97f82a
📥 Commits

Reviewing files that changed from the base of the PR and between 54a2261 and f871f42.

📒 Files selected for processing (4)
  • pslab/cli.py
  • pslab/instrument/oscilloscope.py
  • tests/test_cli.py
  • tests/test_oscilloscope_capacity.py

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

Three-channel oscilloscope captures now use the four-channel buffer-capacity limit. The documentation describes the 2,500-sample limit and internal MIC sampling. CLI sizing and hardware-free tests cover channel capacities and capture results.

Changes

Oscilloscope capture capacity

Layer / File(s) Summary
Channel-specific capture validation
pslab/instrument/oscilloscope.py, tests/test_oscilloscope_capacity.py
Capture capacity validation is separate from timing and channel-argument validation. Three-channel captures use four-channel capacity. Tests cover capacity boundaries, device calls, buffer limits, trigger settings, channel mapping, and capture results.
CLI sizing and capture verification
pslab/cli.py, tests/test_cli.py
The CLI documents three-channel captures and uses four-channel capacity when sizing them. Parameterized tests check capture arguments and returned headers, timestamps, and channel data.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to f871f

The capture and CLI limits are aligned, and no merge-blocking issue remains from the reviewed evidence. This change is ready for normal merge checks.

Security Architecture Review

Security architecture risk: ⚪ Minimal · up to f871f

The change reduces oversized capture admission and rejects it before instrument-state changes or device writes. The reviewed paths introduce no material security risk or additional device authority. Physical hardware behavior was not validated.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated exposure is caller-controlled capture sizing on the supplied device connection and its shared sample buffer. The change narrows admitted requests without adding transport access or device authority in the inspected paths.

Trust Boundaries and Controls

  • observed — Caller-provided channel and sample counts pass through the revised capacity check before capture commands reach the device. The control accounts for physical allocation rather than only returned channels, and oversized rejection preserves existing instrument state.

Resilience and Maintainability Implications

  • observed — Partial transport failure can still occur after capture metadata changes and before the final acknowledgement, without rollback in that path. The blocking progress loop and subsequent capture invalidation are also unchanged. These recovery limitations predate the PR; the new size check prevents oversized requests from entering those transitions.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: limiting three-channel captures to the physical buffer capacity.
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="pslab/instrument/oscilloscope.py" line_range="165" />
<code_context>
-        max_samples = CP.MAX_SAMPLES // channels
+        # Three-channel captures use CAPTURE_FOUR and discard MIC.
+        capture_channels = 4 if channels == 3 else channels
+        max_samples = CP.MAX_SAMPLES // capture_channels
         if not 0 < samples <= max_samples:
             e1 = f"Cannot collect more than {max_samples} when sampling from "
</code_context>
<issue_to_address>
**Three-channel CLI captures abort**

When the CLI requests a three-channel batch larger than 2,500 samples, `cli.oscilloscope` sizes batches using `CP.MAX_SAMPLES // channels`, so it can pass up to 3,333 samples to `scope.capture`, which rejects batches above 2,500 with an uncaught `ValueError`. Collection stops instead of returning the requested data.

Make the CLI batch-size calculation use the same effective channel count as `capture` for three-channel requests.
</issue_to_address>

### Comment 2
<location path="pslab/instrument/oscilloscope.py" line_range="165" />
<code_context>
-        max_samples = CP.MAX_SAMPLES // channels
+        # Three-channel captures use CAPTURE_FOUR and discard MIC.
+        capture_channels = 4 if channels == 3 else channels
+        max_samples = CP.MAX_SAMPLES // capture_channels
         if not 0 < samples <= max_samples:
             e1 = f"Cannot collect more than {max_samples} when sampling from "
</code_context>
<issue_to_address>
**Failed captures change trigger state**

When a three-channel request exceeds 2,500 samples and supplies a trigger setting, `capture` applies `trigger=False` or calls `configure_trigger` before `_check_args` rejects the sample count. The failed call can write changed trigger settings to the device, so later captures use an unexpected trigger setting.

Validate the sample count before applying or configuring the requested trigger setting.
</issue_to_address>

### Comment 3
<location path="pslab/instrument/oscilloscope.py" line_range="64-65" />
<code_context>
         samples : int
             Number of samples to fetch. Maximum 10000 divided by number of
-            channels.
+            channels. Three-channel captures also sample MIC internally,
+            so their maximum is 2500 samples per channel.
         timegap : float
             Time gap between samples in microseconds. Will be rounded to the
</code_context>
<issue_to_address>
**Capture limit documentation conflicts**

The general “10000 divided by number of channels” statement gives a 3,333-sample limit for three channels, contradicting the following 2,500-sample limit and leaving readers unsure which limit applies.

Qualify the general formula to exclude three-channel captures, or state the per-channel limits explicitly.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: pslab/instrument/oscilloscope.py:165, pslab/instrument/oscilloscope.py:165


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread pslab/instrument/oscilloscope.py
Comment thread pslab/instrument/oscilloscope.py
Comment thread pslab/instrument/oscilloscope.py Outdated
@YashAnand69

Copy link
Copy Markdown
Author

Addressed the three findings in f871f42:

  • CLI three-channel batches now use the same 2,500-sample capacity. The real-capture CLI regression failed before the fix; eight CLI cases cover all channel counts and short/full batches.
  • Sample-count validation runs before channel mapping or trigger changes. Four regressions failed on the first PR head and now pass, including trigger disabling and reconfiguration. Valid trigger disabling still permits the shorter single-channel time gap.
  • The docstring now states the explicit limits for all four channel counts.

All 54 capacity/CLI/Pico tests pass; changed-file linters, package build and documentation build pass. The existing #298 optimization patch still applies cleanly. No physical hardware testing was performed.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Sourcery assessment

Approved.

This branch has not been deployed

No deployments
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.

1 participant