Skip to content

chore(esp32): eliminate runtime esp_rom_printf call sites - #2751

Merged
zackees merged 2 commits into
masterfrom
chore/esp32-eliminate-esp-rom-printf
Jun 4, 2026
Merged

zackees merged 2 commits into
masterfrom
chore/esp32-eliminate-esp-rom-printf

Conversation

@zackees

@zackees zackees commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Removes every runtime esp_rom_printf site under examples/AutoResearch and src/platforms/esp, replacing each with a FastLED-owned mechanism. The EspRomPrintfChecker and its tests are unchanged — only the runtime offenders go.

Acceptance criterion from the issue:

rg -n 'esp_rom_printf\(' examples/AutoResearch src/platforms/esp -g '*.h' -g '*.hpp' -g '*.cpp'

returns empty on this branch.

Per-file change

  • examples/AutoResearch/AutoResearch{Wave8Expand,ParlioEncode}.h — delete printXxxResultRom helpers entirely. They are dead code; no caller exists anywhere in the repo. The RPC handlers JSON-serialize the result struct directly, and the boot-time ROM-printf bridge was a stopgap for perf(autoresearch): use FL_PRINT instead of esp_rom_printf in on-device benchmarks #2540/bug(esp32p4): testSimd RPC write-timeout — Serial routes to UART0 instead of USB-Serial-JTAG #2541 that is no longer needed now that bug(esp32p4): testSimd RPC write-timeout — Serial routes to UART0 instead of USB-Serial-JTAG #2541 has landed.
  • src/platforms/esp/32/drivers/usb_serial_jtag_esp32{,_idf.hpp} — the 16 driver-bootstrap esp_rom_printf calls ran inside the singleton constructor, where FL_PRINT would re-enter the in-progress singleton. Replaced with a UsbSerialJtagEsp32::InitOutcome enum recorded in a member field + initOutcome() / initError() getters. The two non-bootstrap runtime errors in write() / writeln() become FL_WARN directly (task context).
  • src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp — drop the 2 backend-selection esp_rom_printf lines from the EspIO constructor; backend state is already in mUseUsbSerialJtag. Adds reportInitDiagnosticsIfNeeded() invoked at the top of print() / println() which emits a one-shot FL_PRINT summary (EspIO: backend=USB-JTAG usb_jtag_outcome=InstalledOk err=0) once construction has completed and FL_PRINT is safe.
  • src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.{h,cpp.hpp} — the 3 esp_rom_printf calls lived in an FL_IRAM function that may be entered from ISR context. LoggingInIramChecker forbids FL_WARN inside FL_IRAM functions, so direct replacement is not possible. Latch each failure into mLast{WaitForSlotTimeout,PanelIoRecreateError,TxColorError} and drain via FL_WARN from waitTransmitDone() — task-only, since xSemaphoreTake would configASSERT from ISR.

Resolution of the two open questions in the issue

The issue listed two unanswered architectural decisions. Per user direction:

  1. USB-Serial JTAG bootstrap diagnostics → defer via status getter (implemented as UsbSerialJtagEsp32::InitOutcome + EspIO::reportInitDiagnosticsIfNeeded).
  2. Tighten EspRomPrintfChecker to forbid // ok esp_rom_printf in runtime source → out of scope for this PR, left as a follow-up if marker creep becomes a problem.

Test plan

  • bash lint — green (Python + C++ checkers + JS).
  • bash test --cpp — 309/309 host tests passed.
  • CI: ESP32 platform compile matrix (deferred to PR CI; all changed files are ESP32-gated).
  • rg -n 'esp_rom_printf\(' examples/AutoResearch src/platforms/esp -g '*.h' -g '*.hpp' -g '*.cpp' returns empty.

Closes #2699

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Exposed richer USB‑Serial JTAG initialization diagnostics for visibility.
    • Benchmarks updated to be RPC-only with results JSON‑serialized by the RPC handler.
  • Bug Fixes

    • Deferred diagnostics until first print to avoid unsafe interrupt‑context logging.
    • LCD SPI now latches transmit errors in IRAM context and reports them safely from task context.
    • Replaced direct ROM console prints with structured logging.

