Skip to content

fix(core): adaptive yield in show()'s refresh throttle (#3762, fixes #2994) - #3764

Merged
zackees merged 1 commit into
masterfrom
fix/3762-show-throttle-adaptive-yield
Jul 29, 2026
Merged

zackees merged 1 commit into
masterfrom
fix/3762-show-throttle-adaptive-yield

Conversation

@zackees

@zackees zackees commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

Implements #3762. Fixes #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 — 9d71de01d0 (skip the vTaskDelay(1) floor), #2817 (runtime NetworkDetector gating), #2818 (bounded spin tier) — but the throttle in FastLED.cpp.hpp never got the treatment.

Mechanism

fl::task::run(<non-zero>, SYSTEM) → pumpCoroutines() → on ESP32 the if (ticks == 0) ticks = 1 branch (added for the #2254 websocket-starvation fix) → vTaskDelay(≥1 tick). That's ≥1 ms at CONFIG_FREERTOS_HZ=1000, ≥10 ms at the 100 Hz default.

setMaxRefreshRate(800) needs only 1250 µs, so every frame overshot to a tick boundary. ~500 shows/sequence × sub-ms jitter = the 63–300 ms drift in #2994. 3.10.3's plain busy-wait was microsecond-accurate — hence its rock-steady 2495 ms.

Why gating alone is not the fix

Worth stating because it drove the design: with a radio up, a gated deep yield still hits the tick floor and still drifts. Gating alone would have looked correct for #2994's reporter — their sketch has no WiFi — while leaving every networked user broken.

The spin tier is what actually restores precision. The gate is the complement, not the fix. So this ships both, mirroring waitForCondition:

condition behavior
no radio up task::run(0) only — equal-priority tasks still get CPU, no tick floor, microsecond-accurate
radio up, remaining > spinBudget deep yield — WiFi/lwIP/BT genuinely need the CPU
radio up, inside the budget spin the last stretch instead of overshooting the deadline

Reuses the existing FastLED.setWaitSpinBudgetUs() knob (default 250 µs) rather than inventing a second one, and factors both loops into one helper so they can't drift apart again.

isAnyNetworkActive() deliberately, not isAnyNetworkConnected() — scanning and association are exactly when the stack most needs CPU, and it matches the existing channel sites.

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

Verification

  • 357/357 host tests
  • bash lint --cpp exit 0

Not yet validated on hardware. Two claims need a board, and I'd like them checked before this lands:

  1. [Bug] Compounded timing inaccuracy on master compared to 3.10.3 (Follow-up to #2420) #2994's sequence returns to a steady 2495 ms with no radio up (ESP32-S3)
  2. ESP32-S3: I2S driver starves websockets, SPI output incorrect, Audio driver FPS impact #2254's websocket throughput is unaffected with a radio up

I have an ESP32-C6 on the bench and can run both if you want the numbers attached here first.

Not in this PR

Two related bugs found while investigating, deliberately left out to keep this reviewable — both noted in #3762:

  • executor.cpp.hpp:138 discards its microseconds argument and hardcodes pumpCoroutines(1000), so every caller asking for a shorter yield silently gets 1000 µs
  • ICoroutineRuntime::needsDeepYield() is dead code (implemented, called from nowhere) duplicating NetworkDetector with weaker semantics — no BT, no Ethernet

Open question from #3762

Whether the deep yield is needed at all anymore now that transposition is fast. This PR keeps it for radio-up cases, which is the conservative choice. If bench numbers show no throughput regression without it, the radio-up branch could be dropped entirely in a follow-up.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Performance Improvements
    • Improved refresh-rate timing for display updates.
    • Reduced the risk of overshooting refresh deadlines when network activity is present.
    • Updated color and display rendering to use more consistent timing behavior.

…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,
#2817 added runtime NetworkDetector gating, #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 #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 #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 #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 #2994's sequence
returns to a steady 2495 ms with no radio, and that #2254's websocket
throughput is unaffected with a radio up.

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

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 29, 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 Plus

Run ID: a28a608d-e822-465a-821f-8ef14745b144

📥 Commits

Reviewing files that changed from the base of the PR and between d17e853 and abc1b78.

📒 Files selected for processing (1)
  • src/FastLED.cpp.hpp

📝 Walkthrough

Walkthrough

FastLED centralizes refresh-rate throttling in a shared helper. The helper adapts waiting behavior based on network activity and remaining time, and both show() and showColor() invoke it before updating lastshow.

Changes

Refresh-rate throttling

Layer / File(s) Summary
Adaptive throttle helper
src/FastLED.cpp.hpp
Adds executor and network detector dependencies, then introduces shared throttling that selects deeper execution or lighter yielding based on remaining time and network activity.
Display path integration
src/FastLED.cpp.hpp
Updates show() and showColor() to use the shared helper before recording the latest display time.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CFastLED
  participant throttleToMaxRefreshRate
  participant NetworkDetector
  participant TaskExecutor
  CFastLED->>throttleToMaxRefreshRate: show() or showColor() with minimum interval
  throttleToMaxRefreshRate->>NetworkDetector: check whether a network is active
  throttleToMaxRefreshRate->>TaskExecutor: perform deep execution or light yield
  throttleToMaxRefreshRate-->>CFastLED: return when refresh time is reached
  CFastLED->>CFastLED: update lastshow
Loading

Possibly related issues

  • FastLED issue 3762 — The change implements network-detector-gated sub-tick refresh throttling in show() and showColor().
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: adaptive yield in refresh throttling, and it references the fixed issue.
Linked Issues check ✅ Passed The changes match #2994 by revising show()/showColor() throttling to reduce timing drift with adaptive yielding.
Out of Scope Changes check ✅ Passed The diff stays focused on refresh-throttle behavior and related includes, with no clear unrelated feature changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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 fix/3762-show-throttle-adaptive-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.

@zackees
zackees merged commit 1e70d60 into master Jul 29, 2026
13 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jul 29, 2026
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 fix/3762-show-throttle-adaptive-yield branch August 21, 2026 19:15
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.

[Bug] Compounded timing inaccuracy on master compared to 3.10.3 (Follow-up to #2420)

1 participant