Skip to content

feat: add ISR-backed channel poll wakeups - #2992

Merged
zackees merged 2 commits into
masterfrom
feat/2991-tight-timing
Jun 9, 2026
Merged

zackees merged 2 commits into
masterfrom
feat/2991-tight-timing

Conversation

@zackees

@zackees zackees commented Jun 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes #2991.

This adds IChannelDriver::PollNeededCallback and setPollNeededCallback() so a driver ISR can wake the channel manager when driver state changed and poll() should run again. The callback is intentionally not a done callback: a driver may signal that a chunk, batch, or transfer changed state while more inter-batch work remains on the main thread.

PollNeededCallback is now an ISR-safe function/context handle, with PollNeededCallbackSlot providing atomic task-to-ISR publication for drivers that invoke the callback from interrupt context. This avoids storing or mutating fl::function on the ISR boundary.

ChannelManager owns the single poll-needed wait primitive. The manager talks only to platforms::ChannelPollSignal, so the channel-manager code has no ESP-specific semaphore guards or drain loops. On ESP32, the platform implementation uses fl::binary_semaphore; drivers only receive the callback. If no driver invokes the callback, the manager still wakes on bounded 1 ms timeout slices and polls, so no separate capability gate or per-driver semaphore is needed.

The ESP32 fl::binary_semaphore release path is now ISR-aware: it detects ISR context, uses xSemaphoreGiveFromISR(), and calls portYIELD_FROM_ISR() when a higher-priority task should run. That lets ESP wake the main loop task at the next scheduling opportunity while keeping the channel manager code normalized around a platform wait abstraction.

The PR also adds an AutoResearch --tight-timing metric for FastLED.show(); FastLED.wait() overhead, enables ESP32-S3 USB CDC for AutoResearch RPC, temporarily raises ESP32-S3/C6 Arduino loop stack size for the deeper AutoResearch driver setup path, and makes the ESP watchdog subscribe/feed the loop task so hung autotest firmware resets instead of wedging the board.

Verification

  • git diff --check
  • touched-file C++ lint for channel manager/driver changes, platform poll signal dispatch, ESP RMT/I2S/LCD/PARLIO callback changes, ESP semaphore, ESP watchdog, shared atomic, and AutoResearch C++ changes
  • uv run python -m compileall ci/autoresearch/phases.py
  • uv run pytest ci/tests/test_no_include_after_namespace.py -q
  • uv run python -m ci.lint_cpp.run_all_checkers src/platforms/esp/32/watchdog_esp32.impl.hpp
  • uv run python -m compileall ci/boards.py ci/autoresearch/args.py ci/autoresearch/phases.py ci/autoresearch/context.py
  • uv run python -m ci.autoresearch --help
  • bash test watchdog
  • bash compile esp32s3 --examples AutoResearch --platformio
  • bash compile esp32c6 --examples AutoResearch --platformio
  • Hardware: ESP32-C6 PARLIO tight timing passed, max overhead 1266 us with 2000 us limit
  • Hardware: ESP32-C6 RMT tight timing passed, max overhead 296 us with 2000 us limit
  • Hardware: ESP32-S3 RMT tight timing passed, max overhead 516 us with 2000 us limit
  • Hardware: ESP32-S3 I2S tight timing passed, max overhead 1503 us with 2000 us limit
  • Hardware: ESP32-C6 deliberate AutoResearch hang reset via watchdog and resumed RPC after reboot

Notes

The wait-state bus should already be resolved before this path; Bus::AUTO must not be represented in any future bus-mask wait state. If a bus mask is added later, use a resolved bus value only.

The -DARDUINO_LOOP_STACK_SIZE=16384 override is temporary. Follow-up issue #2993 tracks investigating the ESP AutoResearch stack growth and reverting back to stock Arduino loop stack settings.

Summary by CodeRabbit

Release Notes

  • New Features

    • AutoResearch now includes a "Tight Timing Metric" option to measure LED timing overhead and performance characteristics across iterations.
  • Bug Fixes

    • Enhanced ESP32 watchdog robustness with explicit loop task monitoring and recovery mechanisms.
  • Chores

    • Updated ESP32 board build configurations for improved USB and memory management.
    • Improved internal driver coordination for better responsiveness and ISR safety.

@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds AutoResearch tight-timing CLI options and device measurement + display, implements driver poll-needed callback/ChannelManager poll-signal plumbing wired into multiple ESP32 drivers, and updates ESP32 watchdog task monitoring, semaphore ISR-safety, atomic exchange, and build flags.

Changes

AutoResearch Tight-Timing Diagnostics

Layer / File(s) Summary
CLI tight-timing args and result display
ci/autoresearch/args.py, ci/autoresearch/context.py, ci/autoresearch/phases.py
Args dataclass gains tight_timing, tight_timing_iterations, and tight_timing_max_overhead_us fields; CLI argument group and parser wiring added; display_tight_timing helper prints PASS/FAIL and timing stats from RPC results in both success and failure paths.
Device-side measurement and watchdog timeout
examples/AutoResearch/AutoResearchRemote.cpp, examples/AutoResearch/AutoResearch.ino
runSingleTestImpl parses tight-timing RPC args, invokes measureTightTiming() helpers to collect show/wait statistics, returns JSON payload with results; AUTORESEARCH_WATCHDOG_TIMEOUT_MS constant (5000 ms) wired to FL_WATCHDOG_AUTO() macro.

Poll-Needed ISR Callback Infrastructure

Layer / File(s) Summary
Channel driver contract
src/fl/channels/driver.h
Adds IChannelDriver::PollNeededCallback type alias and setPollNeededCallback() virtual method with default no-op; updates waitDone() documentation to clarify aggregate poll-signal behavior.
ChannelManager polling and synchronization
src/fl/channels/manager.h, src/fl/channels/manager.cpp.hpp, src/platforms/channel_poll_signal.h, src/platforms/shared/channel_poll_signal.h, src/platforms/esp/32/channel_poll_signal_esp32.h
Manager installs poll-needed callback on drivers, drains pending signals before waiting, implements timeout-sliced waitForPollNeededSignal() waiting in waitForCondition() loop, removes single-driver waitDone fast path; adds platform-guarded ChannelPollSignal implementations.
I2S driver poll callback and transmit ISR
src/platforms/esp/32/drivers/i2s/channel_driver_i2s.h, src/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp.hpp
Implements setPollNeededCallback override, adds isrTransmitDone ISR handler marked IRAM, registers handler with I2S peripheral and stores callback for ISR invocation.
LCD clockless and PARLIO poll callback wiring
src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h, src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp, src/platforms/esp/32/drivers/parlio/channel_driver_parlio.h, src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp, src/platforms/esp/32/drivers/parlio/parlio_engine.h, src/platforms/esp/32/drivers/parlio/parlio_engine.cpp.hpp
Implements setPollNeededCallback in driver wrappers and engines, invokes callbacks from chunk-done and transmission-done ISRs, propagates callbacks through initialization and sub-driver creation; LCD clockless show() empty-enqueue path now calls waitForReady(2000).
RMT driver poll callback and TX-done ISR
src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.h, src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.cpp.hpp
Adds setPollNeededCallback pure-virtual to RMT interface and concrete implementation; extends ChannelState with owner pointer for ISR access to engine; invokes stored callback from TX-done ISR when available.

