Skip to content

perf(channels): runtime NetworkDetector-gated yield in waitForCondition (refs #2815) - #2817

Merged
zackees merged 1 commit into
masterfrom
perf/2815-network-gated-yield
Jun 5, 2026
Merged

zackees merged 1 commit into
masterfrom
perf/2815-network-gated-yield

Conversation

@zackees

@zackees zackees commented Jun 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Refs #2815 (Track 2 only).

Replaces the compile-time #if defined(FL_IS_ESP_32P4) carve-out in the channels wait loops with a runtime fl::NetworkDetector::isAnyNetworkActive() check. When no radio is up, the wait collapses to a fast fl::yield() path (no FreeRTOS tick floor). When a radio is up, the existing deep yield is preserved so WiFi / lwIP / BT controller tasks don't starve (#2254).

This generalizes the #2493 ESP32-P4 carve-out into the actual condition that motivates it ("is a radio actually running?"), removing the platform-specific branch entirely.

Before / after

// Before -- compile-time, ESP32-P4 only:
#if defined(FL_IS_ESP_32P4)
    task::run(0, task::ExecFlags::SYSTEM);
#else
    task::run(250, task::ExecFlags::SYSTEM);
#endif

// After -- runtime, every platform:
if (fl::NetworkDetector::isAnyNetworkActive()) {
    task::run(250, task::ExecFlags::SYSTEM);  // keep WiFi/lwIP/BT alive
} else {
    task::run(0, task::ExecFlags::SYSTEM);    // fast yield, no tick floor
}

Why this fixes the #2420 regression

task::run(250, SYSTEM) resolves to pumpCoroutines(1000) -> vTaskDelay(>=1 tick), which on FreeRTOS at CONFIG_FREERTOS_HZ=1000 is a >= 1 ms floor per spin iteration. For a sketch with no WiFi.begin() and a 35-LED WS2812B burst (~1 ms transmit), that floor doubles per-frame cost and accumulates as the timing drift reported in #2420. The runtime check skips the floor whenever no radio is actually running.

Track 1 deferred

Track 1 (per-driver ISR-completion semaphore -- block on the driver's DMA-done callback instead of polling) is a larger refactor that touches every IChannelDriver and its peripheral plumbing (RMT5, PARLIO, LCD_SPI, I2S_SPI, LCD_CAM, LCD_RGB). It is deferred to a follow-up PR.

#2493 carve-out removal

The #if FL_IS_ESP_32P4 branch added in #2503 to mitigate the PARLIO 16.7 ms show() block (#2493) becomes unnecessary -- NetworkDetector::isAnyNetworkActive() returns false on ESP32-P4 (no radio silicon), so P4 still takes the fast path. The platform-specific carve-out is removed.

NetworkDetector facade

The real fl::NetworkDetector implementation lives at src/platforms/esp/32/drivers/rmt/rmt_5/network_detector.h and is gated by FASTLED_RMT5. To make it callable from platform-neutral fl/channels/ code without circular includes, a small facade is added at src/fl/net/network_detector.h that:

  • delegates to the real RMT5 implementation when FASTLED_RMT5 == 1
  • provides a stub isAnyNetworkActive() { return false; } everywhere else, matching the pre-existing ESP32-P4 / non-ESP32 behavior

On platforms where the real detector is unavailable, the call folds to a constant false and the optimizer collapses the runtime branch.

Files changed (3)

  • src/fl/channels/manager.cpp.hpp -- ChannelManager::waitForCondition template
  • src/fl/channels/driver.cpp.hpp -- IChannelDriver::waitForCondition template
  • src/fl/net/network_detector.h -- new cross-platform facade header (NEW)

Test plan

Note: The two pre-existing test failures in this repo's master tip (spi_pingpong_pipeline_logic UBSAN overflow at line 126, and a related dependency-load failure for spi_peripheral) are unrelated to this PR -- both predate it and reproduce on master.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced system resource management with adaptive yielding that responds to network activity
    • Improved timing accuracy and efficiency across all network scenarios

…on (refs #2815)

Replace the compile-time `#if defined(FL_IS_ESP_32P4)` carve-out in
`ChannelManager::waitForCondition` and `IChannelDriver::waitForCondition`
with a runtime `fl::NetworkDetector::isAnyNetworkActive()` check.

Before:
  #if defined(FL_IS_ESP_32P4)
      task::run(0, task::ExecFlags::SYSTEM);
  #else
      task::run(250, task::ExecFlags::SYSTEM);
  #endif

After:
  if (fl::NetworkDetector::isAnyNetworkActive()) {
      task::run(250, task::ExecFlags::SYSTEM);  // keep WiFi/lwIP/BT alive
  } else {
      task::run(0, task::ExecFlags::SYSTEM);    // fast yield, no tick floor
  }

The deep yield (which causes a >=1 FreeRTOS tick / >=1 ms floor on most
ESP32 builds) only exists to keep WiFi / lwIP / BT controller tasks alive
during channel waits (#2254). When no radio is up that floor is pure
timing drift -- the root cause of the regression in #2420 and the reason
#2493 carved out ESP32-P4 in the first place. The runtime check
generalizes that carve-out so any sketch without an active radio gets the
fast path on any platform.

NetworkDetector currently lives at platforms/esp/32/drivers/rmt/rmt_5/
and is gated by `FASTLED_RMT5`. To make it callable from the
platform-neutral fl/channels/ code without circular includes, a small
facade header is added at fl/net/network_detector.h that:
  - delegates to the real RMT5 implementation when FASTLED_RMT5=1
  - provides a stub `isAnyNetworkActive() { return false; }` everywhere
    else, which matches the pre-existing ESP32-P4 / non-ESP32 behavior

Track 1 (per-driver ISR-completion semaphore) from the issue is deferred
to a follow-up PR. This is Track 2 only.

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

coderabbitai Bot commented Jun 5, 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: 97bfc68e-2a29-4300-9e28-8bd240558099

📥 Commits

Reviewing files that changed from the base of the PR and between cf53a84 and e4a5a38.

📒 Files selected for processing (3)
  • src/fl/channels/driver.cpp.hpp
  • src/fl/channels/manager.cpp.hpp
  • src/fl/net/network_detector.h

📝 Walkthrough

Walkthrough

This PR replaces compile-time platform-specific channel-manager yielding logic with runtime network-aware adaptive yielding. A new NetworkDetector facade provides cross-platform network activity detection, enabling both the channel driver and manager to dynamically select between deep yields (when networks are active) and fast yields (when inactive).

Changes

Network-Aware Adaptive Yielding

Layer / File(s) Summary
Network detector facade
src/fl/net/network_detector.h
New fl::NetworkDetector static facade provides network activity accessors (WiFi, Ethernet, Bluetooth, any-active, any-connected). Conditionally includes real ESP32-RMT5 implementation when available; otherwise provides a stub where all accessors return false, with deleted construction/copy to prevent instantiation.
Driver wait-loop adaptive yielding
src/fl/channels/driver.cpp.hpp
IChannelDriver::waitForCondition adds network-aware yielding: branches on NetworkDetector::isAnyNetworkActive() to select deep yield (task::run(250, ...)) when radios are active or fast yield (task::run(0, ...)) when idle, replacing fixed platform logic.
Manager wait-loop adaptive yielding
src/fl/channels/manager.cpp.hpp
ChannelManager::waitForCondition similarly adopts runtime network-detection-driven yielding, replacing prior compile-time ESP32-P4 macro conditional with runtime NetworkDetector branching for the same deep/fast yield selection.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • FastLED/FastLED#2503: Both PRs modify IChannelDriver::waitForCondition and ChannelManager::waitForCondition yield logic in the same files, switching between task::run(250, ...) and task::run(0, ...) based on platform/network conditions.

Poem

🐰 A network-aware yield we now behold,
Runtime decisions instead of platform mold,
Deep sleeps when radios wake and play,
Fast pulses when networks drift away! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% 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 title accurately reflects the main change: replacing compile-time ESP32-specific yield logic with runtime NetworkDetector-based adaptive yielding in channel wait loops.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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 perf/2815-network-gated-yield

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 merged commit b1d4fe9 into master Jun 5, 2026
6 of 8 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 5, 2026
pull Bot pushed a commit to manmuqingshan/FastLED that referenced this pull request Jun 5, 2026
…e 1 of FastLED#2815, Closes FastLED#2818)

Builds on FastLED#2817 (runtime NetworkDetector-gated yield) by inserting a
bounded microsecond spin tier *before* the cooperator yield. The
combined wait now has three tiers:

  Tier 1 - instant non-blocking condition check (free fast path)
  Tier 2 - bounded microsecond spin (FASTLED_WAIT_SPIN_BUDGET_US, default 250 us) [NEW]
  Tier 3 - NetworkDetector-gated cooperator yield (already merged via FastLED#2817)

Tier 2 catches short DMA tails (APA102 small strips, WS2812B <=8 LEDs)
without paying even the no-radio fast yield's per-iteration overhead.
For the FastLED#2420 reporter's 35-LED WS2812B sketch (~1.05 ms transmit), the
new tier eliminates the residual drift around the transmit boundary.

Public API on CFastLED (per the Public Settings Pattern):
- setWaitSpinBudgetUs(N) / getWaitSpinBudgetUs() runtime setter.
- FASTLED_WAIT_SPIN_BUDGET_US compile-time default (250 us).
- Set to 0 to disable the spin tier entirely.

Implementation lives in fl/channels/detail/wait_spin_budget.{h,cpp.hpp}
with atomic storage (fl::atomic<u32>) so concurrent reads in the wait
loop do not race against a writer in setWaitSpinBudgetUs.

Also fixes a small lint regression from FastLED#2817's fl/net/network_detector.h
(IWYU pragma blocks around platform headers, FL_NOEXCEPT on deleted
special members).

Closes FastLED#2818. Refs FastLED#2815.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 5, 2026
 follow-up)

The SubdirNamespaceChecker requires headers in src/fl/<subdir>/ to
declare namespace fl::<subdir>. The cross-platform stub in
src/fl/net/network_detector.h (added by #2817) was declaring the
NetworkDetector class in `namespace fl`, triggering a lint violation.

Move the stub into `namespace fl::net` and add a `using` alias in
`namespace fl` so the existing consumers (`fl::NetworkDetector` in
fl/channels/manager.cpp.hpp, fl/channels/driver.cpp.hpp) keep working
without any churn. The real RMT5 implementation already lives in
`namespace fl` at its own header and is unaffected.

Pure lint fix, no behavior change.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 5, 2026
…2817

fix(net): move NetworkDetector stub into fl::net namespace (#2817 lint follow-up)
pull Bot pushed a commit to manmuqingshan/FastLED that referenced this pull request Jul 29, 2026
…ixes FastLED#2994)

show() and showColor() were the last call sites still taking an
UNCONDITIONAL deep yield in their refresh-rate wait. Every sibling wait
loop was already fixed -- 9d71de0 skipped the vTaskDelay(1) floor,
FastLED#2817 added runtime NetworkDetector gating, FastLED#2818 added the bounded spin
tier -- but the throttle in FastLED.cpp.hpp never got the treatment.

Mechanism: fl::task::run(<non-zero>, SYSTEM) routes to pumpCoroutines(),
which on ESP32 floors at one FreeRTOS tick (the `if (ticks == 0) ticks =
1` branch added for the FastLED#2254 websocket-starvation fix). That is >=1 ms
at CONFIG_FREERTOS_HZ=1000 and >=10 ms at the 100 Hz default. With
setMaxRefreshRate(800) the throttle only needs 1250 us, so every frame
overshot to a tick boundary. ~500 shows per sequence x sub-ms jitter is
the 63-300 ms drift reported in FastLED#2994; 3.10.3's plain busy-wait was
microsecond-accurate, which is why it reported a rock-steady 2495 ms.

Worth stating explicitly because it drove the design: gating alone does
NOT fix this. With a radio up, a gated deep yield still hits the tick
floor and still drifts -- it would have looked fixed for FastLED#2994's reporter
(whose sketch has no WiFi) while leaving every networked user broken. The
spin tier is what actually restores precision; the gate is the
complement.

So both tiers, mirroring waitForCondition:
  - No radio up: task::run(0) only. Equal-priority tasks still get CPU,
    no tick floor, wait stays microsecond-accurate.
  - Radio up: keep the deep yield while more than the spin budget
    remains, then spin the last stretch rather than overshooting.

Reuses the existing FastLED.setWaitSpinBudgetUs() knob (default 250 us)
rather than inventing a second one, and both loops are factored into one
helper so they cannot drift apart again.

AVR and other small-memory targets are unchanged: without
SKETCH_HAS_LARGE_MEMORY the helper is the same plain busy-wait as before.

Verified: 357/357 host tests, C++ lint clean. NOT yet validated on
hardware -- the two claims that need a board are that FastLED#2994's sequence
returns to a steady 2495 ms with no radio, and that FastLED#2254's websocket
throughput is unaffected with a radio up.

Refs FastLED#2994, FastLED#2193, FastLED#2254, FastLED#2493, FastLED#2815, FastLED#2817, FastLED#2818

Co-Authored-By: Claude <[email protected]>
pull Bot pushed a commit to manmuqingshan/FastLED that referenced this pull request Jul 29, 2026
…eedsDeepYield (FastLED#3765)

Two items from the FastLED#3765 meta-tracker.

1. task::run()'s SYSTEM branch called pumpCoroutines(1000) with a literal
   1000, ignoring its own `microseconds` parameter. Since run() is a
   do/while loop against a deadline, a caller asking for
   run(250, SYSTEM) could pump past its own budget. Now clamped to
   fl::min(1000u, remaining()), mirroring exactly what the COROUTINES
   branch immediately below already does.

   Scope, stated plainly because it is narrower than I first claimed on
   FastLED#3765: this is a correctness/consistency fix, NOT an observable bug fix
   on either platform this suite exercises.
     - ESP32: pumpCoroutines() floors any non-zero request at one FreeRTOS
       tick (the `if (ticks == 0) ticks = 1` branch from FastLED#2254), so 250 and
       1000 are identical. The FastLED#2254 deep-yield guarantee is untouched.
     - Host: CoroutineRunner::run() early-returns when no coroutine is
       registered (`if (mCount == 0) return;`), so both are no-ops.
   It only bites with coroutines registered, where the hardcoded 1000
   pumps them past the caller's deadline.

2. ICoroutineRuntime::needsDeepYield() was dead code -- declared in
   coroutine_runtime.h, overridden in coroutine_esp32.impl.hpp, called
   from nowhere. It duplicated fl::NetworkDetector with weaker semantics
   (WIFI_MODE_NULL only; no Bluetooth, no Ethernet) and was superseded by
   the NetworkDetector gating in FastLED#2817/FastLED#3764. Removed, along with its
   only caller-helper isWiFiActive() and the esp_wifi include and weak
   symbol declaration that existed solely to serve it.

   soc/soc_caps.h is deliberately left: it sits in an IWYU keep block and
   other ESP headers may rely on it transitively, and this file cannot be
   compiled locally.

On testing: the first version of this change shipped a wall-clock test
asserting run(250) does not sleep ~1000us. It passed against the
un-fixed code, because of the mCount==0 early return above -- false
assurance, so it was removed rather than kept. What remains pins the
contract that IS observable here: the zero-budget path must take the
cheap fl::yield() and must not sleep, and a small budget must terminate.

Verified: 357/357 host tests, bash lint --cpp exit 0. The ESP32 deletion
is compile-verified by CI's ESP32 jobs, not locally.

Refs FastLED#3765, FastLED#3762, FastLED#2817, FastLED#2254

Co-Authored-By: Claude <[email protected]>
@zackees
zackees deleted the perf/2815-network-gated-yield branch August 21, 2026 19:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant