Repository navigation
Conversation
Restores websocket throughput on ESP32-S3 under the I2S channel driver and any other driver that spin-waits on DMA via `task::run(us, ExecFlags::SYSTEM)`. Diagnosis --------- The Mar 10 cooperative-yield fix (#2167) and the Apr 5 needsDeepYield() machinery intended a `vTaskDelay(>=1)` in the SYSTEM-yield path when WiFi was active, so that lower-priority lwIP tasks could run. Two regressions made the deep yield degenerate to `taskYIELD()` (which does NOT yield to lower-priority tasks): 1. `pumpCoroutines(1000)` computed ticks from microseconds. On the default ESP-IDF tick rate of 100 Hz, `1000us / 10000us-per-tick = 0` → `taskYIELD()` instead of `vTaskDelay(1)`. Arduino-ESP32 at 1000 Hz happened to work; MoonLight and other ESP-IDF-native projects hit the bad path and saw ~1 FPS websockets. 2. The deep-yield gate relied on `esp_wifi_get_mode() != WIFI_MODE_NULL`. This missed Ethernet-only deployments and the pre-WiFi.begin() window, both of which still need lwIP to get CPU time. Fix --- * `pumpCoroutines()` rounds a non-zero microseconds request UP to at least 1 FreeRTOS tick. A 0us request still just does `taskYIELD()`. * `task::run(us, SYSTEM)` takes the deep-yield path whenever `microseconds > 0`, independent of WiFi state. Tests ----- * All 299 host C++ tests still pass. * Lint clean. * esp32s3 Blink and SpecialDrivers/ESP/DriverTest compile cleanly. * Hardware verification of FPS/websockets behavior is the user's responsibility; see PR description. Addresses Issue 1 in #2254. Issues 2 (SPI rendering) and 3 (audio FPS) are not addressed by this commit. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthroughThe PR modifies yield and delay behavior in the task execution layer and ESP32 coroutine runtime. It unconditionally applies deep yielding based on time budget availability rather than conditional detection, and explicitly handles zero-wait requests while rounding up tick conversions in FreeRTOS delays. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/platforms/esp/32/coroutine_esp32.impl.hpp (1)
65-85: Comment/implementation mismatch: "Round UP" is actually a min-1 clamp.The comment says ticks are rounded up, but the code truncates (
us / tick_period_us) and only bumps0to1. Forusvalues strictly between one and two tick periods (e.g.us = 15000at a 100 Hz tick wheretick_period_us = 10000),ticksbecomes1(~10 ms) rather than2(~20 ms) as a true ceiling would produce. The fix goal ("≥ 1 tick") is met for typical sub-tick callers (the only path that actually exercises the clamp), but if you intend real ceiling semantics as documented, use:♻️ Optional ceiling-division refactor
- const fl::u32 tick_period_us = 1000000u / configTICK_RATE_HZ; - fl::u32 ticks = us / tick_period_us; - if (us == 0) { // Caller explicitly asked for no delay — just yield among // equal/higher priority tasks. taskYIELD(); return; } - // Caller asked for a non-zero wait. Round UP to at least 1 tick ... - if (ticks == 0) { - ticks = 1; - } + // Caller asked for a non-zero wait. Ceiling-divide to guarantee + // at least 1 tick so that lower-priority tasks (e.g. lwIP/WiFi) + // actually get CPU time. See issue `#2254` (Issue 1). + const fl::u32 tick_period_us = 1000000u / configTICK_RATE_HZ; + const fl::u32 ticks = (us + tick_period_us - 1) / tick_period_us; vTaskDelay(ticks);Note: per FreeRTOS semantics
vTaskDelay(n)guarantees a minimum ofn-1ticks, sovTaskDelay(1)can return almost immediately if called just before a tick boundary — the task still enters the delayed list, which is what allows lwIP/WiFi tasks to run, so the spin-wait starvation fix still works.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/coroutine_esp32.impl.hpp` around lines 65 - 85, The comment is wrong: the code currently truncates us/tick_period_us and only clamps zero to one; change the computation of ticks in the coroutine delay routine so it performs a proper ceiling division (i.e. ticks = (us + tick_period_us - 1) / tick_period_us) while preserving the early-return for us == 0 and the subsequent vTaskDelay(ticks) call; update the calculation that sets fl::u32 ticks so callers requesting partial ticks are rounded up to the next whole tick.src/fl/task/executor.cpp.hpp (1)
135-141: Extract the hardcoded1000µs hint into a named constant for consistency and clarity.The magic number
1000appears twice in this code path (lines 137 and 147) and should be unified as a named constant. The suggestedkDeepYieldHintUsmakes the intent explicit and ensures both sites remain synchronized if the hint value needs future adjustment.The change to always call
pumpCoroutines(1000)whenmicroseconds > 0(removing the priorneedsDeepYield()gate) is safe across platforms:
- Arduino:
pumpCoroutinesis a no-op; no behavioral change.- Teensy: Suspend only occurs if called from within a coroutine; calling from the main executor thread is safe.
- ESP32: Now always performs
vTaskDelaywith proper FreeRTOS tick rounding (≥1 tick), which correctly prevents WiFi/lwIP starvation.- WASM: No-op from main thread; calling from executor context is safe.
- Stub: Runs pending coroutines; minimal overhead, no functional issue.
Note that with this change,
microseconds == 0is now the only entry point that takes the lightweightfl::yield()path. Callers relying on smallmicrosecondsvalues (e.g.,task::run(100, SYSTEM)) will block for approximately 1 ms per iteration on platforms with cooperative scheduling, so budgets should account for this minimum granularity.Proposed constant extraction:
Named-constant refactor
+// Per-iteration deep-yield hint. On ESP32 this is clamped to at least +// 1 FreeRTOS tick by CoroutineRuntimeEsp32::pumpCoroutines. +static constexpr fl::u32 kDeepYieldHintUs = 1000; + void run(fl::u32 microseconds, ExecFlags flags) { ... if (do_system) { if (microseconds > 0) { - fl::platforms::ICoroutineRuntime::instance().pumpCoroutines(1000); + fl::platforms::ICoroutineRuntime::instance().pumpCoroutines(kDeepYieldHintUs); } else { fl::yield(); } } // COROUTINES: Platform cooperative coroutines (pumpCoroutines) if (do_coroutines) { auto time_left = remaining(); if (time_left) { - fl::u32 sleep_us = fl::min(1000u, time_left); + fl::u32 sleep_us = fl::min(kDeepYieldHintUs, time_left); fl::platforms::ICoroutineRuntime::instance().pumpCoroutines(sleep_us); } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fl/task/executor.cpp.hpp` around lines 135 - 141, Extract the hardcoded 1000µs hint into a named constant (e.g., kDeepYieldHintUs) and replace both occurrences of the literal in the executor path so they stay synchronized; update the branch that currently calls fl::platforms::ICoroutineRuntime::instance().pumpCoroutines(1000) to use kDeepYieldHintUs and ensure the other site that previously used 1000 is changed the same way, leaving the fl::yield() call for the microseconds==0 path unchanged so behavior matches the review description.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/fl/task/executor.cpp.hpp`:
- Around line 135-141: Extract the hardcoded 1000µs hint into a named constant
(e.g., kDeepYieldHintUs) and replace both occurrences of the literal in the
executor path so they stay synchronized; update the branch that currently calls
fl::platforms::ICoroutineRuntime::instance().pumpCoroutines(1000) to use
kDeepYieldHintUs and ensure the other site that previously used 1000 is changed
the same way, leaving the fl::yield() call for the microseconds==0 path
unchanged so behavior matches the review description.
In `@src/platforms/esp/32/coroutine_esp32.impl.hpp`:
- Around line 65-85: The comment is wrong: the code currently truncates
us/tick_period_us and only clamps zero to one; change the computation of ticks
in the coroutine delay routine so it performs a proper ceiling division (i.e.
ticks = (us + tick_period_us - 1) / tick_period_us) while preserving the
early-return for us == 0 and the subsequent vTaskDelay(ticks) call; update the
calculation that sets fl::u32 ticks so callers requesting partial ticks are
rounded up to the next whole tick.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 53c9858e-6f1f-44fc-8430-f5d47832490b
📒 Files selected for processing (2)
src/fl/task/executor.cpp.hppsrc/platforms/esp/32/coroutine_esp32.impl.hpp
📊 Header Compilation PerformanceTotal Time: 1155.35ms Top 5 Slowest Headers
Warnings
Full Report |
…tive (#2254) Restores WiFi / Ethernet / lwIP throughput on ESP32-S3 when the I2S LCD_CAM channel driver (and any other driver that spin-waits on DMA via `task::run(us, ExecFlags::SYSTEM)`) is active. Addresses **Issue 1** of #2254. Two regressions made the cooperative yield path degenerate back into `taskYIELD()`, which does NOT yield to lower-priority tasks: 1. **Tick-rate truncation** in `pumpCoroutines()`. On the default ESP-IDF tick rate of 100 Hz, `tick_period_us = 10000`, so a sub-tick request such as `pumpCoroutines(1000)` computed `ticks = 0` and fell through to `taskYIELD()`. Arduino-ESP32 at 1000 Hz tick happened to work; ESP-IDF-native projects (MoonLight among them) hit the bad path and saw ~1 FPS websockets while LEDs rendered correctly. 2. **Over-narrow deep-yield gate** in `task::run(us, ExecFlags::SYSTEM)`. The SYSTEM yield only took the deep path when `esp_wifi_get_mode() != WIFI_MODE_NULL`. That condition misses: - Ethernet-only deployments (no WiFi mode, but lwIP is live). - The pre-`WiFi.begin()` window where the mode is still WIFI_MODE_NULL but network stacks may be initializing. - Weak-linkage edge cases where `esp_wifi_get_mode` resolves to nullptr even when WiFi is in use. Fix: - `src/platforms/esp/32/coroutine_esp32.impl.hpp`: `pumpCoroutines()` now rounds a non-zero microseconds request UP to at least 1 FreeRTOS tick. `us == 0` still just does `taskYIELD()`. - `src/fl/task/executor.cpp.hpp`: `task::run(us, ExecFlags::SYSTEM)` takes the deep-yield path whenever `microseconds > 0`, independent of WiFi mode. This is the path used by every driver's DMA spin-wait (I2S, SPI, LCD_SPI, LCD_CLOCKLESS, LCD_RGB, PARLIO, RMT, UART, I2S_SPI) and by `FastLED.show()`'s minFPS wait. Net effect: any spin-wait loop that calls `task::run(>0, SYSTEM)` now guarantees at least one FreeRTOS tick of delay per iteration on ESP32, freeing the CPU for lwIP / WiFi / Ethernet tasks. Validation on attached ESP32-S3: - `bash test --cpp`: 301/301 tests pass - `bash autoresearch esp32s3 --net`: 3/3 HTTP loopback tests PASS - `bash autoresearch esp32s3 --rmt --strip-sizes 100`: PASS (1 test, 103ms) - `bash autoresearch esp32s3 --spi --strip-sizes 100`: PASS (2/2 frames) - `bash autoresearch esp32s3 --lcd`: pre-existing harness RPC timeout (same behavior on master, unrelated to this fix) This is a re-application of the diff from the previously-closed PR #2290. Refs #2254 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Restores WiFi / Ethernet / lwIP throughput on ESP32-S3 when the I2S LCD_CAM channel driver (and any other driver that spin-waits on DMA via
task::run(us, ExecFlags::SYSTEM)) is active. Addresses Issue 1 of #2254.Sub-issues from #2254
Diagnosis
The Mar 10 cooperative-yield refactor (#2167) and the Apr 5
needsDeepYield()machinery intended avTaskDelay(>=1)in the SYSTEM-yield path when WiFi was active, so that lower-priority lwIP tasks could run during LED DMA spin-waits. Two regressions made the deep yield degenerate back totaskYIELD(), which does not yield to lower-priority tasks:Tick-rate truncation.
pumpCoroutines(1000)insrc/platforms/esp/32/coroutine_esp32.impl.hppcomputes ticks asus / tick_period_us. On the default ESP-IDF tick rate of 100 Hz,1000 / 10000 = 0→taskYIELD()instead ofvTaskDelay(1). Arduino-ESP32 at 1000 Hz happened to work; ESP-IDF-native projects (MoonLight among them) hit the bad path and saw ~1 FPS websockets while LEDs rendered correctly.Over-narrow deep-yield gate. The SYSTEM yield in
executor.cpp.hpponly took the deep path whenesp_wifi_get_mode() != WIFI_MODE_NULL. That condition misses:WiFi.begin()window where the mode is stillWIFI_MODE_NULLbut network stacks may be initializing.esp_wifi_get_moderesolves tonullptreven when WiFi is in use.Fix
Two minimal changes:
src/platforms/esp/32/coroutine_esp32.impl.hpp—pumpCoroutines()now rounds a non-zero microseconds request UP to at least 1 FreeRTOS tick. A 0 us request still just doestaskYIELD().src/fl/task/executor.cpp.hpp—task::run(us, ExecFlags::SYSTEM)takes the deep-yield path whenevermicroseconds > 0, independent of WiFi mode. This is the path used by every driver's DMA spin-wait (I2S, SPI, LCD_SPI, LCD_CLOCKLESS, LCD_RGB, PARLIO, RMT, UART, I2S_SPI) and byFastLED.show()'s minFPS wait.Net effect: any spin-wait loop that calls
task::run(>0, SYSTEM)now guarantees at least one FreeRTOS tick of delay per iteration on ESP32, freeing the CPU for lwIP / WiFi / Ethernet tasks.What I built / tested locally
bash test --cpp— 299 / 299 tests pass.bash lint— clean (Python, C++, JS, Meson).bash compile esp32s3 --examples Blink— succeeds.bash compile esp32s3 --examples SpecialDrivers/ESP/DriverTest— succeeds.Hardware verification (USER action required)
I cannot run on a physical board. Please verify on ESP32-S3 with WiFi + I2S channel driver + websockets:
If FPS regresses significantly because a driver is completing DMA in well under one tick, please report — we may need a
vTaskDelay(0)+ tight re-check fast-path for ultra-short DMA transfers.Not addressed in this PR
Issue 2 (SPI driver — incorrect LED output) — I read the LCD_SPI driver (
channel_driver_lcd_spi.cpp.hpp,lcd_spi_peripheral_esp.cpp.hpp) and the fix(esp32): resolve SPI/LCD_SPI buffer growth failure on channel reuse #2251 fix. I could not identify a plausible root cause from code inspection alone — the transpose encoder, the APA102 frame encoder, the chunked DMA streaming, and the buffer-reallocation fix from fix(esp32): resolve SPI/LCD_SPI buffer growth failure on channel reuse #2251 all look internally consistent. Diagnosing the visible rendering defect realistically needs the video reference reproduced on a bench. Leaving open.Issue 3 (Audio driver reduces FPS 100→60) — Confirmed by code inspection: the audio pump runs via
fl::task::every_ms(1).then(...)insrc/fl/audio/audio_processor.cpp.hpp::createWithAutoInput, which executes on whichever thread callstask::run(... TASKS ...)— i.e. the LED main loop. The fix is to dispatch audio pumping to its own FreeRTOS task (TaskCoroutineESP32::create()already exists insrc/platforms/esp/32/coroutine_esp32.impl.hpp). This requires auditing Processor / Context thread safety to avoid races on shared detector state, which I intentionally did not gold-plate in this PR. Leaving open as a follow-up.Refs #2254
🤖 Generated with Claude Code
Summary by CodeRabbit