ESP32 System Updates

Layer / File(s) Summary
Watchdog monitored-task lifecycle
src/platforms/esp/32/watchdog_esp32.h, src/platforms/esp/32/watchdog_esp32.cpp.hpp, src/platforms/esp/32/watchdog_esp32.impl.hpp, src/platforms/esp/32/watchdog_esp32_idf4.hpp, src/platforms/esp/32/watchdog_esp32_idf5.hpp
Extends watchdog state with FreeRTOS task handle and tracking; implements subscription/reset/unsubscription helpers; wires task monitoring through begin/feed/disable/onTimeout; handles already-initialized TWDT in IDF4/IDF5 init; updates documentation and log messaging.
Semaphore ISR-safety and atomic helpers
src/platforms/esp/32/semaphore_esp32.h, src/platforms/esp/32/semaphore_esp32.cpp.hpp, src/platforms/shared/atomic.h
Adds ISR-context detection with conditional xSemaphoreGiveFromISR path; implements try_acquire_for_ms millisecond timeout helper with tick conversion and 1-tick minimum; adds atomic exchange operation for lock-free swaps.
Build flags and configuration
platformio.ini, ci/boards.py, src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp
Updates shared PlatformIO env:generic-esp and device-specific environments with USB mode/CDC-on-boot and loop stack size defines; replaces an IWYU include with freertos/FreeRTOS.h where appropriate.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#2828: Modifies channel-waiting behavior; closely related to the poll-needed vs per-driver waitDone approaches.
  • FastLED/FastLED#2817: Also adjusts ChannelManager wait strategy; overlaps conceptually with waitForCondition changes.
  • FastLED/FastLED#2827: Related changes to wait phases and yielding strategy in the channel wait path.

"🐰
Callbacks wake the manager with a ping,
Tight timing measured, returned, and singed;
Watchdog guards the loop with steady beat,
Semaphores and atomics keep the dance neat.
✨"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.60% 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 'feat: add ISR-backed channel poll wakeups' clearly and concisely describes the main feature addition—implementing ISR-backed callback mechanisms for channel polling.
Linked Issues check ✅ Passed The PR implements multiple objectives from #2991: ISR-backed poll wakeups via PollNeededCallback, driver-specific completion primitives (RMT, I2S, PARLIO, LCD), bounded wait slices with ISR signaling, ESP32 watchdog loop-task subscription, and AutoResearch tight-timing measurement harness.
Out of Scope Changes check ✅ Passed All changes align with #2991 objectives: poll-wakeup infrastructure, driver implementations, watchdog subscription, ESP32 USB CDC enablement, Arduino loop stack increases, and AutoResearch timing metrics are within scope.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/2991-tight-timing

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.

@zackees

zackees commented Jun 9, 2026

Copy link
Copy Markdown
Member Author

I still see task sleep in there, it should be fixed. Please see the commit. It's unclear if the wait is happening in the channel driver of the channel manager.

@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: 1

🧹 Nitpick comments (6)
src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp (2)

309-322: ⚡ Quick win

Consider tracking elapsed time for timeout across loop iterations.

The timeout is recomputed on each while (mBusy) iteration (lines 315-316), which means the timeout effectively resets if the loop somehow iterates multiple times. While the loop is defensive (the ISR clears mBusy before giving the semaphore, so a successful xSemaphoreTake should immediately exit), tracking elapsed time and computing remaining timeout would be more robust:

const u32 startMs = (timeout_ms > 0) ? millis() : 0;
while (mBusy) {
    TickType_t timeout_ticks = portMAX_DELAY;
    if (timeout_ms > 0) {
        const u32 elapsed = millis() - startMs;
        if (elapsed >= timeout_ms) return false;
        timeout_ticks = pdMS_TO_TICKS(timeout_ms - elapsed);
    }
    if (xSemaphoreTake(mCompleteSem, timeout_ticks) != pdTRUE) {
        return false;
    }
}

This ensures the timeout applies to the entire wait operation rather than per-take.

🤖 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/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp` around
lines 309 - 322, The current I2sLcdCamPeripheralEsp::waitTransmitDone
implementation recomputes the full timeout for each xSemaphoreTake call which
effectively resets the timeout on each loop; change it to record a start time
when timeout_ms>0 (use millis()), compute elapsed inside the while(mBusy) loop,
subtract elapsed from timeout_ms to derive a remaining timeout_ticks for
xSemaphoreTake, and return false if elapsed >= timeout_ms or xSemaphoreTake
times out; keep the existing guards for mInitialized and mCompleteSem and
continue using mBusy as the loop condition.

59-79: 💤 Low value

Consider using fl::atomic<bool> for mBusy for strict guideline compliance.

The coding guidelines state: "ISR-Shared State: any state written from ISR context and read from task context must use fl::atomic<T> with explicit memory_order or be guarded with the proper FreeRTOS critical section APIs."

Currently, mBusy is volatile bool (written at line 60 in ISR, read in waitTransmitDone/isBusy in task context). While the semaphore xSemaphoreGiveFromISR and xSemaphoreTake provide memory ordering guarantees that likely make this safe, switching to fl::atomic<bool> with explicit memory ordering would fully align with the guideline and make the ordering guarantees explicit.

This is a low-priority suggestion since the semaphore synchronization provides the necessary ordering for correctness.

🤖 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/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp` around
lines 59 - 79, Replace the volatile bool mBusy with fl::atomic<bool> and update
all accesses: in the ISR (the code that currently sets self->mBusy = false) use
self->mBusy.store(false, std::memory_order_release), and in task-context readers
like waitTransmitDone and isBusy use self->mBusy.load(std::memory_order_acquire)
(or equivalent acquire loads) so the semaphore-based synchronization is made
explicit; ensure the member declaration and every read/write of mBusy use the
fl::atomic<bool> type and the specified memory orders.

