Repository navigation
Delegate all flashing to fbuild + LPC845 drivers + ban raw pyserial in AutoResearch - #3601
Conversation
…loses #3580) `bash autoresearch lpc845 --dma-spi` is now fully green on the LPC845-BRK: build → fbuild deploy (probe-rs SWD) → all four bench RPCs PASS, including the async proof (978 CPU beacon toggles during a 512-byte DMA stream) and a throughput measurement matching the FIFO-less-IP physical model. Six independent silicon bugs, each masking the next, bisected with the WWDT NMI backtrace + breadcrumb prints + bounded-spin register snapshots: 1. **DMA0->SRAMBASE never programmed.** The driver "punted to the SDK conventional address" that nothing ever set — the DMA engine fetched channel descriptors from the FLASH VECTOR TABLE at address 0 and wrote through garbage pointers, corrupting .bss (the original PC=<static object> wedge). New shared `lpc_dma_descriptor_table.h` owns a FL_ALIGNAS(512) 25-channel table; both the SPI driver and the SCT+DMA runtime call `fl::lpc::ensureDmaSramBase()` at init, and `configureChannelDescriptor()` now returns bool so SETVALID can never arm an unwritten descriptor. 2. **SPI peripheral never clocked.** init() assumed "the user's startup enables the SPI clock + SWM routing" — nothing did, and reading an unclocked LPC peripheral stalls the AHB bus forever (no fault; the load never retires). init() now owns SYSAHBCLKCTRL0 (SPI0/1 + SWM), PRESETCTRL0 reset release, and SWM PINASSIGN routing of SCK/MOSI to the template pins. 3. **Wrong DMA channel.** Default was 4, citing a nonexistent "UM11029 Table 80". Ground truth (UM11029 §16.3.3 Table 296): channel 4 is USART2_RX; SPI0_TX is channel 11, SPI1_TX is 13. The armed channel sat waiting for a request line that never fires. 4. **Channel never TRIGGERED.** XFERCFG.SWTRIG was 0 on the belief that "the SPI TXRDY hardware-triggers it" — but PERIPHREQEN requests only PACE transfers; the channel must first be triggered (CTLSTAT.TRIG), and with HWTRIGEN=0 only software can do that. Register snapshot showed CFGVALID=1, TXRDY=1, TRIG=0, XFERCOUNT frozen. SWTRIG=1. 5. **SPI function clock unselected.** SYSCON->FCLKSEL[9] (SPI0) resets to "none": the register bus worked but the shift engine had no clock — first DMA write accepted, then STAT=0 and frozen mid-shift. init() selects main_clk. 6. **Frame never closed after a stream.** DMA writes plain TXDAT (no per-unit EOT), so the master held the frame open and MSTIDLE never re-asserted — every handler call after a completed stream wedged in its entry waitFully() (bench alternated PASS/WEDGE via watchdog reboots). Per-byte sticky EOT fixed it but cost 39% throughput in SSEL gaps (4 MHz → 2.46 MHz effective, measured); final fix closes the frame once in waitFully() via STAT.ENDTRANSFER after the DMA drains. Bench-side changes: - `AutoResearchSpiDma.h`: bounded spin (2M iters) returns a DMA/SPI register snapshot CSV instead of wedging into the watchdog; stale "fbuild SystemInit configures SPI0" comment corrected. - `test_lpc_dma_spi.py`: SCK check remodeled as effective throughput. The LPC845 SPI is FIFO-less — each byte costs 8/SCK shift + ~0.76 us DMA refill (measured), so wire SCK 4 MHz yields ~2.9 MHz effective. The old ±25%-of-wire-SCK band was physically unattainable. - `phases.py`: channel-override hints corrected (SPI1=13, SPI0=11). Acceptance (LPC845-BRK, COM10, 2026-07-02): dmaSpiTransferOnce(32) PASS — 109 us (theoretical 64) dmaSpiTransferOnce(256) PASS — 716 us (theoretical 512) dmaSpiTransferOverlap PASS — 1411 us, 978 CPU toggles during DMA dmaSpiMeasureSck PASS — 2.894 MHz effective vs 2.76 model PASS — #3456 SPI+DMA async bench green. Closes #3580. Refs #3456, #3453 (Phase 1 silicon gate), #3517 (Phase B.1 acceptance — now genuinely met), #3437 (vendor-PAL policy). Co-Authored-By: Claude Fable 5 <[email protected]>
Port the silicon-validated init block from the DMA sibling (#3580) to ARMHardwareSPIOutput<>: SYSAHBCLKCTRL0 (SPI0/1 + SWM), PRESETCTRL0 reset release, FCLKSEL function-clock select, and SWM SCK/MOSI routing. Without it the first spi->STAT read stalls the AHB bus forever — the polled driver had the identical "user's startup does the plumbing" contract that nothing honors. LPC845-gated; LPC804 keeps the old contract until it gets vendor-PAL bring-up of its own. Compile-verified in the lpc845 AutoResearch build (the DMA harness includes this header). Refs #3580, #3453. Co-Authored-By: Claude Fable 5 <[email protected]>
## ISR-refillable drivers (#3453 follow-up) - **`lpc_dma_isr.h`** — shared DMA0 interrupt hub: one strong `DMA0_IRQHandler` (the LPC845 has a single DMA IRQ line for all 25 channels) dispatching `INTA` completion bits to per-channel callbacks registered via `fl::lpc::registerDmaChannelIsr()`. Opt-in via `FASTLED_LPC_DMA_ISR=1`; requires the ACLPC core with named weak IRQ vector slots (framework-arduino-lpc8xx#38, merging alongside). - **SPI streaming** — `ARMHardwareSPIOutputDMA::kickDmaStreamAsync()`: ping-pong halves of the encode buffer; the completion ISR arms the pre-encoded other half (~2 µs wire gap) and refills the freed one, so frames larger than the buffer stream without blocking the main thread. Bench RPC `dmaSpiStreamOverlap` (gated on the ISR build) beacon-toggles across a 1024-byte multi-chunk stream. - **UART async TX** — new `ARMHardwareUARTOutputDMA<TX_PIN, BAUD>` (`uart_arm_lpc_dma.h`): USART1 (or 2) TX paced by its fixed DMA request channel (ch3/ch5 per UM11029 Table 296), chunks chained from the ISR, DMA reading the caller's buffer in place (no staging copy). Owns its full plumbing (clock, reset, FCLKSEL, SWM, OSR/BRG baud search) per the #3580 lesson. USART0 stays free as the console — the "drive a data lane and keep printing" capability. - **Bench**: `bash autoresearch lpc845 --dma-uart` — new harness (`AutoResearchUartDma.h`, `uartDmaStreamOnce`/`Overlap` RPCs, 2048- byte streams = two descriptors so completion REQUIRES the ISR chain), host runner `test_lpc_uart_dma.py`, args/phases wiring, define injection (`FASTLED_LPC_UART_DMA=1` + `FASTLED_LPC_DMA_ISR=1`). ## CodeRabbit review fixes (PR #3550) - `test_autoresearch_phases.py`: mock patches the renamed `_build_and_deploy_nxplpc` (was silently missing the LPC path). - Watchdog tick math: u64 intermediate — `60000 ms * 125 kHz` wraps u32 above ~34.3 s and programmed a much shorter window. - `FL_LPC_WDT_NMI_BACKTRACE` → `FL_LPC_WATCHDOG_NMI_BACKTRACE` (spelled-out vocabulary; macro is new in this PR). Silicon status: SPI sync bench remains green (rebuilt, RAM 11.41 KB); the ISR paths await the ACLPC weak-alias core (framework#38) + fbuild pin bump before on-device validation. Refs #3453, #3580, framework-arduino-lpc8xx#38. Co-Authored-By: Claude Fable 5 <[email protected]>
…trace hooks Silicon-hardening from the first ISR-streaming bring-up session: - **Hub (`lpc_dma_isr.h`)**: `registerDmaChannelIsr` now W1C-clears any stale INTA and NVIC pending before enabling — a prior synchronous transfer (XFERCFG.SETINTA) left INTA pending and the callback fired before the caller finished initializing its stream state. - **Single-TU handler**: `DMA0_IRQHandler` moved from the hub header to `lpc_dma_isr.cpp.hpp` (unity slot) — a non-inline extern "C" definition in a header emitted one copy per TU and failed the link with 10+ "multiple definition" errors. - **End-of-stream quiesce (both drivers)**: the ISR's final branch now INTENCLRs its channel. Leaving the gate open let a residual completion fire into post-stream state and HardFault the RPC reply path (deterministic PC in the stack region; gone with the quiesce). - **SPI INTENSET.TXRDYEN removed**: a leftover from the failed pacing hypothesis (#3580 — SWTRIG was the real fix). A pending-but-disabled TXRDY line is a live grenade the moment anything enables SPI0_IRQn. - **Opt-in ISR trace** (`-DFASTLED_LPC_SPI_DMA_ISR_TRACE=1`): polled breadcrumbs from IRQ context — this is what bisected all of the above. - `--dma-spi` now also injects `FASTLED_LPC_DMA_ISR=1`. - Test helper Args factory gains the pwm_dma_cl/dma_spi/dma_uart fields (pre-existing construction failure). Silicon status (LPC845-BRK, 2026-07-02): - UART async bench: green ×3 runs including back-to-back 2048-byte streams (20,511 µs vs 20,480 theoretical; 8,455 toggles). - SPI sync bench: green (unchanged). - SPI ISR stream: FIRST stream green ("1,2577,1358" — 1024 B, 4 chained chunks, 1358 main-thread toggles); repeat-kick corrupts memory — tracked with full evidence at #3585. Refs #3453, #3580, #3585, framework-arduino-lpc8xx#38, fbuild#944. Co-Authored-By: Claude Fable 5 <[email protected]>
…or, not pyserial
The LPC845 SPI/UART bench runners hand-rolled raw pyserial request/reply
loops. On Windows these dropped replies ~one-per-session — `in_waiting`
under-reports, a pre-write `reset_input_buffer()` races the reply,
byte-at-a-time reads straddle the port timeout. The firmware answered
every RPC correctly (verified with a tight manual loop); the pyserial
*transport* lost them.
Fix: both runners now use `ci.rpc_client.RpcClient` over
`ci.util.serial_interface.create_serial_interface()` — fbuild's native
(Rust) serial monitor, the same path ble/decode/driver_sweep/coroutine
tests already use. Mandatory JSON-RPC id correlation + correct framing
make the bench 100% deterministic (SPI: 5/5 cases green run after run;
UART: 2/2). A thin `SpiBench`/`UartBench` sync facade wraps the async
client so the run_* helpers are unchanged.
Two supporting changes this required:
- The bench C++ handlers were `(int, int)` positional — the raw-pyserial
convention. RpcClient wraps args as a single JSON param, so the
handlers now take `(const fl::json& args)` and read `args[N].as_int()`
(the house convention every `-> fl::json` handler already uses).
Handler logic is unchanged; only the bind adapter differs.
- The handlers return a CSV *string*; RpcClient coerces non-dict results
to {} but preserves the full line in `raw_line`, so the facade
recovers the CSV there. (A later cleanup could return fl::json objects.)
Docs: new "Device serial: fbuild's Rust monitor ONLY — NEVER raw
pyserial" rule in agents/docs/hardware-autoresearch.md, plus a "Device
serial - No raw pyserial" entry in agents/docs/python-standards.md.
Also folds in the #3585 RAM fix: the SPI ISR-stream harness buffer
defaults to 512 B (was 1024) so the DMA ISR's deep preemption of the
RPC stack can't collide with the heap on the 16 KB part — that was the
"repeat-kick corruption", a stack/heap collision, not a driver bug (the
ping-pong logic is correct: 5 back-to-back streams green with headroom).
Refs #3456, #3453, #3585.
Co-Authored-By: Claude Fable 5 <[email protected]>
…fenders
## The checker
`ci/lint_python/pyserial_checker.py` (PYS001) bans `import serial` /
`from serial import ...` anywhere under `ci/autoresearch/`. No allowlist:
device serial must go through fbuild's native (Rust) serial monitor via
`ci.rpc_client.RpcClient` + `ci.util.serial_interface.create_serial_interface`.
The genuinely-exceptional site (e.g. a not-yet-migrated BLE bridge) uses
an inline `# noqa: PYS001` with a justification. Wired into the Python
lint pipeline (`ci/lint/stage_impls.py`). The low-level pyserial plumbing
under `ci/util/` (the backend that create_serial_interface(use_pyserial=
True) selects) is out of scope — that is where pyserial legitimately lives.
Why: hand-rolled pyserial request/reply loops drop replies ~one-per-
session on Windows (`in_waiting` under-reports, a pre-write
`reset_input_buffer()` races the reply, byte-at-a-time reads straddle the
port timeout). The firmware answers every RPC; pyserial loses them.
Silicon-diagnosed 2026-07-04 on the LPC845 SPI/UART benches.
## All 14 offenders across 12 files migrated
- **Shared facade** `ci/autoresearch/rpc_bench.py` — `RpcBench`, a sync
wrapper over the async fbuild-backed RpcClient (context-manager +
CSV-result recovery, since RpcClient coerces non-dict results to {}).
- **7 RPC test runners** (test_lpc_pwm_dma_cl / _ws2812_loopback /
_pin_toggle_rx, test_flexio_rx_objectfled / _rx_squarewave /
_spi_smoke, test_objectfled_spi_smoke) → RpcBench.
- **3 debug scripts** → RpcBench (find_pins, object_fled_small) / raw
SerialInterface firehose (object_fled_capture).
- **ota.py + 2 phases.py port polls** → new sanctioned
`port_utils.port_exists()` (OS-level list_ports enumeration, no device
open).
- **phases.py bring-up echo** → SerialInterface write/read_lines.
Hardware-verified on LPC845: echo sentinel round-trip + REMOTE prefix
+ FL_WARN pipeline all PASS.
Docs: "Device serial: fbuild's Rust monitor ONLY" in
agents/docs/hardware-autoresearch.md + agents/docs/python-standards.md
(committed earlier). KeyboardInterrupt handlers added to every new
connect block (KBI001).
Verified: ruff, PYS001 (0), KBI001 (0), AST all clean; the two
already-migrated runners (test_lpc_dma_spi, test_lpc_uart_dma) stay green
over the same transport.
Co-Authored-By: Claude Fable 5 <[email protected]>
…ed" claim Strengthens the "Check if the target hardware might already be attached" rule (cpp-standards.md) with a MANDATORY, unconditional first step: never write "board X is not attached" / "static-verified only" without first enumerating what is physically connected via `fbuild port scan` — fbuild's native scanner that resolves each port's vendor/product from the FastLED boards DB (two rows per port). Cross-referenced from hardware-autoresearch.md with example output. History: on 2026-07-04 an agent declared the flexio/objectfled bench runners "static-verified only, target ESP32/Teensy boards not attached" without ever scanning — an ESP32-WROOM (COM11), three ESP32-S3s, and a Teensy were attached the whole time. When it then reached for raw pyserial `list_ports`, the developer corrected it to `fbuild port scan`. Both corrections are now the rule: enumerate, don't infer; use the fbuild scanner, not pyserial. Co-Authored-By: Claude Fable 5 <[email protected]>
…ia `-m` The pyserial→RpcBench migration added a `sys.path.insert(_REPO_ROOT)` bootstrap to each runner so `from ci.autoresearch.rpc_bench import …` would resolve when run by script path. That trips the SPI001 sys-path-modification ban. Correct fix: remove the bootstrap and launch the runners as modules (`uv run python -m ci.autoresearch.<name>`), which puts the repo root on sys.path[0] so `ci.*` resolves with no hack. - Removed the `_REPO_ROOT`/`sys.path.insert` block from all 12 runners (+ dropped now-unused Path imports, obsolete E402 noqas). - phases.py: switched all 5 subprocess invocations from `"ci/autoresearch/test_lpc_*.py"` to `"-m", "ci.autoresearch.test_lpc_*"`. - Updated each runner's docstring "Usage:" to the `-m` form. Verified: SPI001=0, PYS001=0, KBI001=0, ruff clean; `-m` import resolution confirmed for the runners. Co-Authored-By: Claude Fable 5 <[email protected]>
…otation `bash lint` ty pass flagged 3 type errors from the pyserial→RpcBench migration: - RpcBench.call typed `args: list[Any] | None`, but the flexio/objectfled runners pass a dict (object-param handlers). Widened to `list[Any] | dict[str, Any] | None`, and correspondingly widened RpcClient.send's `args` at the source — send wraps `[args]` opaquely as the single `fl::json` RPC parameter, so a dict was always valid at runtime; the annotation was just too narrow. Backward-compatible widening; existing list callers unaffected. - test_lpc_pwm_dma_cl.py: a run_* helper still annotated `s: "serial.Serial"` (leftover from the pre-migration raw-pyserial version) → `s: "RpcBench"`. Verified: ty clean, ruff clean, SPI001/PYS001/KBI001 = 0. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (36)
📝 WalkthroughWalkthroughThis PR migrates AutoResearch CI scripts from raw pyserial to a shared RpcBench/RpcClient transport, adds a pyserial-ban lint checker, replaces pyserial-based port-readiness checks with OS-level port_exists polling, and introduces a new LPC845 UART TX DMA driver/harness alongside hardened LPC SPI DMA ISR-based async streaming. ChangesAutoResearch Serial Transport Migration and LPC DMA Hardening
Estimated code review effort: 4 (Complex) | ~75 minutes Sequence Diagram(s)sequenceDiagram
participant BenchScript
participant RpcBench
participant RpcClient
participant Firmware
BenchScript->>RpcBench: call(method, args, timeout)
RpcBench->>RpcClient: send(method, args)
RpcClient->>Firmware: JSON-RPC request over Rust serial monitor
Firmware-->>RpcClient: REMOTE/RESULT line or timeout
RpcClient-->>RpcBench: response, RpcError, or RpcTimeoutError
RpcBench-->>BenchScript: parsed result, METHOD_NOT_FOUND, or None
sequenceDiagram
participant Phases
participant PortUtils
participant OSSerialEnum
participant Device
Phases->>PortUtils: port_exists(upload_port)
PortUtils->>OSSerialEnum: comports()
OSSerialEnum-->>PortUtils: enumerated ports
PortUtils-->>Phases: True/False
loop until ready or timeout
Phases->>PortUtils: port_exists(upload_port)
end
Phases->>Device: proceed with bring-up test
Possibly related issues
Possibly related PRs
✨ 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 |
Summary
Three related tracks that landed on this branch:
1. Deployment is fbuild's job — remove pyocd
refactor(autoresearch): delete the pyocd flash path; all deploy goes throughfbuild deploy(probe-rs SWD + lpc21isp ISP fallback). pyocd's LPC-Link2 CMSIS-DAP v1.0.7 HID hang (8 min/invocation on Windows) is a fbuild-owned platform problem, not something FastLED scripts should carry.fbuild deploytakes--port(not--upload-port).2. LPC845 drivers — silicon-validated
ARMHardwareSPIOutputDMA<>) — fixed 6 stacked hardware bugs (SRAMBASE, SPI clocking, DMA channel, SWTRIG, FCLKSEL, frame close); green on real LPC845 (closes LPC845 SPI+DMA driver wedges on first use — control flow jumps into harnessDriver()::drv static (PC=0x100018BC) #3580).3. Ban raw pyserial in the AutoResearch complex (PYS001)
ci/lint_python/pyserial_checker.py(PYS001, no allowlist) — device serial must go through fbuild's Rust monitor (RpcClient/create_serial_interface), never raw pyserial. Wired into the Python lint pipeline. Motivation: hand-rolled pyserial request/reply loops drop replies ~one-per-session on Windows; silicon-diagnosed on the LPC845 benches.RpcBenchfacade (7 RPC runners), rawSerialInterfacefirehose (debug capture), and a sanctionedport_utils.port_exists()for port-availability polls.uv run python -m ci.autoresearch.<name>) — nosys.pathhacks (SPI001-clean).4. Agent docs
fbuild port scanbefore any "board not attached" claim (enumerate, don't infer). Two documented incidents where boards were wrongly declared absent.Verification
Related
fbuild port scan), fbuild#595/ESP32 SPI problems #923/RGBCalibrate example - index out of bounds #928 (nxplpc deployer).🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Chores