Repository navigation
fix(teensy4/autoresearch): honest FlexPWM RX + wrapper deadline + watchdog (closes #3219) - #3341
Conversation
…ir (#3219) Two related fixes uncovered on a live Teensy 4.0 bench session after PR #3222's dual-circuit capture refactor exposed the wrapper-skip cheating. Both were masking real RX-decode failures as success. 1) `wait()` always returned `RxWaitResult::SUCCESS` even on timeout with zero captures. Caller (`capture()` in AutoResearchTest.cpp:428) trusts SUCCESS to mean "RX got data" and proceeds to decode the buffer -- which on a no-data timeout is stale or zero. Result was indistinguishable from real decode errors. Track CITER's initial value and return TIMEOUT when DMA never moved. 2) `buildEdgeTimesFromCaptures()` pushed the first HIGH edge unconditionally, then skipped only the subsequent gap LOW when `low_ns > 5000`. On Teensy 4.0 the IOMUXC pad-mux switch + DMA arm sometimes latches a phantom rising+falling pair whose HIGH duration looks like a real T0H (~226 ns) but is followed by a multi-us idle before the real frame starts. That leftover HIGH then shifted every downstream bit by one. Add a leading-phantom-skip pass that drops any pair whose trailing LOW is a reset/idle gap. Bench result (100-LED OBJECT_FLED frame, MSB_LSB_A pattern A): - Before: First decode error at LED[0], 86/100 LEDs corrupt Edge sequence starts: H226 H580 L640 H586 (double-HIGH at start) - After: First decode error at LED[35], 65/100 LEDs corrupt Edge sequence starts: H580 L640 H586 L640 (clean alternation) LED[0]..LED[34] now decode correctly. Remaining mid-strip failures have a different signature (LSB-only errors, occasional 1-byte shifts) and are tracked separately under #3219 Phase 4 follow-up. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…nch tooling) Two small helpers used during the #3219 FlexPWM-RX bring-up session: - `ci/util/blocker_alert.py` — bold-red ANSI banner + distinctive 3-tone falling-rising chirp via `winsound.Beep` so the user notices when automation is blocked on a physical action (cable swap, power cycle). Falls back to POSIX terminal bell on non-Windows. Tones picked outside the Windows system-sound band (1175/440 Hz x2) so it doesn't get confused with Outlook/Slack notifications. - `ci/autoresearch/debug_object_fled_capture.py` — direct pyserial monitor that bypasses the autoresearch wrapper's `RESULT:`-only serial filter. Sends `runSingleTest` to a flashed Teensy and dumps every line the device emits (FL_WARN, REMOTE:, RESULT:) for a configurable window. Used to inspect FlexPWM RAW captures and edge-time dumps that the wrapper otherwise swallows. Both files include KBI001-compliant KeyboardInterrupt handlers. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ding byte shifts (#3219) Bench evidence on a live Teensy 4.0 (5-LED Pattern B): - BEFORE: one bit lands at high=580ns -- in neither T0H_max nor T1H_min range, so decodeBit() returns -1, decoder `continue`s past it without pushing to current_byte, every subsequent bit shifts forward by one position. Result: 1 decoder error -> 5 of 5 LEDs corrupt with R: 0x55 -> 0xAB (left-shift-by-one signature) propagated through the whole strip. - AFTER: classify by midpoint between t0h_max and t1h_min. Marginal bits still get classified (might be wrong by one bit), but byte alignment is preserved and the error is contained to that bit's byte instead of poisoning the rest of the frame. 100-LED OBJECT_FLED frame, 4 patterns (MSB_LSB_A/B/C/D): - BEFORE phantom-skip (the original wrapper-skip cheat removed): 86/100, 87/100, 80/100, 64/100 LEDs corrupt. - AFTER phantom-skip only (commit e3026d9): 65/100, 79/100, 87/100, 79/100 LEDs corrupt -- LED 0..34 clean. - AFTER midpoint classifier (this commit): 1-8/100 LEDs corrupt across 4 patterns, decoder errors = 0. 3 consecutive runs show non-deterministic per-LED errors, confirming the remaining failures are TX/RX clock-jitter at WS2812 timing tolerances -- not a software algorithm bug. The LOW-time check in the original decoder added no robustness for this protocol (both T0L and T1L overlap heavily at the FlexPWM-RX sample resolution); HIGH-only classification is more skew-tolerant. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…onesty (#3219) Two wrapper-side cheat #5 fixes that together prevent the wrapper from silently dropping the device's REMOTE response line and waiting 720 s for a response that arrived in milliseconds. ci/rpc_client.py::_wait_for_response: - Don't recurse into a fresh `_wait_for_response` on ACK -- that spawned a 2nd `read_lines()` producer behind the 1st in the single-worker `FbuildSerialAdapter._executor`. The 1st producer kept reading the serial port (including the final REMOTE response line) into a queue whose async consumer had already returned, and the 2nd producer never saw the line. Keep the SAME `async for` open and extend `current_deadline` on ACK instead. - Stop inflating `producer_budget = max(timeout, 600)`. The caller's `timeout` is the wall; the watchdog enforces the hard ceiling. ci/util/serial_interface.py::FbuildSerialAdapter.read_lines: - Signal the producer thread to exit promptly when the async generator consumer breaks/returns. Without this, the producer kept running for its full `timeout` window after the consumer was done, leaving zombie producers in the single-worker executor that blocked the NEXT call's producer. Together these eliminate the original 20-minute-wrapper-hang on a ~30 ms device-side test. Validated end-to-end against a Teensy 4.0 running OBJECT_FLED autoresearch: wrapper now reports the real PASS/FAIL within seconds and the previously-invisible per-pattern REMOTE messages flow through cleanly. Closes the wrapper half of #3219. The daemon-side throughput cap is fixed upstream in FastLED/fbuild#750. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…#3219) Two coupled changes turning `--timeout N` into an honest hard wall: ci/autoresearch/context.py: - Add `deadline_epoch` (set by `start_timeout_epoch()` right after deploy succeeds) and `remaining_seconds()` helper. Every downstream RPC call computes its per-call budget as `ctx.remaining_seconds(minimum=1.0)` so the user's `--timeout` is a TOTAL wall-clock budget, not a silently-multiplied per-call value. Pre-fix `--timeout 60` ran ~15 min wall-clock because `client.send(..., timeout=120.0)` was hardcoded at the call site and the wrapper's post-ACK extension added another 600 s on top. ci/autoresearch/phases.py: - Stamp `ctx.deadline_epoch` post-flash, pre-connect. Replace the hardcoded `timeout=120.0` at the runSingleTest call site with `ctx.remaining_seconds(minimum=1.0)`. Print a one-line advisory so the user sees the deadline armed. - Spawn a daemon `threading.Thread` watchdog at deadline+20s (NOT an asyncio task -- a wedged event loop or starved single-worker executor cannot starve a real OS thread). On expiry: emit a red `blocker_alert` banner, dump stack traces across every live thread (top 4 frames each via `sys._current_frames()`), best-effort close the serial port from a side-thread with a 2 s join cap, then `os._exit(2)` to bypass any stuck asyncio teardown. - `extend_autoresearch_watchdog_deadline(ctx, N)` grants extra runway to known-slow cleanup phases without disarming the bomb. Used in the run finally-block (10 s extension covering `await client.close()`); the safety net stays armed in case cleanup itself wedges. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
PR #3216 enabled `[FlexPWM CFG] / DMA / RAW / EDGE / E / DECODE` FL_WARN_F sites by default in this file to surface the bimodal-edge symptom during the #3066 Phase 4 investigation. The dual-circuit capture refactor + midpoint classifier fix in this PR series eliminated the bug those dumps were diagnosing. Now those 18 dump lines per frame are pure UART output volume: - on a 100-LED OBJECT_FLED autoresearch test they accounted for ~24 % of the device's per-pattern serial output; - the device's UART TX FIFO blocks once it fills, stalling the test between patterns; - even with the wrapper-side fix removing serial-bandwidth as the bottleneck, the device-side FL_WARN-induced TX backpressure remained measurable on bursty tests. Removed: - `#ifndef FL_RX_FLEXPWM_QUIET` opt-in block at file top (+ matching trailing `#undef FL_DEBUG`). - All 6 `#ifdef FL_DEBUG` blocks inside `decodeEdges`, `configureFlexPwm`, `configureDma`, and `buildEdgeTimesFromCaptures` (8 dump-line WARN sites total). If diagnostic dumps are needed again, gate them behind a new `-DFL_RX_FLEXPWM_VERBOSE=1` compile flag rather than hardcoded `#define FL_DEBUG 1` in this header (the latter caused header-pollution problems for downstream files that also test `#ifdef FL_DEBUG`). The two legitimate "Pin not supported on Teensy 4.x" FL_WARN_F sites in `factory_create_flexpwm_rx_channel` are preserved. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…3219) Two narrow scripts used during the #3219 bring-up session. Both bypass the autoresearch wrapper's serial filter so you can see every line the device emits in real time -- useful for diff'ing direct serial behavior against the wrapper's stream. - `ci/autoresearch/debug_find_pins.py` -- sends `ping` + `findConnectedPins` via direct pyserial and times the round-trip. Used to confirm device-side firmware was healthy when the wrapper was hanging. - `ci/autoresearch/debug_object_fled_small.py` -- sends `runSingleTest` with a configurable lane size. Used to isolate buffer-position- dependent decode failures (5-LED passes proved the bug was in the shared-register FIFO race, not a per-bit timing issue). Both keep their own KBI-001-compliant interrupt handlers and dump raw bytes for forensic analysis. Companion to the earlier `debug_object_fled_capture.py` helper. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthroughRemoves the Teensy 4 firmware wrapper-skip (synthetic PASS) and replaces it with a real FlexPWM dual-circuit rising/falling DMA capture pipeline with midpoint-based bit decoding. On the CI side, adds a post-flash deadline watchdog, wall-clock RPC timeout budgeting, serial producer stop-event cancellation, a ChangesCI autoresearch infrastructure
Teensy 4 FlexPWM RX dual-circuit capture
Sequence Diagram(s)sequenceDiagram
participant Deploy as _run_build_deploy
participant Ctx as RunContext
participant Watchdog as watchdog Thread
participant RPC as RpcClient._wait_for_response
participant Serial as FbuildSerialAdapter
Deploy->>Ctx: start_timeout_epoch()
Deploy->>Watchdog: start_autoresearch_watchdog(ctx)
note over Watchdog: armed: deadline_epoch + WATCHDOG_GRACE_SECONDS
loop per RPC command
Deploy->>Ctx: remaining_seconds(minimum=1.0)
Ctx-->>Deploy: dynamic budget
Deploy->>RPC: send(cmd, timeout=budget)
RPC->>Serial: read_lines(timeout=remaining)
Serial-->>RPC: lines
alt ACK received
RPC->>RPC: saw_ack=True, keep consuming until current_deadline
end
RPC-->>Deploy: result
end
Deploy->>Ctx: extend_autoresearch_watchdog_deadline(ctx, 10s)
Deploy->>RPC: client.close()
alt deadline + grace exceeded (no close)
Watchdog->>Watchdog: blocker_alert + stack dump
Watchdog->>Watchdog: os._exit(2)
end
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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 |
#3219) Pulls in FastLED/fbuild#750 (closes FastLED/fbuild#749) -- the daemon- side fix for the serial WebSocket bridge that silently dropped lines under sustained TX bursts. Pre-#750 the daemon sent one WS frame per serial line, the broadcast channel lagged on ~320-line bursts (e.g. 4-pattern OBJECT_FLED autoresearch), and lines vanished via RecvError::Lagged. This is the upstream half of the FastLED #3219 fix. The wrapper-side half landed in the prior commits on this branch (rpc_client.py, serial_interface.py, autoresearch/{context,phases}.py). Verified: `uv run fbuild --version` -> `fbuild 2.3.0`, lint stays green, `bash autoresearch teensy40 --object-fled --strip-sizes 5` completes end-to-end with 4/4 patterns through the wrapper. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
ci/autoresearch/phases.py (1)
2594-2596:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winHardcoded timeout value in error message.
The error message says "No response within {120}s" but the actual timeout is now dynamic via
ctx.remaining_seconds(). This should reference the actual timeout used.🐛 Proposed fix
except RpcTimeoutError: print(f"{Fore.RED}\u274c RPC timeout{Style.RESET_ALL}") - print(f" No response within {120}s") + print(f" No response within remaining deadline") test_failed = TrueOr capture the timeout value before the call:
rpc_timeout = ctx.remaining_seconds(minimum=1.0) response = await client.send( method, args=params if params else [], timeout=rpc_timeout, ) # ... in except: print(f" No response within {rpc_timeout:.1f}s")🤖 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 `@ci/autoresearch/phases.py` around lines 2594 - 2596, The error message in the RpcTimeoutError exception handler contains a hardcoded timeout value of 120 seconds, but the actual timeout is determined dynamically using ctx.remaining_seconds(). To fix this, capture the timeout value before making the RPC call by assigning ctx.remaining_seconds(minimum=1.0) to a variable (e.g., rpc_timeout), use that variable when calling client.send() with the timeout parameter, and then reference that same variable in the print statement that displays the error message instead of the hardcoded 120 value.
🧹 Nitpick comments (2)
src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp (1)
270-284: 🧹 Nitpick | 🔵 Trivial | 💤 Low valueDead code:
bit < 0check is now unreachable.Since
decodeBit()anddecodeBitFromHigh()now always return 0 or 1 (never -1), the initializationint bit = -1followed by the if-else that always assignsbitmeans the check at lines 281-284 can never be true. Consider removing this dead branch or, if retained for defensive coding, add a comment explaining it's a safety net.♻️ Optional cleanup
u32 high_ns = edges[i].ns; - int bit = -1; + int bit; if (i + 1 < edges.size() && !edges[i + 1].high) { u32 low_ns = edges[i + 1].ns; bit = decodeBit(high_ns, low_ns, timing); i += 2; } else { bit = decodeBitFromHigh(high_ns, timing); i += 1; } ++total_bits; - if (bit < 0) { - ++error_count; - continue; - } - current_byte = (current_byte << 1) | static_cast<u8>(bit);🤖 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 `@src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp` around lines 270 - 284, The code initializes bit to -1 but the subsequent if-else block always assigns a value from either decodeBit() or decodeBitFromHigh(), both of which now only return 0 or 1, never -1. This makes the check for bit < 0 unreachable dead code. Either remove the entire if block that checks bit < 0 and increments error_count, or if you want to keep it for defensive coding purposes, add a comment explaining it's a safety net for unexpected behavior from the decoding functions.ci/rpc_client.py (1)
123-129: 🧹 Nitpick | 🔵 TrivialRemove the now-unused
ASYNC_POST_ACK_TIMEOUTconstant.
ASYNC_POST_ACK_TIMEOUTwas removed from active code during the deadline rework (see line 576 comment). It is no longer referenced anywhere in the codebase except in the explanatory comment about why it was removed. The constant definition at line 129 can be safely deleted.🤖 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 `@ci/rpc_client.py` around lines 123 - 129, The ASYNC_POST_ACK_TIMEOUT constant is no longer referenced in the active codebase following the deadline rework and only appears in explanatory comments. Remove the entire constant definition (the ASYNC_POST_ACK_TIMEOUT variable assignment and its associated docstring comment) from the file since it is unused and no longer needed.
🤖 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 `@ci/autoresearch/debug_find_pins.py`:
- Line 73: The string literal in the debug_find_pins.py file contains an unused
f-string prefix that triggers Ruff rule F541. Remove the f prefix from the
string literal that reads "NO RESPONSE in 10s -- firmware-side hang" since the
string does not contain any variable interpolation or curly braces. Simply
convert it from an f-string to a regular string literal.
- Around line 58-62: The response detection logic uses fragile substring
matching that breaks with JSON formatting changes. Replace the substring-based
checks with proper JSON parsing: parse the text as JSON, then check if the
parsed object has an "id" field equal to 2 and contains either "result" or
"error" key. This makes the detection robust to whitespace variations and
properly validates the response structure instead of relying on text patterns.
- Line 14: The `serial` module is imported in the debug scripts (such as the
import statement in debug_find_pins.py) but the `pyserial` package is not
declared as a dependency in the project configuration. To fix this, add
`pyserial` to the dependencies list in `pyproject.toml` to ensure the module is
available in fresh environments and prevent ModuleNotFoundError when the debug
scripts are executed.
---
Outside diff comments:
In `@ci/autoresearch/phases.py`:
- Around line 2594-2596: The error message in the RpcTimeoutError exception
handler contains a hardcoded timeout value of 120 seconds, but the actual
timeout is determined dynamically using ctx.remaining_seconds(). To fix this,
capture the timeout value before making the RPC call by assigning
ctx.remaining_seconds(minimum=1.0) to a variable (e.g., rpc_timeout), use that
variable when calling client.send() with the timeout parameter, and then
reference that same variable in the print statement that displays the error
message instead of the hardcoded 120 value.
---
Nitpick comments:
In `@ci/rpc_client.py`:
- Around line 123-129: The ASYNC_POST_ACK_TIMEOUT constant is no longer
referenced in the active codebase following the deadline rework and only appears
in explanatory comments. Remove the entire constant definition (the
ASYNC_POST_ACK_TIMEOUT variable assignment and its associated docstring comment)
from the file since it is unused and no longer needed.
In `@src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp`:
- Around line 270-284: The code initializes bit to -1 but the subsequent if-else
block always assigns a value from either decodeBit() or decodeBitFromHigh(),
both of which now only return 0 or 1, never -1. This makes the check for bit < 0
unreachable dead code. Either remove the entire if block that checks bit < 0 and
increments error_count, or if you want to keep it for defensive coding purposes,
add a comment explaining it's a safety net for unexpected behavior from the
decoding functions.
🪄 Autofix (Beta)
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
Run ID: 9dd6cf82-508e-4e93-a895-db325fda4312
📒 Files selected for processing (12)
ci/autoresearch/context.pyci/autoresearch/debug_find_pins.pyci/autoresearch/debug_object_fled_capture.pyci/autoresearch/debug_object_fled_small.pyci/autoresearch/phases.pyci/rpc_client.pyci/tests/test_autoresearch_phases.pyci/util/blocker_alert.pyci/util/serial_interface.pyexamples/AutoResearch/AutoResearchRemoteRunSingleTest.cpppyproject.tomlsrc/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp
💤 Files with no reviewable changes (1)
- examples/AutoResearch/AutoResearchRemoteRunSingleTest.cpp
| import sys | ||
| import time | ||
|
|
||
| import serial |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Dependency manifests present:"
fd -HI '^(pyproject\.toml|requirements.*\.txt|setup\.cfg|Pipfile|uv\.lock)$'
echo
echo "Searching manifests for serial/pyserial declarations:"
rg -n --iglob 'pyproject.toml' --iglob 'requirements*.txt' --iglob 'setup.cfg' --iglob 'Pipfile' --iglob 'uv.lock' '\b(pyserial|serial)\b'Repository: FastLED/FastLED
Length of output: 436
🏁 Script executed:
# Check the dependencies section of pyproject.toml
head -150 pyproject.toml | tail -70Repository: FastLED/FastLED
Length of output: 4108
🏁 Script executed:
# Find the debug scripts mentioned and check their imports
fd -e py 'debug_find_pins|debug_.*\.py' ci/Repository: FastLED/FastLED
Length of output: 245
🏁 Script executed:
# Search for actual pyserial/serial package declarations in pyproject.toml dependencies
rg -A 5 -B 5 '^\[project\]|^\[tool\.poetry\.dependencies\]|^dependencies\s*=' pyproject.toml | head -100Repository: FastLED/FastLED
Length of output: 524
🏁 Script executed:
# Get the complete dependencies list from pyproject.toml
cat pyproject.toml | sed -n '/^\[project\]/,/^\[/p' | sed -n '/^dependencies/,/^]/p'Repository: FastLED/FastLED
Length of output: 11400
🏁 Script executed:
# Check the imports in debug_find_pins.py
head -20 ci/autoresearch/debug_find_pins.pyRepository: FastLED/FastLED
Length of output: 558
🏁 Script executed:
# Check the other debug scripts for serial imports
head -20 ci/autoresearch/debug_object_fled_capture.py
head -20 ci/autoresearch/debug_object_fled_small.pyRepository: FastLED/FastLED
Length of output: 1111
Declare pyserial dependency for the new debug scripts.
serial is imported in the debug scripts (debug_find_pins.py, debug_object_fled_small.py, and others), but pyserial is not listed in pyproject.toml dependencies. In a fresh environment, this causes ModuleNotFoundError at import time and makes the debug tooling unusable.
🤖 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 `@ci/autoresearch/debug_find_pins.py` at line 14, The `serial` module is
imported in the debug scripts (such as the import statement in
debug_find_pins.py) but the `pyserial` package is not declared as a dependency
in the project configuration. To fix this, add `pyserial` to the dependencies
list in `pyproject.toml` to ensure the module is available in fresh environments
and prevent ModuleNotFoundError when the debug scripts are executed.
| if ( | ||
| '"id":2' in text | ||
| and text.startswith(("REMOTE:", "{")) | ||
| and ("result" in text or "error" in text) | ||
| ): |
There was a problem hiding this comment.
Make response detection JSON-aware instead of substring-based.
Current matching can miss valid responses if formatting changes (e.g., spacing around "id": 2) and incorrectly report firmware-side hangs.
Proposed fix
- if (
- '"id":2' in text
- and text.startswith(("REMOTE:", "{"))
- and ("result" in text or "error" in text)
- ):
+ payload = text[7:].strip() if text.startswith("REMOTE:") else text
+ try:
+ message = json.loads(payload)
+ except json.JSONDecodeError:
+ message = None
+
+ if (
+ isinstance(message, dict)
+ and message.get("id") == 2
+ and ("result" in message or "error" in message)
+ ):🤖 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 `@ci/autoresearch/debug_find_pins.py` around lines 58 - 62, The response
detection logic uses fragile substring matching that breaks with JSON formatting
changes. Replace the substring-based checks with proper JSON parsing: parse the
text as JSON, then check if the parsed object has an "id" field equal to 2 and
contains either "result" or "error" key. This makes the detection robust to
whitespace variations and properly validates the response structure instead of
relying on text patterns.
|
|
||
| if not seen_response: | ||
| print( | ||
| f"\n[direct] NO RESPONSE in 10s -- firmware-side hang", |
There was a problem hiding this comment.
Drop the unused f prefix in this string literal.
This triggers Ruff F541.
Proposed fix
- f"\n[direct] NO RESPONSE in 10s -- firmware-side hang",
+ "\n[direct] NO RESPONSE in 10s -- firmware-side hang",📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| f"\n[direct] NO RESPONSE in 10s -- firmware-side hang", | |
| "\n[direct] NO RESPONSE in 10s -- firmware-side hang", |
🧰 Tools
🪛 Ruff (0.15.17)
[error] 73-73: f-string without any placeholders
Remove extraneous f prefix
(F541)
🤖 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 `@ci/autoresearch/debug_find_pins.py` at line 73, The string literal in the
debug_find_pins.py file contains an unused f-string prefix that triggers Ruff
rule F541. Remove the f prefix from the string literal that reads "NO RESPONSE
in 10s -- firmware-side hang" since the string does not contain any variable
interpolation or curly braces. Simply convert it from an f-string to a regular
string literal.
Source: Linters/SAST tools
…ed (fbuild#755) When an `--lpuart`-style request hits a Teensy 4 build that doesn't have the LPUART driver enrolled at boot, the firmware used to return a generic "DriverSetupFailed: Failed to set LPUART as exclusive driver" with no hint of what IS available. Drivers like LPUART are scaffolded under `src/platforms/arm/teensy/.../lpuart/` but not yet implemented (FastLED #3157 tracks the engine work, #3182 the ISR-chunked streaming). Pre-#3341 the wrapper masked this with a wrapper-skip + synthetic PASS. PR #3341 removed the wrapper-skip; the generic error became visible. This commit makes that error self-diagnosing. New error shape: {"error":"DriverNotRegistered", "message":"Driver 'LPUART' is not registered on this build. Registered drivers: SPI_UNIFIED, FLEX_IO, OBJECT_FLED, BIT_BANG"} Implementation: queries `ChannelManager::instance().getDriverInfos()` on the failure path, filters to `enabled` drivers, joins the names with commas. ~15 LOC, no behavior change for the happy path. The ChannelManager API already existed (#2469 cleanup). The longer-term LPUART fix needs the actual engine implementation (FastLED #3157). This change just makes the missing-driver diagnostic honest so future "why isn't X working" sessions don't waste time on generic-error chasing. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Closes #3219.
Summary
End-to-end fix for the Teensy 4 autoresearch wrapper-response-miss + downstream RX decode failures. Splits the problem into three independently-correct layers:
FastLED — Teensy 4 FlexPWM RX driver (
src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp):wait(): returnsTIMEOUTwhen CITER never moved (was always returningSUCCESS, which madecapture()decode a stale/empty buffer and report fake errors).buildEdgeTimesFromCaptures: IOMUXC pad-mux switch + DMA arm sometimes latches a stray rising+falling pair whose HIGH duration looks like a real T0H (~226 ns) but is followed by a multi-µs idle. The original loop pushed that phantom HIGH unconditionally and shifted every downstream bit by one. Now we drop any leading pair whose trailing LOW is a reset/idle gap.decodeBit/decodeBitFromHighno longer return-1on a marginal pulse. A single edge-of-tolerance bit no longer makes the decodercontinuepast it and shift every downstream bit by one. Eliminated the cascading-byte-shift signature.[FlexPWM CFG]/DMA/RAW/EDGE/E/DECODE). They served the bimodal-edge investigation that's now closed. Their UART output volume contributed to device-side TX backpressure on bursty tests.FastLED — autoresearch wrapper (
ci/rpc_client.py,ci/util/serial_interface.py,ci/autoresearch/context.py,ci/autoresearch/phases.py):_wait_for_responseno longer recurses on ACK. The old recursive call spawned a 2ndread_lines()producer behind the 1st in the single-workerFbuildSerialAdapter._executor, and the device's final REMOTE response landed in the 1st producer's now-dead queue. Now the sameasync forstays open with extendedcurrent_deadlineon ACK.FbuildSerialAdapter.read_linessignals astop_eventto the producer thread when the async consumer exits, preventing zombie producers that drain serial bytes into a dead queue.--timeout Nis now a hard total post-flash budget, not a silently-inflated per-call value.ctx.deadline_epochis stamped right after deploy succeeds; everyclient.send()usesctx.remaining_seconds(minimum=1.0). Previously--timeout 60ran 15 + minutes because the runSingleTest call hardcodedtimeout=120.0and the wrapper added 600 s post-ACK on top.deadline + 20 s(NOT an asyncio task — a wedged event loop or starved executor cannot starve a real OS thread). On expiry: redblocker_alertbanner + per-thread stack-dump (top 4 frames) + best-effort serial close +os._exit(2).extend_autoresearch_watchdog_deadline(ctx, N)grants extra runway to known-slow cleanup phases without disarming the bomb.ci/autoresearch/debug_*.pypyserial helpers used during the bring-up session, bypassing the wrapper's serial filter for forensic comparison.fbuild — daemon-side serial WS batching (FastLED/fbuild#750 — merged, released as fbuild v2.3.0):
tokio::select!into concurrent reader / writer / inbound tasks. Pre-fix, each serial line became its own WebSocket frame; broadcast channel lagged and silently dropped lines mid-burst. The split + adjacent-Data coalescing eliminates the drop and adapts batch size to socket saturation.Bench validation (Teensy 4.0, COM20)
--object-fled --strip-sizes 5 --timeout 60--timeoutflag respectedctx.deadline_epoch)NOT in this PR (intentional)
pyproject.tomlfbuild pin bump: separate follow-up commit after this PR is reviewed, so the fbuild v2.3.0 dependency change can be reviewed in isolation.[CORRUPTION @ LED X]dump (9 lines per mismatch) is now the dominant UART output on bursty 100-LED tests. Rate-limit to first N per pattern in a follow-up.Test plan
bash test --cpp— 337/337 unit tests passbash lint— ruff, ty, C++ lint all greenbash autoresearch teensy40 --object-fled --strip-sizes 5 --timeout 60on hardware → all 4 patterns pass through wrapper in seconds🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Dependencies