Source: Coding guidelines

src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.h (1)

18-29: 💤 Low value

Verify include ordering against coding guidelines.

The coding guidelines specify: "All system imports must be at the top of the file in proper order: standard library, third-party, local." Currently, local headers (fl/stl/compiler_control.h) appear before third-party FreeRTOS headers.

If FL_EXTERN_C_BEGIN/END macros from compiler_control.h are required to wrap the FreeRTOS includes, this ordering is unavoidable. Otherwise, consider moving compiler_control.h after the FreeRTOS includes to align with the guideline.

🤖 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/i2s/i2s_lcd_cam_peripheral_esp.h` around lines
18 - 29, The include ordering violates the guideline because local header
"fl/stl/compiler_control.h" appears before third-party FreeRTOS headers; either
move the FreeRTOS includes (freertos/FreeRTOS.h and freertos/semphr.h) above the
local includes so headers follow: standard, third-party, local, or if the
FL_EXTERN_C_BEGIN/FL_EXTERN_C_END macros from compiler_control.h are required to
wrap the FreeRTOS headers, keep the current order but add a brief comment above
FL_EXTERN_C_BEGIN explaining that compiler_control.h must precede the FreeRTOS
includes to provide the extern "C" macros and to preserve the IWYU pragma blocks
(so reviewers understand the exception).

Source: Coding guidelines

src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp (2)

595-634: ⚡ Quick win

Inconsistent yield pattern with other drivers.

The fallback path at line 630 uses fl::delayMicroseconds(50) when no peripheral is available. The I2S and LCD drivers in this PR use task::run(0, task::ExecFlags::SYSTEM) for the same fallback case. Per the coding guidelines, tight wait loops should yield via task::run rather than busy-waiting. Consider aligning with the established pattern.

🔄 Proposed fix to align yield behavior
             } else {
-                fl::delayMicroseconds(50);
+                task::run(0, task::ExecFlags::SYSTEM);
             }

As per coding guidelines: "yield with fl::task::run(..., fl::task::ExecFlags::SYSTEM) (short OS yield for tight polling)".

🤖 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/parlio/channel_driver_parlio.cpp.hpp` around
lines 595 - 634, The fallback busy-wait in ChannelDriverPARLIO::waitDone
currently calls fl::delayMicroseconds(50) when no Parlio peripheral is
available; replace that busy-wait with the short OS yield used by the other
drivers (fl::task::run(0, fl::task::ExecFlags::SYSTEM)) so the loop yields
instead of spinning. Update the else branch under the peripheral == nullptr path
(in waitDone) to call fl::task::run(0, fl::task::ExecFlags::SYSTEM) and ensure
the fl::task header is included if not already.

Source: Coding guidelines


292-323: ⚡ Quick win

Inconsistent yield pattern with other drivers.

The fallback path at line 320 uses fl::delayMicroseconds(50) when no peripheral is available. The I2S and LCD drivers in this PR use task::run(0, task::ExecFlags::SYSTEM) for the same fallback case (e.g., channel_driver_i2s.cpp.hpp:227). Per the coding guidelines, tight wait loops should yield via task::run rather than busy-waiting. Consider aligning with the established pattern.

🔄 Proposed fix to align yield behavior
         } else {
-            fl::delayMicroseconds(50);
+            task::run(0, task::ExecFlags::SYSTEM);
         }

As per coding guidelines: "yield with fl::task::run(..., fl::task::ExecFlags::SYSTEM) (short OS yield for tight polling)".

