Repository navigation
fix(autoresearch): fail fast when --upload-port is not attached - #3873
Conversation
`bash autoresearch rp2350w --upload-port COM17` used to install packages, lint and build for ~7 minutes before fbuild refused the deploy, on a board that had simply not been plugged in for five days. Worse than the wasted time, the refusal surfaces as a stale `health=phantom` COM record, which reads like a wedged devnode — that misreading is what sent the #3864 investigation down a BOOTSEL and PnP-recovery hunt before anyone checked whether the board was attached at all. Now checked before Phase 0: ❌ COM17 is not attached, last seen 5d ago. Windows keeps the record after a board is unplugged, so this is a stale devnode, not a fault — plug the board in and re-run. The message states the conclusion rather than the symptom, because the symptom is precisely what gets misread. Two deliberate limits: - **Explicit `--upload-port` only.** Without one, fbuild can still reach an RP-series board through the BOOTSEL volume with no working CDC record (fbuild#1147), so absence there is not fatal. Gating on `args.upload_port` rather than `ctx.upload_port` keeps auto-detected ports out of scope. - **Only an unambiguous `Present = False` stops a run.** If the host cannot answer, the run proceeds. A query failure that reported absence would abort against a board sitting there perfectly healthy — so "unknown" is permissive by construction, and a test pins that. `platform` is injectable, like `selective_suspend_warnings`, so the Windows behaviour is actually exercised on Linux CI instead of silently short- circuiting to a pass. Verified live rather than only against fakes — the mocked-tests-pass-but- the-feature-is-dead failure has bitten this module before: - `port_presence("COM17")` → `(False, 474041)`, i.e. 5d, matching the independent `DEVPKEY_Device_LastArrivalDate` of 2026-08-01. - `port_presence("COM9")` → `(True, 23149)` on the attached LOLIN S3. - End-to-end `bash autoresearch rp2350w --upload-port COM17` aborts in seconds with exit 1, before any build. Costs one PowerShell CIM query, ~1.7s, against ~7 minutes saved. `uv run pytest ci/tests/test_usb_power.py` — 16 passed. `bash lint` clean. Refs #3864 Co-Authored-By: Claude <[email protected]>
📝 WalkthroughWalkthroughThe change adds Windows USB presence diagnostics for explicit upload ports. Autoresearch now aborts before installation when a requested port is definitely absent. Automatic port selection remains unchanged. Tests and hardware documentation cover the behavior. ChangesExplicit upload-port preflight
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant Autoresearch
participant absent_port_error
participant WindowsPnP
participant BuildPhases
Autoresearch->>absent_port_error: validate explicit upload port
absent_port_error->>WindowsPnP: query requested port
WindowsPnP-->>absent_port_error: return presence and last-arrival data
absent_port_error-->>Autoresearch: return diagnostic or no error
Autoresearch->>BuildPhases: continue when port is not definitely absent
Possibly related issues
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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.
Inline comments:
In `@agents/docs/hardware-autoresearch.md`:
- Around line 217-221: Update the diagnostic code fence containing the COM17
console-output example to specify the text language, changing the opening fence
to use text while preserving its contents.
In `@ci/autoresearch/usb_power.py`:
- Around line 64-89: Replace the tuple result of parse_presence and
port_presence with a typed, `@typechecked` presence dataclass exposing named
fields for presence and arrival time; update absent_port_error and related
assertions to use those fields instead of positional indexing. Add default run
arguments where needed to support injectable tests, and preserve the existing
parsing behavior for valid, invalid, and missing values. Apply these changes at
ci/autoresearch/usb_power.py lines 64-89, 92-112, and 144-147.
- Around line 103-105: Escape the CLI port value before embedding it in the
PowerShell script generated by the script construction near Get-PnpDevice. Build
the single-quoted literal separately, concatenate it with the regex-escaped port
value using [regex]::Escape, and add a regression test covering a port
containing a single quote.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: c3e0432d-6e84-47fa-9fe6-d3845ebf597d
📒 Files selected for processing (4)
agents/docs/hardware-autoresearch.mdci/autoresearch/phases.pyci/autoresearch/usb_power.pyci/tests/test_usb_power.py
Addresses both CodeRabbit findings on #3873. `parse_presence`/`port_presence` returned a bare `(Optional[bool], Optional[int])` that `absent_port_error` unpacked positionally. Both fields are optional and neither is self-describing at the call site, so a swap would type-check and silently invert the meaning of the check — on a function whose entire job is deciding whether to abort a run. `PortPresence` is frozen and `@typechecked`, matching the dataclass-result convention already used by `ChipDetectionResult` in ci/util/port_utils.py. Its docstring now carries the tri-state rule that was previously buried in `parse_presence`: `present=None` means "the host could not say" and must never be read as "absent". Also sets the `text` language on the diagnostic fence in hardware-autoresearch.md (markdownlint MD040). Re-verified live after the refactor, not just against the fakes: COM17: PortPresence(present=False, last_seen_secs=482667) # 5d, absent COM9 : PortPresence(present=True, last_seen_secs=31776) # attached `uv run pytest ci/tests/test_usb_power.py` — 16 passed. `bash lint` clean (warn-only checkers unchanged). Refs #3864 Co-Authored-By: Claude <[email protected]>
Addresses the third CodeRabbit finding on #3873 (Security, Major). `port` came from `--upload-port` and was interpolated straight into a single-quoted PowerShell literal: Where-Object { $_.FriendlyName -match '\(COM17\)' } A value containing `'` closes that string and runs arbitrary PowerShell as the invoking user. Now refused by allowlist (`^COM\d+$`) rather than escaped, and the subprocess is never spawned for a rejected value. Allowlist over escaping on purpose. Escaping here needs two independent layers to be correct — PowerShell quoting *and* regex metacharacters, since the value lands inside `-match` — and getting either wrong reintroduces the hole silently. A COM port name has no legitimate reason to contain anything outside `COM\d+`. It is also a correctness fix, which is what makes it more than hardening: `--upload-port` legitimately accepts `UF2=E:\` for a board already in BOOTSEL. That trailing backslash would corrupt the `-match` regex. It names a volume, not a COM device, so there is nothing to look up — it now returns "unknown" and, because unknown is permissive, a UF2 deploy is never blocked by the preflight. Verified: `port_presence("UF2=E:\\")` -> unknown. Applied the same guard to `hub_chain_power_off`, which had the identical pattern from #3872. Four regression tests: a quote-bearing port, the `UF2=` form, the hub-chain path, and one pinning that real ports (`COM9`, `COM17`, `com3`, `COM255`) still work — a guard that broke the actual use case would be worse than the bug. The hostile-input tests assert the runner is never called at all, not merely that the result is empty. Live: COM17 -> present=False/482925s, COM9 -> present=True/32035s. 20 tests pass; `bash lint` clean. Refs #3864 Co-Authored-By: Claude <[email protected]>
#3874) * refactor(autoresearch): return a typed PortPresence instead of a tuple Addresses both CodeRabbit findings on #3873. `parse_presence`/`port_presence` returned a bare `(Optional[bool], Optional[int])` that `absent_port_error` unpacked positionally. Both fields are optional and neither is self-describing at the call site, so a swap would type-check and silently invert the meaning of the check — on a function whose entire job is deciding whether to abort a run. `PortPresence` is frozen and `@typechecked`, matching the dataclass-result convention already used by `ChipDetectionResult` in ci/util/port_utils.py. Its docstring now carries the tri-state rule that was previously buried in `parse_presence`: `present=None` means "the host could not say" and must never be read as "absent". Also sets the `text` language on the diagnostic fence in hardware-autoresearch.md (markdownlint MD040). Re-verified live after the refactor, not just against the fakes: COM17: PortPresence(present=False, last_seen_secs=482667) # 5d, absent COM9 : PortPresence(present=True, last_seen_secs=31776) # attached `uv run pytest ci/tests/test_usb_power.py` — 16 passed. `bash lint` clean (warn-only checkers unchanged). Refs #3864 Co-Authored-By: Claude <[email protected]> * fix(autoresearch): allowlist COMn before interpolating into PowerShell Addresses the third CodeRabbit finding on #3873 (Security, Major). `port` came from `--upload-port` and was interpolated straight into a single-quoted PowerShell literal: Where-Object { $_.FriendlyName -match '\(COM17\)' } A value containing `'` closes that string and runs arbitrary PowerShell as the invoking user. Now refused by allowlist (`^COM\d+$`) rather than escaped, and the subprocess is never spawned for a rejected value. Allowlist over escaping on purpose. Escaping here needs two independent layers to be correct — PowerShell quoting *and* regex metacharacters, since the value lands inside `-match` — and getting either wrong reintroduces the hole silently. A COM port name has no legitimate reason to contain anything outside `COM\d+`. It is also a correctness fix, which is what makes it more than hardening: `--upload-port` legitimately accepts `UF2=E:\` for a board already in BOOTSEL. That trailing backslash would corrupt the `-match` regex. It names a volume, not a COM device, so there is nothing to look up — it now returns "unknown" and, because unknown is permissive, a UF2 deploy is never blocked by the preflight. Verified: `port_presence("UF2=E:\\")` -> unknown. Applied the same guard to `hub_chain_power_off`, which had the identical pattern from #3872. Four regression tests: a quote-bearing port, the `UF2=` form, the hub-chain path, and one pinning that real ports (`COM9`, `COM17`, `com3`, `COM255`) still work — a guard that broke the actual use case would be worse than the bug. The hostile-input tests assert the runner is never called at all, not merely that the result is empty. Live: COM17 -> present=False/482925s, COM9 -> present=True/32035s. 20 tests pass; `bash lint` clean. Refs #3864 Co-Authored-By: Claude <[email protected]> * fix(autoresearch): use fullmatch so COM1\n cannot pass the allowlist CodeRabbit caught a hole in the allowlist from the previous commit. In Python `$` matches before a final newline, so: re.match(r"^COM\d+$", "COM1\n") -> match re.fullmatch(r"^COM\d+$", "COM1\n") -> None Both callers used `match`, so `COM1\n` was accepted and reached the PowerShell script construction it was supposed to be barred from. Routed both through a single `_is_com_port()` helper using `fullmatch`, rather than fixing the two call sites independently — one guard is harder to get inconsistently wrong than two, and the next caller inherits it. The `^`/`$` anchors stay as belt-and-braces for anyone who reaches for `match` out of habit, with the reason recorded next to the pattern. The regression test covers the whole shape of the mistake, not just the reported input: `COM1\n`, `COM1\r\n`, and leading/trailing space and tab. It also asserts the runner is never invoked, so a future "fix" that merely returns empty after shelling out still fails. Verified: `port_presence("COM1\n")` -> unknown, `port_presence("COM17")` -> present=False/486027s (still absent, unchanged). 21 tests pass; lint clean. Refs #3864 Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
bash autoresearch rp2350w --upload-port COM17used to install packages, lint and build for ~7 minutes before fbuild refused the deploy — on a board that had simply not been plugged in for five days.The wasted time is the smaller problem. The refusal surfaces as a stale
health=phantomCOM record, which reads like a wedged devnode, and that misreading is what sent the #3864 investigation down a BOOTSEL and PnP-recovery hunt before anyone checked whether the board was attached at all.Now checked before Phase 0:
The message states the conclusion rather than the symptom, because the symptom is exactly what gets misread.
Two deliberate limits
Explicit
--upload-portonly. Without one, fbuild can still reach an RP-series board through the BOOTSEL volume with no working CDC record (fbuild#1147), so absence there is not fatal. Gating onargs.upload_portrather thanctx.upload_portkeeps auto-detected ports out of scope.Only an unambiguous
Present = Falsestops a run. If the host cannot answer, the run proceeds — a query failure that reported absence would abort against a board sitting there perfectly healthy. "Unknown" is permissive by construction and a test pins it.platformis injectable, matchingselective_suspend_warnings, so the Windows behaviour is actually exercised on Linux CI rather than silently short-circuiting to a pass.Validation
Verified live, not only against fakes — the mocked-tests-pass-but-the-feature-is-dead failure has bitten this exact module before (
capture_output=Falsesilently disabled every check in #3872):port_presence("COM17")→(False, 474041)— 5d, matching the independentDEVPKEY_Device_LastArrivalDateof 2026-08-01, and agreeing withfbuild port doctor --port COM17.port_presence("COM9")→(True, 23149)on the attached LOLIN S3.bash autoresearch rp2350w --upload-port COM17aborts in seconds with exit 1, before any build.One PowerShell CIM query, ~1.7s, against ~7 minutes saved.
uv run pytest ci/tests/test_usb_power.py— 16 passed.bash lintclean.Scope
This does not close #3864. That issue's acceptance criteria are hardware-in-the-loop results, and the RP2350W is still not attached to this bench. This fixes the diagnostic that made its absence hard to recognise.
Refs #3864
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
fbuild port doctor --portfor detailed port diagnostics.Bug Fixes
Tests