Skip to content

fix(autoresearch): fail fast when --upload-port is not attached - #3873

Merged
zackees merged 1 commit into
masterfrom
fix/autoresearch-absent-port-preflight
Aug 7, 2026
Merged

zackees merged 1 commit into
masterfrom
fix/autoresearch-absent-port-preflight

Conversation

@zackees

@zackees zackees commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

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.

The wasted time is the smaller problem. The refusal surfaces as a stale health=phantom COM 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:

❌ 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 exactly 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. "Unknown" is permissive by construction and a test pins it.

platform is injectable, matching selective_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=False silently disabled every check in #3872):

  • port_presence("COM17") → (False, 474041) — 5d, matching the independent DEVPKEY_Device_LastArrivalDate of 2026-08-01, and agreeing with fbuild port doctor --port COM17.
  • 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.

One PowerShell CIM query, ~1.7s, against ~7 minutes saved.

uv run pytest ci/tests/test_usb_power.py — 16 passed. bash lint clean.

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

    • Added pre-build validation for explicitly selected upload ports.
    • Reports missing or stale ports before installation, linting, or compilation.
    • Added fbuild port doctor --port for detailed port diagnostics.
    • Preserves automatic port detection and RP BOOTSEL fallback behavior.
  • Bug Fixes

    • Prevents builds from proceeding when Windows definitively reports the selected port as absent.
  • Tests

    • Added coverage for port detection, unknown states, age formatting, platform behavior, and diagnostic messages.

`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]>
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The 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.

Changes

Explicit upload-port preflight

Layer / File(s) Summary
USB presence diagnostics
ci/autoresearch/usb_power.py
The utilities parse presence records, query Windows PnP data, format last-arrival age, and report errors only for definite absence.
Build preflight and validation
ci/autoresearch/phases.py, ci/tests/test_usb_power.py, agents/docs/hardware-autoresearch.md
Autoresearch validates explicit ports before package installation. Tests cover known and unknown states. Documentation describes diagnostics, BOOTSEL fallback, and fbuild port doctor --port.

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
Loading

Possibly related issues

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR adds the diagnostic preflight but does not satisfy #3864 acceptance criteria for healthy hardware and completed HIL validation. Complete and record the required RP2350W and ESP32-C6 HIL flows, watchdog recovery, and GPIO 0/1 loopback evidence.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: failing fast when an explicitly supplied upload port is not attached.
Out of Scope Changes check ✅ Passed The changes support the stated diagnostic objective and remain focused on validating explicitly supplied upload ports before builds.
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/autoresearch-absent-port-preflight

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.

@coderabbitai coderabbitai 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0bb2269 and 86971af.

📒 Files selected for processing (4)
  • agents/docs/hardware-autoresearch.md
  • ci/autoresearch/phases.py
  • ci/autoresearch/usb_power.py
  • ci/tests/test_usb_power.py

Comment thread agents/docs/hardware-autoresearch.md Resolved
Comment thread ci/autoresearch/usb_power.py Resolved
Comment thread ci/autoresearch/usb_power.py Resolved
@zackees
zackees merged commit 6a120de into master Aug 7, 2026
18 of 21 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Aug 7, 2026
zackees added a commit that referenced this pull request Aug 7, 2026
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]>
zackees added a commit that referenced this pull request Aug 7, 2026
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]>
zackees added a commit that referenced this pull request Aug 7, 2026
#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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

chore(rp2350w): hand off final #3832 hardware validation

1 participant