🤖 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/parlio/channel_driver_parlio.cpp.hpp` around
lines 292 - 323, The tight-wait fallback in ChannelDriverPARLIOImpl::waitDone
currently busy-waits using fl::delayMicroseconds(50); change this to yield the
scheduler like other drivers by calling fl::task::run(0,
fl::task::ExecFlags::SYSTEM) in the else branch so the loop yields correctly
when detail::IParlioPeripheral* peripheral is null; locate the else branch in
waitDone and replace the delayMicroseconds call with the task::run yield.

Source: Coding guidelines

src/platforms/esp/32/watchdog_esp32_idf4.hpp (1)

137-139: 💤 Low value

ESP_ERR_INVALID_STATE handling is correct for IDF4 API limitations.

Converting ESP_ERR_INVALID_STATE to ESP_OK allows the watchdog to proceed when the TWDT is already initialized (e.g., by the Arduino core or another component that has tasks subscribed, preventing deinit_existing_watchdog() from succeeding). IDF4 lacks esp_task_wdt_reconfigure(), so the existing timeout is kept.

Note that log_watchdog_status() at line 150 logs the requested timeout_ms, not the actual configured timeout, which could be misleading if this path is taken. However, IDF4 provides no API to query the actual timeout, so this is acceptable. Consider adding a debug log here to clarify when the requested timeout wasn't applied:

Optional: Add debug log when timeout cannot be reconfigured
     esp_err_t err = esp_task_wdt_init(timeout_s, true);
     if (err == ESP_ERR_INVALID_STATE) {
+        FL_DBG("[WATCHDOG] TWDT already initialized; keeping existing timeout (IDF4 cannot reconfigure)");
         err = ESP_OK;  // Already armed; keep the existing IDF4 timeout.
     }
🤖 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/watchdog_esp32_idf4.hpp` around lines 137 - 139, The
current handler in watchog_esp32_idf4.hpp converts ESP_ERR_INVALID_STATE to
ESP_OK to accept an already-initialized TWDT (in deinit_existing_watchdog()),
but it doesn't record that the requested timeout_ms wasn't applied; update the
ESP_ERR_INVALID_STATE branch to keep the conversion but also emit a debug/warn
log indicating the watchdog was already armed and the requested timeout_ms may
not have been applied (reference the err comparison for ESP_ERR_INVALID_STATE,
the deinit_existing_watchdog() flow, and the log_watchdog_status() usage) so
callers can distinguish requested vs actual timeout.
🤖 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/phases.py`:
- Around line 534-540: Validate the upper bound for tight-timing iterations in
the same block where args.tight_timing is checked: ensure
args.tight_timing_iterations is between 1 and 64 (inclusive) and return an error
if it is outside that range; update the error message for
args.tight_timing_iterations to state the valid range [1, 64] so invalid values
are rejected on the host before RPC calls.

---

Nitpick comments:
In `@src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp`:
- Around line 309-322: The current I2sLcdCamPeripheralEsp::waitTransmitDone
implementation recomputes the full timeout for each xSemaphoreTake call which
effectively resets the timeout on each loop; change it to record a start time
when timeout_ms>0 (use millis()), compute elapsed inside the while(mBusy) loop,
subtract elapsed from timeout_ms to derive a remaining timeout_ticks for
xSemaphoreTake, and return false if elapsed >= timeout_ms or xSemaphoreTake
times out; keep the existing guards for mInitialized and mCompleteSem and
continue using mBusy as the loop condition.
- Around line 59-79: Replace the volatile bool mBusy with fl::atomic<bool> and
update all accesses: in the ISR (the code that currently sets self->mBusy =
false) use self->mBusy.store(false, std::memory_order_release), and in
task-context readers like waitTransmitDone and isBusy use
self->mBusy.load(std::memory_order_acquire) (or equivalent acquire loads) so the
semaphore-based synchronization is made explicit; ensure the member declaration
and every read/write of mBusy use the fl::atomic<bool> type and the specified
memory orders.

In `@src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.h`:
- Around line 18-29: The include ordering violates the guideline because local
header "fl/stl/compiler_control.h" appears before third-party FreeRTOS headers;
either move the FreeRTOS includes (freertos/FreeRTOS.h and freertos/semphr.h)
above the local includes so headers follow: standard, third-party, local, or if
the FL_EXTERN_C_BEGIN/FL_EXTERN_C_END macros from compiler_control.h are
required to wrap the FreeRTOS headers, keep the current order but add a brief
comment above FL_EXTERN_C_BEGIN explaining that compiler_control.h must precede
the FreeRTOS includes to provide the extern "C" macros and to preserve the IWYU
pragma blocks (so reviewers understand the exception).

In `@src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp`:
- Around line 595-634: The fallback busy-wait in ChannelDriverPARLIO::waitDone
currently calls fl::delayMicroseconds(50) when no Parlio peripheral is
available; replace that busy-wait with the short OS yield used by the other
drivers (fl::task::run(0, fl::task::ExecFlags::SYSTEM)) so the loop yields
instead of spinning. Update the else branch under the peripheral == nullptr path
(in waitDone) to call fl::task::run(0, fl::task::ExecFlags::SYSTEM) and ensure
the fl::task header is included if not already.
- Around line 292-323: The tight-wait fallback in
ChannelDriverPARLIOImpl::waitDone currently busy-waits using
fl::delayMicroseconds(50); change this to yield the scheduler like other drivers
by calling fl::task::run(0, fl::task::ExecFlags::SYSTEM) in the else branch so
the loop yields correctly when detail::IParlioPeripheral* peripheral is null;
locate the else branch in waitDone and replace the delayMicroseconds call with
the task::run yield.

In `@src/platforms/esp/32/watchdog_esp32_idf4.hpp`:
- Around line 137-139: The current handler in watchog_esp32_idf4.hpp converts
ESP_ERR_INVALID_STATE to ESP_OK to accept an already-initialized TWDT (in
deinit_existing_watchdog()), but it doesn't record that the requested timeout_ms
wasn't applied; update the ESP_ERR_INVALID_STATE branch to keep the conversion
but also emit a debug/warn log indicating the watchdog was already armed and the
requested timeout_ms may not have been applied (reference the err comparison for
ESP_ERR_INVALID_STATE, the deinit_existing_watchdog() flow, and the
log_watchdog_status() usage) so callers can distinguish requested vs actual
timeout.
🪄 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: 81f9d6f3-a6eb-4908-9b59-5bb5b5e532c4

📥 Commits

Reviewing files that changed from the base of the PR and between ed860aa and d79e9c1.

📒 Files selected for processing (24)
  • ci/autoresearch/args.py
  • ci/autoresearch/context.py
  • ci/autoresearch/phases.py
  • ci/boards.py
  • examples/AutoResearch/AutoResearch.ino
  • examples/AutoResearch/AutoResearchRemote.cpp
  • platformio.ini
  • src/fl/channels/driver.h
  • src/fl/channels/manager.cpp.hpp
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp.hpp
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.h
  • src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp
  • src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.h
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.h
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.cpp.hpp
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.h
  • src/platforms/esp/32/watchdog_esp32.cpp.hpp
  • src/platforms/esp/32/watchdog_esp32.h
  • src/platforms/esp/32/watchdog_esp32.impl.hpp
  • src/platforms/esp/32/watchdog_esp32_idf4.hpp
  • src/platforms/esp/32/watchdog_esp32_idf5.hpp

Comment thread ci/autoresearch/phases.py Resolved
@zackees zackees changed the title feat: add ISR-backed channel waits feat: add ISR-backed channel poll wakeups Jun 9, 2026
@zackees
zackees force-pushed the feat/2991-tight-timing branch from 026ef8f to 7b52467 Compare June 9, 2026 14:27

@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: 5

🧹 Nitpick comments (1)
src/fl/channels/manager.cpp.hpp (1)

62-98: ⚡ Quick win

Make the poll-needed flag ordering explicit.

mPollNeededSignalPending is the new ISR/task handoff flag, but every exchange()/store() here currently depends on the implicit default ordering. Please spell out the intended acquire/release semantics so this wakeup protocol is reviewable and stays aligned with the ISR-sharing contract.

As per coding guidelines, "ISR-shared state: any field written from ISR and read from task context (or vice versa) must be fl::atomic with explicit memory_order or protected by portENTER_CRITICAL_ISR/portENTER_CRITICAL. Never use volatile alone."

🤖 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/fl/channels/manager.cpp.hpp` around lines 62 - 98, The
mPollNeededSignalPending atomic uses implicit memory ordering; make the ISR↔task
handoff explicit: when setting the flag in notifyPollNeeded (the ISR/path that
calls mPollNeededSignalPending.exchange(true)), pass an explicit
memory_order_release; when clearing/observing the flag from task context
(drainPollNeededSignals' mPollNeededSignalPending.store(false),
waitForPollNeededSignal's mPollNeededSignalPending.store(false) and the fallback
mPollNeededSignalPending.exchange(false)), use memory_order_acquire or
memory_order_acq_rel for read-modify-write ops so the task properly synchronizes
with the ISR. Update those calls to use std::memory_order (release for the
writer, acquire or acq_rel for the reader/clearer) on mPollNeededSignalPending
so the wakeup protocol is explicit and reviewable.

Source: Coding guidelines

🤖 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 `@src/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp.hpp`:
- Around line 405-409: When registerTransmitCallback(...) fails after
initialize() has succeeded, clean up before returning: call the class
deinitialization routine (e.g. deinitialize() or the existing cleanup method
used by initialize()) to release the peripheral and restore hardware state,
ensure mInitialized is set to false, and only then return false; specifically
modify the failure branch after
mPeripheral->registerTransmitCallback(reinterpret_cast<void*>(&isrTransmitDone),
this) to invoke the deinit/cleanup path and reset mInitialized so retries won't
leave the peripheral half-open.

In `@src/platforms/esp/32/drivers/i2s/channel_driver_i2s.h`:
- Around line 190-192: mBusy is accessed from ISR (isrTransmitDone) and task
context (poll(), show(), teardown), so replace the volatile<bool> mBusy with
fl::atomic_bool (using explicit memory_order semantics) or protect all
reads/writes with the same ISR critical-section API; update the declaration of
mBusy and change all accesses in poll(), show(), teardown and isrTransmitDone to
use atomic operations (or wrap them with
portENTER_CRITICAL_ISR/portEXIT_CRITICAL_ISR and the normal
portENTER_CRITICAL/portEXIT_CRITICAL) so the ISR and task contexts use a single
consistent synchronization mechanism per coding guidelines.

In `@src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.cpp.hpp`:
- Around line 1590-1592: The ISR sets state->transmissionComplete and then calls
state->owner->mPollNeededCallback(), but poll() reads that flag from task
context causing a data race; change the shared flag type to fl::atomic<bool> (or
protect accesses with portENTER_CRITICAL_ISR/portENTER_CRITICAL) and update the
ISR to store(true) with std::memory_order_release and have poll() load() with
std::memory_order_acquire, or wrap both ISR write and task read in the
appropriate FreeRTOS critical sections to ensure correct synchronization between
ISR and task.

In `@src/platforms/esp/32/semaphore_esp32.cpp.hpp`:
- Around line 145-150: In CountingSemaphoreESP32::try_acquire_for, guard against
negative or zero durations before calling pdMS_TO_TICKS: convert rel_time to ms,
and if ms.count() <= 0 simply return try_acquire() (no wait) instead of passing
the value to pdMS_TO_TICKS; otherwise proceed to compute TickType_t ticks =
pdMS_TO_TICKS(ms.count()) and keep the existing adjustment that sets ticks = 1
when ms.count() > 0 && ticks == 0 so short positive waits still block briefly.

---

Nitpick comments:
In `@src/fl/channels/manager.cpp.hpp`:
- Around line 62-98: The mPollNeededSignalPending atomic uses implicit memory
ordering; make the ISR↔task handoff explicit: when setting the flag in
notifyPollNeeded (the ISR/path that calls
mPollNeededSignalPending.exchange(true)), pass an explicit memory_order_release;
when clearing/observing the flag from task context (drainPollNeededSignals'
mPollNeededSignalPending.store(false), waitForPollNeededSignal's
mPollNeededSignalPending.store(false) and the fallback
mPollNeededSignalPending.exchange(false)), use memory_order_acquire or
memory_order_acq_rel for read-modify-write ops so the task properly synchronizes
with the ISR. Update those calls to use std::memory_order (release for the
writer, acquire or acq_rel for the reader/clearer) on mPollNeededSignalPending
so the wakeup protocol is explicit and reviewable.
🪄 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: 1ff61d45-abd7-480a-9d61-58854f0fc462

📥 Commits

Reviewing files that changed from the base of the PR and between d79e9c1 and 026ef8f.

📒 Files selected for processing (17)
  • src/fl/channels/driver.h
  • src/fl/channels/manager.cpp.hpp
  • src/fl/channels/manager.h
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp.hpp
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.h
  • src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.h
  • src/platforms/esp/32/drivers/parlio/parlio_engine.cpp.hpp
  • src/platforms/esp/32/drivers/parlio/parlio_engine.h
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.cpp.hpp
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.h
  • src/platforms/esp/32/semaphore_esp32.cpp.hpp
  • src/platforms/esp/32/semaphore_esp32.h
  • src/platforms/shared/atomic.h
✅ Files skipped from review due to trivial changes (1)
  • src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp

Comment thread src/fl/channels/driver.h Resolved
@zackees
zackees force-pushed the feat/2991-tight-timing branch from 7b52467 to 938da02 Compare June 9, 2026 14:43

@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: 4

🤖 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 `@examples/AutoResearch/AutoResearchRemote.cpp`:
- Around line 461-470: The device-side handler currently enforces
tight_timing_iterations to be in [1,64] (see tight_timing_iterations,
config["tightTimingIterations"], and the response error branch), but the host
RPC contract in ci/autoresearch/args.py and ci/autoresearch/phases.py allows any
value >= 1; make them consistent by removing or relaxing the device upper-bound
check: either validate against a shared constant (e.g.,
TIGHT_TIMING_ITERATIONS_MAX) used by both host and device, or simply change the
condition so only tight_timing_iterations < 1 is rejected and values >= 1 are
accepted, updating the response error/message logic accordingly.
- Around line 635-653: The current logic sets tight_timing_passed=false for
legacy/unsupported paths and always does passed = passed && tight_timing_passed,
causing unsupported drivers to fail; change the code so the overall passed is
only updated when the tight-timing metric is actually supported. Specifically,
after the measure_tight_timing branch (or the legacy branch that sets
tight_timing_response), query the tight-timing supported flag on
tight_timing_response (or a tight_timing_supported boolean returned/filled by
measureTightTiming) and only AND passed with tight_timing_passed when that
supported flag is true; do not modify passed when supported is false
(legacy/unsupported path). Ensure you reference measure_tight_timing,
use_legacy_api, tight_timing_response, tight_timing_passed, and passed when
applying the change.

In `@src/platforms/esp/32/drivers/parlio/parlio_engine.cpp.hpp`:
- Around line 614-616: poll() currently clears mStreamComplete and mTransmitting
before calling waitAllDone(0), which allows a spurious transition from DRAINING
to READY on a fast wake; change the logic so the engine remains in DRAINING
until waitAllDone(0) returns success — do not clear mStreamComplete or
mTransmitting (or restore them) until waitAllDone(0) succeeds. Locate the poll()
method and update the sequence around the waitAllDone(0) call (and where
mPollNeededCallback is invoked) so that clearing mStreamComplete/mTransmitting
happens only after a successful waitAllDone(0) and the state transition to READY
occurs only then.