Replaces every runtime `esp_rom_printf` site under `examples/AutoResearch`
and `src/platforms/esp` with FastLED-owned mechanisms. The
`EspRomPrintfChecker` and its tests are untouched; this commit only removes
the runtime offenders so the checker no longer needs the `// ok` opt-out
in shipping code.

- examples/AutoResearch/AutoResearch{Wave8Expand,ParlioEncode}.h:
  delete `printXxxResultRom` helpers (dead code: no callers anywhere). The
  RPC handlers JSON-serialize the result struct directly; the boot-time
  ROM-printf bridge was a stopgap for #2540/#2541 and is no longer needed
  now that #2541 has landed. Also drops the now-unused `<esp_rom_sys.h>`
  includes and the stale doc-comments referring to esp_rom_printf routing.

- src/platforms/esp/32/drivers/usb_serial_jtag_esp32{,_idf.hpp}:
  the 16 driver-bootstrap esp_rom_printf calls happened inside the
  singleton constructor, where FL_PRINT would re-enter the in-progress
  singleton. Replaced with a `UsbSerialJtagEsp32::InitOutcome` enum
  recorded into a member field plus `initOutcome()` / `initError()`
  getters; EspIO surfaces a single human-readable summary on first print.
  The two non-bootstrap runtime errors in `write()` / `writeln()` (which
  are task-context) become FL_WARN directly.

- src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp:
  drop the 2 backend-selection esp_rom_printf lines from the EspIO
  constructor; the state was already captured in `mUseUsbSerialJtag`. Adds
  `reportInitDiagnosticsIfNeeded()` invoked at the top of `print()` and
  `println()` to emit a one-shot FL_PRINT summary
  (`EspIO: backend=USB-JTAG usb_jtag_outcome=InstalledOk err=0`) once
  construction has completed and FL_PRINT is safe.

- src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.{h,cpp.hpp}:
  the 3 esp_rom_printf calls lived in a function tagged FL_IRAM that may
  be entered from ISR context. LoggingInIramChecker forbids FL_WARN inside
  FL_IRAM functions, so direct replacement is not possible. Latch each
  failure (`mLastWaitForSlotTimeout`, `mLastPanelIoRecreateError`,
  `mLastTxColorError`) and drain via FL_WARN from `waitTransmitDone()` —
  task-only, since `xSemaphoreTake` would already configASSERT from ISR.

Resolves the two issue-thread open questions per user decision:
  - USB-Serial JTAG bootstrap: defer-via-status-getter (implemented above).
  - Tightening EspRomPrintfChecker to forbid `// ok esp_rom_printf` in
    runtime source: out of scope for this PR (left as a follow-up).

Acceptance verified locally:
  rg -n 'esp_rom_printf\(' examples/AutoResearch src/platforms/esp \
    -g '*.h' -g '*.hpp' -g '*.cpp'    # returns empty
  bash lint                              # green
  bash test --cpp                        # 309/309 passed

Closes #2699

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f4460cab-430f-4c8a-b368-696891606031

📥 Commits

Reviewing files that changed from the base of the PR and between 9e0ee39 and 311c484.

📒 Files selected for processing (1)
  • src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp

📝 Walkthrough

Walkthrough

Eliminates runtime esp_rom_printf call sites: USB-Serial JTAG init outcomes are recorded and exposed; EspIO defers reporting until first print(); LCD SPI latches IRAM transmit errors for later task-context logging; AutoResearch bench headers remove ROM-print helpers and mark RPC-only JSON output.

Changes

Eliminate esp_rom_printf runtime call sites

