Skip to content

fix(teensy4/autoresearch): honest FlexPWM RX + wrapper deadline + watchdog (closes #3219) - #3341

Merged
zackees merged 9 commits into
masterfrom
goal/3219-flexpwm-rx-test
Jun 22, 2026
Merged

zackees merged 9 commits into
masterfrom
goal/3219-flexpwm-rx-test

Conversation

@zackees

@zackees zackees commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

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:

  1. FastLED — Teensy 4 FlexPWM RX driver (src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp):

    • Honest wait(): returns TIMEOUT when CITER never moved (was always returning SUCCESS, which made capture() decode a stale/empty buffer and report fake errors).
    • Skip leading phantom edge pair in 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.
    • Midpoint bit classifier: decodeBit/decodeBitFromHigh no longer return -1 on a marginal pulse. A single edge-of-tolerance bit no longer makes the decoder continue past it and shift every downstream bit by one. Eliminated the cascading-byte-shift signature.
    • Removed PR feat(flexpwm-rx): enable Phase 4 raw-capture dumps by default (#3066) #3216's per-frame debug dumps ([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.
  2. FastLED — autoresearch wrapper (ci/rpc_client.py, ci/util/serial_interface.py, ci/autoresearch/context.py, ci/autoresearch/phases.py):

    • _wait_for_response no longer recurses on ACK. The old recursive call spawned a 2nd read_lines() producer behind the 1st in the single-worker FbuildSerialAdapter._executor, and the device's final REMOTE response landed in the 1st producer's now-dead queue. Now the same async for stays open with extended current_deadline on ACK.
    • FbuildSerialAdapter.read_lines signals a stop_event to the producer thread when the async consumer exits, preventing zombie producers that drain serial bytes into a dead queue.
    • --timeout N is now a hard total post-flash budget, not a silently-inflated per-call value. ctx.deadline_epoch is stamped right after deploy succeeds; every client.send() uses ctx.remaining_seconds(minimum=1.0). Previously --timeout 60 ran 15 + minutes because the runSingleTest call hardcoded timeout=120.0 and the wrapper added 600 s post-ACK on top.
    • Daemon-thread watchdog at deadline + 20 s (NOT an asyncio task — a wedged event loop or starved executor cannot starve a real OS thread). On expiry: red blocker_alert banner + 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.
    • Three small ci/autoresearch/debug_*.py pyserial helpers used during the bring-up session, bypassing the wrapper's serial filter for forensic comparison.
  3. fbuild — daemon-side serial WS batching (FastLED/fbuild#750 — merged, released as fbuild v2.3.0):

    • Split the daemon's single-loop 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)

Scenario Before After
--object-fled --strip-sizes 5 --timeout 60 wrapper hung 20+ min, then watchdog kill 42 s wall, exit 0, 4/4 patterns pass, device duration 13 ms
Honest 5-LED 4-pattern decode reported fake PASS via wrapper-skip block All 4 patterns byte-match
Pattern A LED-error rate (100 LEDs) 86/100 corrupt 1-8/100 corrupt (random, jitter-level)
Wrapper-side --timeout flag respected NO (hardcoded 120 s override) YES (hard wall via ctx.deadline_epoch)

NOT in this PR (intentional)

  • pyproject.toml fbuild pin bump: separate follow-up commit after this PR is reviewed, so the fbuild v2.3.0 dependency change can be reviewed in isolation.
  • Wrapper unit + integration tests for the deadline/watchdog/reader+writer pieces: tracked as task Support single-color multi-chip brightness variations #20 on the goal-list; recommended as a follow-up commit on this same branch.
  • Device-side AutoResearchTest.cpp diagnostic verbosity rate-limiting: the per-[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 pass
  • bash lint — ruff, ty, C++ lint all green
  • bash autoresearch teensy40 --object-fled --strip-sizes 5 --timeout 60 on hardware → all 4 patterns pass through wrapper in seconds
  • Direct-pyserial baseline confirms device-side firmware produces correct REMOTE response in milliseconds
  • CI green on this PR

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added three new debug scripts for hardware diagnostics and testing.
    • Introduced blocker alert system for CI/automation notifications.
    • Implemented watchdog timeout mechanism to prevent hangs during teardown.
  • Bug Fixes

    • Improved async RPC timeout handling with wall-clock deadline tracking.
    • Enhanced hardware signal capture with dual-circuit rising/falling edge design.
    • Fixed serial interface thread coordination to prevent data queue interference.
  • Tests

    • Added unit test for driver selection validation.
  • Dependencies

    • Updated fbuild dependency to 2.3.0.

zackees and others added 8 commits June 22, 2026 00:15
…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]>
@coderabbitai

coderabbitai Bot commented Jun 22, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Removes 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 blocker_alert utility, and three standalone serial debug scripts. fbuild is bumped to 2.3.0.

Changes

CI autoresearch infrastructure

Layer / File(s) Summary
blocker_alert visual/audible utility
ci/util/blocker_alert.py
Implements blocker_alert() with a bold red ANSI stderr banner, Windows winsound 3-tone chirp, non-Windows terminal bell fallback, KeyboardInterrupt routing, and a __main__ smoke test.
RunContext deadline fields + serial stop_event cancellation
ci/autoresearch/context.py, ci/util/serial_interface.py
Adds deadline_epoch/_watchdog_task to RunContext with start_timeout_epoch() and remaining_seconds(); reworks FbuildSerialAdapter.read_lines producer to poll a stop_event with capped 0.25 s inner reads and adds consumer try/finally to set stop_event on early generator exit.
RpcClient _wait_for_response wall-clock deadline rework
ci/rpc_client.py
Introduces saw_ack state and a single current_deadline; replaces elapsed-time checks with absolute deadline checks; continues consuming after ACK within the same loop instead of recursively reinvoking with an extended post-ACK timeout.
Watchdog mechanism and phases wiring
ci/autoresearch/phases.py
Defines WATCHDOG_GRACE_SECONDS; adds _autoresearch_watchdog_thread (banner + stack dump + serial close + os._exit(2)), start_autoresearch_watchdog, and extend_autoresearch_watchdog_deadline; arms epoch/watchdog post-flash; switches per-RPC timeout to ctx.remaining_seconds(minimum=1.0); extends watchdog by 10 s before teardown.
Teensy 4 driver narrowing, wrapper-skip removal, and test
ci/autoresearch/phases.py, examples/AutoResearch/AutoResearchRemoteRunSingleTest.cpp, ci/tests/test_autoresearch_phases.py
Narrows --all to OBJECT_FLED/FLEX_IO/LPUART for Teensy 4; removes synthetic __skip_with_pass from RPC loop; deletes #if defined(FL_IS_TEENSY_4X) early-return block from firmware runSingleTestImpl; adds unit test asserting only real drivers and runSingleTest methods with no __skip_with_pass.
fbuild bump to 2.3.0
pyproject.toml
Updates fbuild pin from 2.2.28 to 2.3.0 and documents the serial/WebSocket bridge refactor in the dependency history.
Standalone serial debug scripts
ci/autoresearch/debug_find_pins.py, ci/autoresearch/debug_object_fled_capture.py, ci/autoresearch/debug_object_fled_small.py
Adds debug_find_pins.py (ping + findConnectedPins with 10 s firmware-hang detection), debug_object_fled_capture.py (full serial capture via setPins + runSingleTest firehose log), and debug_object_fled_small.py (lane-size configurable OBJECT_FLED isolation).

Teensy 4 FlexPWM RX dual-circuit capture

Layer / File(s) Summary
FlexPWM hardware reconfiguration and DMA TCD programming
src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp
Updates pipeline/CVAL register comments for dual-circuit capture; rewrites configureFlexPwm() to EDGA0/EDGA1 rising/falling with CA1DE/CB1DE DMA enable; replaces DMAChannel helper calls with direct TCD field programming (SADDR, SOFF, NBYTES minor-loop rewind, CITER/BITER, CSR) for paired CVAL2/CVAL3 reads per DMA request.
Bit decoder and edge reconstruction overhaul
src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp
Replaces dual-duration threshold decoder (could return -1) with midpoint HIGH-only classifier (always 0/1); updates decodeEdges() to pair HIGH with following LOW or fall back to HIGH-only; overhauls buildEdgeTimesFromCaptures() to scale by pair size, skip leading phantom pair, rebuild edges from rise/fall deltas with long-LOW-gap skipping; removes FL_DEBUG decode dump blocks.
DMA wait timeout honesty and debug cleanup
src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp
Tracks initial_citer/last_citer in wait() to detect actual DMA progress; returns RxWaitResult::TIMEOUT when CITER never advanced; removes default-on FL_DEBUG instrumentation and trailing FL_DEBUG_DEFINED_BY_RX_FLEXPWM undef block.

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
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • FastLED/FastLED#3062: Directly modifies RpcClient._wait_for_response ACK timeout handling in ci/rpc_client.py — the same function this PR rewrites to use a single wall-clock deadline.
  • FastLED/FastLED#3217: Added the __skip_with_pass synthetic PASS / Teensy 4 wrapper-skip logic in ci/autoresearch/phases.py that this PR removes.
  • FastLED/FastLED#3216: Enabled FL_DEBUG by default in rx_flexpwm_channel.cpp.hpp for raw-capture dumps; this PR removes those same default-on FL_DEBUG instrumentation blocks.

Poem

🐰 A watchdog now barks at the deadline wall,
dual circuits catch rising and falling — all!
No more fake PASS where the firmware once fled,
real edges decoded by midpoint instead.
The serial producer stops on a signal, neat —
every Teensy byte validated, the skip obsolete! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 65.52% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly identifies the three main layers being fixed (teensy4 device-side, autoresearch wrapper, and watchdog) and references the closed issue #3219, accurately summarizing the primary changes.
Linked Issues check ✅ Passed The PR comprehensively addresses the Phase 4 root blocker from #3219 by fixing FlexPWM RX bimodal-edge captures, wrapper-side response handling race conditions, and deadline enforcement with watchdog protection, enabling honest byte-level validation instead of wrapper-skip substitutions.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the linked issue #3219: device-side FlexPWM RX fixes, wrapper-side deadline and watchdog implementations, removal of wrapper-skip blocks, fbuild dependency update for daemon-side WebSocket batching, and debug utilities for bring-up support.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 goal/3219-flexpwm-rx-test

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 and usage tips.

#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]>

@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

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 win

Hardcoded 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 = True

Or 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 value

Dead code: bit < 0 check is now unreachable.

Since decodeBit() and decodeBitFromHigh() now always return 0 or 1 (never -1), the initialization int bit = -1 followed by the if-else that always assigns bit means 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 | 🔵 Trivial

Remove the now-unused ASYNC_POST_ACK_TIMEOUT constant.

ASYNC_POST_ACK_TIMEOUT was 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

📥 Commits

Reviewing files that changed from the base of the PR and between bdf7550 and 7576dc4.

📒 Files selected for processing (12)
  • ci/autoresearch/context.py
  • ci/autoresearch/debug_find_pins.py
  • ci/autoresearch/debug_object_fled_capture.py
  • ci/autoresearch/debug_object_fled_small.py
  • ci/autoresearch/phases.py
  • ci/rpc_client.py
  • ci/tests/test_autoresearch_phases.py
  • ci/util/blocker_alert.py
  • ci/util/serial_interface.py
  • examples/AutoResearch/AutoResearchRemoteRunSingleTest.cpp
  • pyproject.toml
  • src/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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 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 -70

Repository: 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 -100

Repository: 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.py

Repository: 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.py

Repository: 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.

Comment on lines +58 to +62
if (
'"id":2' in text
and text.startswith(("REMOTE:", "{"))
and ("result" in text or "error" in text)
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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

@zackees
zackees merged commit e21048a into master Jun 22, 2026
13 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 22, 2026
zackees added a commit that referenced this pull request Jun 22, 2026
…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]>
@zackees
zackees deleted the goal/3219-flexpwm-rx-test branch August 21, 2026 19:16
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.

[meta][burndown] Teensy 4 autoresearch — every driver byte-level RX validated, no wrapper-skip

1 participant