In `@src/platforms/esp/32/watchdog_esp32.impl.hpp`:
- Around line 156-163: esp32UnsubscribeMonitoredTask currently clears
s.monitored_task and s.monitored_task_added unconditionally which breaks reset
behavior if TWDT disable fails; update the logic so that
esp32UnsubscribeMonitoredTask only clears those fields after a successful
esp_task_wdt_delete (or when no delete was required), and adjust
Watchdog::disable to call unsubscribe only after fl::watchdog_disable() reports
success (or propagate that result back) so s.armed/s.monitored_task stay
consistent; refer to esp32UnsubscribeMonitoredTask, Watchdog::disable,
esp32WatchdogState, esp_task_wdt_delete, esp32MonitoredTask, and
esp32ResetMonitoredTask to locate and modify the code.
🪄 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: 4343e30c-9963-4c42-bd4e-7cfde000ffe7

📥 Commits

Reviewing files that changed from the base of the PR and between 026ef8f and 7b52467.

📒 Files selected for processing (29)
  • ci/autoresearch/args.py
  • ci/autoresearch/context.py
  • ci/autoresearch/phases.py
  • ci/boards.py
  • examples/AutoResearch/AutoResearch.ino
  • examples/AutoResearch/AutoResearchRemote.cpp
  • platformio.ini
  • src/fl/channels/driver.h
  • src/fl/channels/manager.cpp.hpp
  • src/fl/channels/manager.h
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp.hpp
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.h
  • src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.h
  • src/platforms/esp/32/drivers/parlio/parlio_engine.cpp.hpp
  • src/platforms/esp/32/drivers/parlio/parlio_engine.h
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.cpp.hpp
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.h
  • src/platforms/esp/32/semaphore_esp32.cpp.hpp
  • src/platforms/esp/32/semaphore_esp32.h
  • src/platforms/esp/32/watchdog_esp32.cpp.hpp
  • src/platforms/esp/32/watchdog_esp32.h
  • src/platforms/esp/32/watchdog_esp32.impl.hpp
  • src/platforms/esp/32/watchdog_esp32_idf4.hpp
  • src/platforms/esp/32/watchdog_esp32_idf5.hpp
  • src/platforms/shared/atomic.h
💤 Files with no reviewable changes (1)
  • src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp
✅ Files skipped from review due to trivial changes (3)
  • src/platforms/esp/32/watchdog_esp32.h
  • src/platforms/esp/32/watchdog_esp32.cpp.hpp
  • platformio.ini
🚧 Files skipped from review as they are similar to previous changes (22)
  • src/platforms/esp/32/watchdog_esp32_idf4.hpp
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.h
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h
  • src/platforms/shared/atomic.h
  • ci/boards.py
  • examples/AutoResearch/AutoResearch.ino
  • src/platforms/esp/32/semaphore_esp32.h
  • src/fl/channels/driver.h
  • src/platforms/esp/32/semaphore_esp32.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp.hpp
  • ci/autoresearch/args.py
  • ci/autoresearch/phases.py
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp
  • ci/autoresearch/context.py
  • src/platforms/esp/32/drivers/parlio/parlio_engine.h
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.cpp.hpp
  • src/fl/channels/manager.h
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.h
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.h
  • src/platforms/esp/32/watchdog_esp32_idf5.hpp
  • src/fl/channels/manager.cpp.hpp

@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/fl/channels/manager.cpp.hpp (1)

446-460: 💤 Low value

Duplicate timeout error logging.

When timeoutMs > 0 and time expires, the timeout check at lines 448-450 logs an error and returns. However, if pollNeededWaitSliceMs returns 0 (which happens when elapsed >= timeoutMs), lines 454-456 also log an error. In practice, the first check at 448 should catch the timeout before sliceMs becomes 0, but the redundant check adds unnecessary code and could cause double-logging if timing aligns poorly.

Consider removing the redundant slice-exhaustion error or consolidating the timeout handling.