Layer / File(s) Summary
USB-Serial JTAG initialization diagnostics infrastructure
src/platforms/esp/32/drivers/usb_serial_jtag_esp32.h, src/platforms/esp/32/drivers/usb_serial_jtag_esp32_idf.hpp
Adds InitOutcome enum and initOutcome()/initError() accessors; implementation records init outcome/error state instead of eager esp_rom_printf. Move ops copy outcome state. write/writeln log errors using FL_WARN.
EspIO deferred initialization diagnostics
src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp
Adds mDiagnosticsReported and reportInitDiagnosticsIfNeeded(); defers emitting backend selection and USB-Serial JTAG InitOutcome/error to first print()/println() via FL_PRINT.
LCD SPI IRAM error latching and deferred reporting
src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.h, src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp
Introduces volatile latched fields for slot-wait timeout and panel-IO/tx_color esp_err_t. transmitInternal() latches failures (avoids IRAM logging); teardownLocked() clears latches; waitTransmitDone() reports latched errors via FL_WARN and resets them.
AutoResearch benchmark RPC-only enforcement
examples/AutoResearch/AutoResearchParlioEncode.h, examples/AutoResearch/AutoResearchWave8Expand.h
Removes esp_rom_sys.h includes and printParlioEncodeResultRom/printWave8ExpandResultRom helpers. Documentation updated to state benchmarks are RPC-only and results are JSON-serialized by the RPC handler. Disabled stubs now only return empty measure results.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant EspIO
  participant UsbSerialJtag as UsbSerialJtagEsp32
  participant FL as FL_PRINT / FL_WARN
  Client->>EspIO: call print()/println()
  EspIO->>UsbSerialJtag: query initOutcome()/initError()
  EspIO->>FL: reportInitDiagnosticsIfNeeded() -> emit backend + InitOutcome/initError
  EspIO->>UsbSerialJtag: forward write()/writeln() (errors -> FL_WARN)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

"I'm a rabbit in a code-filled glade,
deferring prints until the sun is made.
Latched errors tucked for task-time song,
benches whisper JSON all day long.
esp_rom_printf hops away 🐇"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.62% 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 'chore(esp32): eliminate runtime esp_rom_printf call sites' directly and clearly summarizes the main change: removing all runtime esp_rom_printf calls from ESP32 code.
Linked Issues check ✅ Passed All acceptance criteria from issue #2699 are met: no runtime esp_rom_printf calls remain in targeted dirs, AutoResearch output is routed through FastLED mechanisms, USB-Serial-JTAG diagnostics use InitOutcome enum/deferred reporting, and LCD SPI errors are latched and reported from task context.
Out of Scope Changes check ✅ Passed All changes directly support the core objective of eliminating runtime esp_rom_printf calls; no unrelated modifications to unrelated systems or files outside AutoResearch and src/platforms/esp are present.

✏️ 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 chore/esp32-eliminate-esp-rom-printf

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.

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

🧹 Nitpick comments (2)
src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp (1)

468-483: 💤 Low value

Consider clearing latched error fields in teardownLocked() for session hygiene.

The draining logic here is correct, but teardownLocked() (lines 234-266) resets most state but not the latched error fields. If a transmit error was latched from the previous driver session and waitTransmitDone() wasn't called before teardown, those stale errors could be reported in the next driver session's first successful waitTransmitDone() call.

This is a minor edge case since the messages are diagnostic-only and would have been valid errors at some point.

🔧 Optional fix in teardownLocked()
 void LcdSpiPeripheralEsp::teardownLocked() FL_NOEXCEPT {
     // ... existing teardown code ...
     mLastTransmitSize = 0;
     mOwner = LcdSpiOwnerDriver::NONE;
+
+    // Clear latched errors so a new driver session starts clean.
+    mLastWaitForSlotTimeout = false;
+    mLastPanelIoRecreateError = ESP_OK;
+    mLastTxColorError = ESP_OK;
 }