♻️ Suggested simplification
     while (!condition()) {
         // Check timeout if specified
         if (timeoutMs > 0 && (millis() - startTime >= timeoutMs)) {
             FL_ERROR("ChannelManager: Timeout occurred while waiting for condition");
             return false;  // Timeout occurred
         }

         const u32 sliceMs = pollNeededWaitSliceMs(startTime, timeoutMs);
-        if (sliceMs == 0) {
-            FL_ERROR("ChannelManager: Timeout occurred while waiting for condition");
-            return false;
-        }
+        // sliceMs == 0 only when timeout already elapsed; handled above.
         if (waitForPollNeededSignal(sliceMs)) {
             continue;
         }
🤖 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/fl/channels/manager.cpp.hpp` around lines 446 - 460, The timeout is being
logged twice: once in the explicit timeout check inside the while loop (using
timeoutMs and startTime) and again when pollNeededWaitSliceMs(startTime,
timeoutMs) returns 0; remove the redundant error log in the sliceMs==0 branch.
Specifically, in the loop surrounding condition(), keep the FL_ERROR + return
false in the timeoutMs/startTime check and change the pollNeededWaitSliceMs(...)
== 0 case to simply return false (or return false without logging), leaving
waitForPollNeededSignal(...) logic unchanged; this removes duplicate logging
while preserving correct timeout behavior.
src/platforms/esp/32/channel_poll_signal_esp32.h (1)

1-2: ⚡ Quick win

Misleading comment contradicts actual namespace.

The comment // ok no namespace fl is incorrect - this file defines class ChannelPollSignal inside namespace fl::platforms (lines 12-14). Either remove the comment or update it to reflect the actual namespace structure.

♻️ Suggested fix
-// ok no namespace fl
+// ESP32 channel-manager poll wake signal (fl::platforms namespace)
 `#pragma` once
🤖 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/channel_poll_signal_esp32.h` around lines 1 - 2, Update
or remove the misleading top-of-file comment "// ok no namespace fl" in
src/platforms/esp/32/channel_poll_signal_esp32.h: the file actually defines
class ChannelPollSignal inside namespace fl::platforms, so either delete the
comment or replace it with an accurate note (e.g., indicating the class is
inside fl::platforms) to avoid confusion when locating the ChannelPollSignal
declaration and namespace block.
🤖 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/fl/channels/manager.cpp.hpp`:
- Around line 446-460: The timeout is being logged twice: once in the explicit
timeout check inside the while loop (using timeoutMs and startTime) and again
when pollNeededWaitSliceMs(startTime, timeoutMs) returns 0; remove the redundant
error log in the sliceMs==0 branch. Specifically, in the loop surrounding
condition(), keep the FL_ERROR + return false in the timeoutMs/startTime check
and change the pollNeededWaitSliceMs(...) == 0 case to simply return false (or
return false without logging), leaving waitForPollNeededSignal(...) logic
unchanged; this removes duplicate logging while preserving correct timeout
behavior.

In `@src/platforms/esp/32/channel_poll_signal_esp32.h`:
- Around line 1-2: Update or remove the misleading top-of-file comment "// ok no
namespace fl" in src/platforms/esp/32/channel_poll_signal_esp32.h: the file
actually defines class ChannelPollSignal inside namespace fl::platforms, so
either delete the comment or replace it with an accurate note (e.g., indicating
the class is inside fl::platforms) to avoid confusion when locating the
ChannelPollSignal declaration and namespace block.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 653e5bc1-b7b0-48df-aba1-3735968a394e

📥 Commits

Reviewing files that changed from the base of the PR and between 7b52467 and 938da02.

📒 Files selected for processing (32)
  • ci/autoresearch/args.py
  • ci/autoresearch/context.py
  • ci/autoresearch/phases.py
  • ci/boards.py
  • examples/AutoResearch/AutoResearch.ino
  • examples/AutoResearch/AutoResearchRemote.cpp
  • platformio.ini
  • src/fl/channels/driver.h
  • src/fl/channels/manager.cpp.hpp
  • src/fl/channels/manager.h
  • src/platforms/channel_poll_signal.h
  • src/platforms/esp/32/channel_poll_signal_esp32.h
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp.hpp
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.h
  • src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.h
  • src/platforms/esp/32/drivers/parlio/parlio_engine.cpp.hpp
  • src/platforms/esp/32/drivers/parlio/parlio_engine.h
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.cpp.hpp
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.h
  • src/platforms/esp/32/semaphore_esp32.cpp.hpp
  • src/platforms/esp/32/semaphore_esp32.h
  • src/platforms/esp/32/watchdog_esp32.cpp.hpp
  • src/platforms/esp/32/watchdog_esp32.h
  • src/platforms/esp/32/watchdog_esp32.impl.hpp
  • src/platforms/esp/32/watchdog_esp32_idf4.hpp
  • src/platforms/esp/32/watchdog_esp32_idf5.hpp
  • src/platforms/shared/atomic.h
  • src/platforms/shared/channel_poll_signal.h
💤 Files with no reviewable changes (1)
  • src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp
✅ Files skipped from review due to trivial changes (4)
  • src/platforms/shared/channel_poll_signal.h
  • src/platforms/esp/32/watchdog_esp32.h
  • src/platforms/channel_poll_signal.h
  • src/platforms/esp/32/watchdog_esp32.cpp.hpp
🚧 Files skipped from review as they are similar to previous changes (20)
  • src/platforms/shared/atomic.h
  • src/platforms/esp/32/watchdog_esp32_idf5.hpp
  • examples/AutoResearch/AutoResearch.ino
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.h
  • ci/autoresearch/context.py
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.h
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp.hpp
  • src/platforms/esp/32/watchdog_esp32_idf4.hpp
  • src/platforms/esp/32/semaphore_esp32.h
  • src/platforms/esp/32/drivers/parlio/parlio_engine.cpp.hpp
  • ci/boards.py
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.cpp.hpp
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h
  • src/platforms/esp/32/semaphore_esp32.cpp.hpp
  • src/platforms/esp/32/drivers/parlio/parlio_engine.h
  • ci/autoresearch/args.py
  • ci/autoresearch/phases.py
  • examples/AutoResearch/AutoResearchRemote.cpp
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.h

@zackees
zackees force-pushed the feat/2991-tight-timing branch from 938da02 to 1d18e95 Compare June 9, 2026 15:24

@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: 5

🤖 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 `@examples/AutoResearch/AutoResearchRemote.cpp`:
- Line 177: Save the current global brightness using FastLED.getBrightness()
before calling FastLED.setBrightness(255), then ensure you restore that saved
value on every return path (including error paths) after the diagnostic
completes; implement this by wrapping the brightness change in a
try/finally-style scope guard or explicit restore so
FastLED.setBrightness(savedBrightness) is always called, or use an RAII helper
class to restore brightness in its destructor.
- Around line 282-285: The current logic sets metric "message" based only on
out_passed, which overwrites a timeout failure when timed_out is true; update
the message assignment around the out_passed calculation (variables: out_passed,
timed_out, max_overhead_us, max_allowed_overhead_us) so you first check
timed_out and set the metric message to indicate the wait timeout (e.g.,
"timeout waiting for sample") if timed_out is true, otherwise set the existing
messages for "tight timing within budget" or "tight timing exceeded budget";
ensure metric.set("passed", out_passed) still reflects the boolean but the
message preserves timeout as the reported failure reason.

In `@src/fl/channels/driver.h`:
- Around line 88-109: set()/clear() currently update mContext and mCallback
separately which can leave invoke() observing mismatched pairs; change to
publish a single atomic snapshot pointer (e.g. an immutable heap-allocated
struct holding PollNeededCallback::Callback and void* context) and replace
mContext/mCallback with a single std::atomic<Snapshot*> member, then update
set() by allocating a new Snapshot and atomically store it with
memory_order_release (clearing will atomically store nullptr), and change
invoke() to atomically load the Snapshot* with memory_order_acquire and call
snapshot->callback(snapshot->context); ensure to free the previous snapshot
safely (delete old pointer after successful store) to avoid leaks and keep ISR
reads lock-free.

In `@src/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp.hpp`:
- Around line 406-410: The TX ISR is left registered to the singleton peripheral
when ChannelEngineI2S is destroyed; update the ChannelEngineI2S teardown to
unregister the transmit callback and/or deinitialize the peripheral so the ISR
won't point at freed memory. In the ChannelEngineI2S destructor (or its
deinitialize/stop method) call the peripheral's unregister or
registerTransmitCallback with a null handler/context (matching how you
registered via mPeripheral->registerTransmitCallback and the isrTransmitDone
symbol), then call mPeripheral->deinitialize() only after the callback is
cleared and before freeing buffers to ensure no stale hardware state or dangling
ISR references remain.

In `@src/platforms/esp/32/drivers/parlio/parlio_engine.cpp.hpp`:
- Around line 614-615: The ISR-updated completion flags in ParlioIsrContext
(used by txDoneCallback() and read by poll()/other task code) are currently
non-atomic and race-prone; replace those bare shared fields and any uses of
FL_MEMORY_BARRIER with fl::atomic<T> (choose appropriate integral/enum type) and
use explicit memory orders (e.g., memory_order_release in txDoneCallback() when
setting the flag and memory_order_acquire in poll() when reading it), or
alternatively wrap all writes/reads in the FreeRTOS critical-section API
(taskENTER_CRITICAL/taskEXIT_CRITICAL) to serialize ISR/task access; apply the
same change to the other ISR-shared flags referenced around the other occurrence
noted (the block around the similar completion state usage) so txDoneCallback(),
poll(), and any other readers use atomic operations or critical sections
consistently.
🪄 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: 7a6409c7-32ef-4a3e-b807-cd22515e3513

📥 Commits

Reviewing files that changed from the base of the PR and between 938da02 and 1d18e95.

📒 Files selected for processing (33)
  • ci/autoresearch/args.py
  • ci/autoresearch/context.py
  • ci/autoresearch/phases.py
  • ci/boards.py
  • examples/AutoResearch/AutoResearch.ino
  • examples/AutoResearch/AutoResearchRemote.cpp
  • platformio.ini
  • src/fl/channels/driver.h
  • src/fl/channels/manager.cpp.hpp
  • src/fl/channels/manager.h
  • src/fl/stl/atomic.h
  • src/platforms/channel_poll_signal.h
  • src/platforms/esp/32/channel_poll_signal_esp32.h
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp.hpp
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.h
  • src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.h
  • src/platforms/esp/32/drivers/parlio/parlio_engine.cpp.hpp
  • src/platforms/esp/32/drivers/parlio/parlio_engine.h
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.cpp.hpp
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.h
  • src/platforms/esp/32/semaphore_esp32.cpp.hpp
  • src/platforms/esp/32/semaphore_esp32.h
  • src/platforms/esp/32/watchdog_esp32.cpp.hpp
  • src/platforms/esp/32/watchdog_esp32.h
  • src/platforms/esp/32/watchdog_esp32.impl.hpp
  • src/platforms/esp/32/watchdog_esp32_idf4.hpp
  • src/platforms/esp/32/watchdog_esp32_idf5.hpp
  • src/platforms/shared/atomic.h
  • src/platforms/shared/channel_poll_signal.h
💤 Files with no reviewable changes (1)
  • src/platforms/esp/32/drivers/i2s/i2s_lcd_cam_peripheral_esp.cpp.hpp
✅ Files skipped from review due to trivial changes (1)
  • src/platforms/channel_poll_signal.h
🚧 Files skipped from review as they are similar to previous changes (25)
  • src/platforms/esp/32/watchdog_esp32.cpp.hpp
  • src/platforms/shared/atomic.h
  • src/platforms/esp/32/watchdog_esp32_idf5.hpp
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h
  • src/fl/channels/manager.h
  • ci/autoresearch/context.py
  • src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp
  • src/platforms/esp/32/watchdog_esp32_idf4.hpp
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.h
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.h
  • ci/autoresearch/args.py
  • examples/AutoResearch/AutoResearch.ino
  • src/platforms/esp/32/watchdog_esp32.h
  • src/platforms/shared/channel_poll_signal.h
  • src/platforms/esp/32/semaphore_esp32.h
  • src/platforms/esp/32/drivers/i2s/channel_driver_i2s.h
  • src/platforms/esp/32/channel_poll_signal_esp32.h
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp
  • src/platforms/esp/32/semaphore_esp32.cpp.hpp
  • platformio.ini
  • ci/autoresearch/phases.py
  • src/fl/channels/manager.cpp.hpp
  • ci/boards.py
  • src/platforms/esp/32/watchdog_esp32.impl.hpp
  • src/platforms/esp/32/drivers/rmt/rmt_5/channel_driver_rmt.cpp.hpp

Comment thread src/fl/channels/driver.h Resolved
@zackees
zackees merged commit 27a1583 into master Jun 9, 2026
6 of 7 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 9, 2026
pull Bot pushed a commit to manmuqingshan/FastLED that referenced this pull request Jun 14, 2026
…r real-DMA semantics (FastLED#2992 follow-up)

After FastLED#2992 ("feat: add ISR-backed channel poll wakeups"), `ParlioEngine`
runs `beginTransmission()` in ASYNC mode: the last txDone ISR sets
`mStreamComplete=true` and the *next* `poll()` tick observes that flag
and clears `mTransmitting` (the gate that begins a new transmission).
The old engine cleared `mTransmitting` directly in the ISR, so callers
that issued back-to-back `beginTransmission()` calls without an
intervening `poll()` still worked. After FastLED#2992 they no longer do.

Two `parlio_driver` unit tests issue exactly that pattern and have been
failing on master since 2026-06-09 (every CI run on PRs FastLED#2998, FastLED#3001,
and the just-merged FastLED#3003 fails the same way):

  FAIL: ParlioEngine mock - transmission history clearing at
    tests/platforms/esp/32/drivers/parlio/parlio_driver.cpp:671
      :694: count2 > 0
      :695: mock.getTransmitCount() > count1
  REQUIRE FAILED: parlio_driver.cpp:1029: tx_ok

On real hardware the engine's own line-1845 drain pattern
(`mPeripheral->waitAllDone(100)` at the top of `beginTransmission()`)
gives the ISR a chance to fire and then a `poll()` tick can clear
`mTransmitting`. The mock, by contrast, fires txDone callbacks
synchronously inside `transmit()` and used to noop `waitAllDone()`, so
no `poll()` tick ever ran — `mTransmitting` stayed stuck at true
forever and the second `beginTransmission()` short-circuited with
"transmission already in progress".

Fix the mock, not the test (per the maintainer's "gap in the mock vs
the real thing" framing): drive one `ParlioEngine::poll()` tick from
the mock's `waitAllDone()` and `deinitialize()`. Those are the two
real-hardware-faithful boundaries where "no active DMA" is the
contract — `waitAllDone()` is the engine's own pre-transmission drain
point, and `deinitialize()` is what the engine calls from its
config-match re-init path at parlio_engine.cpp.hpp:1411 (the route
test 1029 takes). A single `mSettlingEngine` re-entrancy flag breaks
the obvious recursion (`poll()` itself calls `waitAllDone(0)`).

The mock stays fully synchronous and single-threaded — no new threads,
no new deferred-callback states, no churn in the existing
pumpDeferredCallbacks/mFiringCallbacks machinery. Only the engine
async-state contract gets one extra tick at each transmit boundary.

No engine changes. No test changes. Verified:
- `bash test parlio_driver` passes (both originally failing tests)
- `bash test parlio_driver --debug` passes (ASAN/LSAN/UBSAN clean)
- `bash lint --cpp` clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

fix(esp32-s3): verify and finish #2420 FastLED.show() timing regression

1 participant