🤖 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/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp` around
lines 468 - 483, teardownLocked() currently resets most peripheral state but
doesn't clear the latched error fields, causing stale diagnostics to surface in
the next session; update teardownLocked() to explicitly clear
mLastWaitForSlotTimeout (set false), mLastPanelIoRecreateError (set ESP_OK), and
mLastTxColorError (set ESP_OK) so any previously latched errors are cleared when
the driver is torn down and will not be reported in the following session.
src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp (1)

240-267: ⚡ Quick win

Well-designed deferred diagnostic reporting.

The one-shot guard and deferred FL_PRINT correctly avoid re-entrancy during singleton construction. The switch covers all InitOutcome enum values and provides clear human-readable diagnostics.

⚛️ Optional: Consider atomic flag for strict thread-safety

mDiagnosticsReported is currently a plain bool. If multiple threads call print() or println() simultaneously before the flag is set, both could see false and emit the diagnostic twice. While benign (duplicate diagnostics are harmless), strict correctness would use fl::atomic<bool> or a mutex guard.

However, given that:

  1. The singleton construction itself is thread-safe
  2. The worst-case failure is a duplicate diagnostic line
  3. Most codebases call print() from a single thread

...the current implementation is acceptable. Only consider this refinement if strict once-only semantics are required.

🤖 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/esp/32/detail/io_esp_jtag_or_uart.hpp` around lines 240 - 267,
The deferred diagnostic guard mDiagnosticsReported can race if multiple threads
call reportInitDiagnosticsIfNeeded() concurrently; change mDiagnosticsReported
from plain bool to fl::atomic<bool> (or std::atomic<bool> if fl::atomic is
unavailable) and perform an atomic test-and-set in
reportInitDiagnosticsIfNeeded() (e.g., load/check and then
compare_exchange_strong to set true) so only one thread proceeds to emit the
FL_PRINT; keep the rest of reportInitDiagnosticsIfNeeded(), mUseUsbSerialJtag
and mUsbSerialJtag.initOutcome()/initError() logic unchanged.
🤖 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.

Nitpick comments:
In `@src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp`:
- Around line 240-267: The deferred diagnostic guard mDiagnosticsReported can
race if multiple threads call reportInitDiagnosticsIfNeeded() concurrently;
change mDiagnosticsReported from plain bool to fl::atomic<bool> (or
std::atomic<bool> if fl::atomic is unavailable) and perform an atomic
test-and-set in reportInitDiagnosticsIfNeeded() (e.g., load/check and then
compare_exchange_strong to set true) so only one thread proceeds to emit the
FL_PRINT; keep the rest of reportInitDiagnosticsIfNeeded(), mUseUsbSerialJtag
and mUsbSerialJtag.initOutcome()/initError() logic unchanged.

In `@src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp`:
- Around line 468-483: teardownLocked() currently resets most peripheral state
but doesn't clear the latched error fields, causing stale diagnostics to surface
in the next session; update teardownLocked() to explicitly clear
mLastWaitForSlotTimeout (set false), mLastPanelIoRecreateError (set ESP_OK), and
mLastTxColorError (set ESP_OK) so any previously latched errors are cleared when
the driver is torn down and will not be reported in the following session.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 15a4f045-ae8b-4c36-ab3d-c33bb2932c10

📥 Commits

Reviewing files that changed from the base of the PR and between 2b2d912 and 9e0ee39.

📒 Files selected for processing (7)
  • examples/AutoResearch/AutoResearchParlioEncode.h
  • examples/AutoResearch/AutoResearchWave8Expand.h
  • src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp
  • src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.h
  • src/platforms/esp/32/drivers/usb_serial_jtag_esp32.h
  • src/platforms/esp/32/drivers/usb_serial_jtag_esp32_idf.hpp

…2751)

Address CodeRabbit nitpick on PR #2751: teardownLocked() reset most state
but not the latched-error fields introduced by the esp_rom_printf cleanup.
A stale error from the previous owner-driver session could otherwise surface
from the next session's first waitTransmitDone().

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees

zackees commented Jun 4, 2026

Copy link
Copy Markdown
Member Author

Addressing CodeRabbit's two nitpicks:

1. teardownLocked() should clear latched errors (lcd_spi) — Fixed in 311c484. Real session-hygiene concern; trivial 3-line fix.

2. mDiagnosticsReported should be atomic (io_esp_jtag_or_uart) — Acknowledged, not applied. CodeRabbit's own assessment was: "the current implementation is acceptable. Only consider this refinement if strict once-only semantics are required."

FastLED's typical runtime is a single-thread loop(), and the worst case of a race here is one duplicate EspIO: backend=… line at startup — benign. Adding fl::atomic<bool> would pull in atomics machinery into the boot path for a diagnostic line that is, by design, fired once per device boot. Leaving as-is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

chore(esp32): eliminate runtime esp_rom_printf call sites

1 participant