Skip to content

1D->2D expansions can lead to crashes #4779

Open

Description

@DedeHai

What happened?

While debugging the PS code I found it crashes quite often when using 1D FX in a 2D segment.
My investigation showed, that this also happens with non PS effects. The larger the segment, the easier it is to trigger the crash.

To Reproduce Bug

I was able to reproduce this on S3 and ESP32:
set up a 2D matrix, 32x32 or larger, on 64x32 it happens more often. I used two outputs in my tests both WS281x with equal amounts of LEDs (512 for example).
I set a bootup preset with Aurora effect, then switch to Android effect (just to see if it crashes as I tested with no LEDs connected). Crash dump below was with Aurora.
Change the 1D->2D expansion type randomly, at 32x32 it usually takes 10-20 changes, on larger ones it happenes sometimes after just one or two changes.

Expected Behavior

Install Method

Self-Compiled

What version of WLED?

Latest main.

Which microcontroller/board are you seeing the problem on?

ESP32

Relevant log/trace output

Unfortunately, trace outputs are very erratic and inconclusive. What often pops up is something like this:

JSON buffer released. (12)
-- Stopping transition: S=0x3ffd87bc T(0x3fff15f0) O[0x3fff098c]
-- Destroying segment: 0x3fff098c [0,32:0,32] 352->(0x3fff16fc) T[0]
JSON buffer locked. (11)
Waited for strip to finish servicing.
Waited for strip to finish servicing.
-- Started transition: S=0x3ffd87bc T(0x3fff15f0) O[0x3fff098c] OP[0x3fff1a68]
JSON buffer released. (11)
JSON buffer locked. (11)
Waited for strip to finish servicing.
JSON buffer released. (11)
Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.

Core  1 register dump:
PC      : 0x40082d99  PS      : 0x00050032  A0      : 0x40087b94  A1      : 0x3ffbf870  
=> 0x40082d99: i2s_ll_get_intr_status at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/hal/esp32/include/hal/i2s_ll.h:398
      (inlined by) i2s_intr_handler_default at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/driver/i2s.c:434
=> 0x40087b94: _xt_medint2 at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/port/xtensa/xtensa_vectors.S:1203
A2      : 0x3ffd9910  A3      : 0x00020202  A4      : 0x00020202  A5      : 0x4008f122  
=> 0x4008f122: _frxt_int_enter at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/port/xtensa/portasm.S:119
A6      : 0x00000001  A7      : 0x3fe925a6  A8      : 0x00000001  A9      : 0x3fe92485
A10     : 0x7ff00000  A11     : 0x00000123  A12     : 0x00000020  A13     : 0x00000001
A14     : 0x00000000  A15     : 0x80000002  SAR     : 0x00000009  EXCCAUSE: 0x0000001c
EXCVADDR: 0x00020212  LBEG    : 0x400029ac  LEND    : 0x400029cb  LCOUNT  : 0x00000000
=> 0x400029ac: ?? ??:0
=> 0x400029cb: ?? ??:0


Backtrace: 0x40082d96:0x3ffbf870 0x40087b91:0x3ffbf8a0 0x40081628:0x3ffcc350 0x400e84df:0x3ffcc410 0x400ed1fc:0x3ffcc450 0x4011d855:0x3ffcc480 0x4011dd2e:0x3ffcc530 0x4013a7e5:0x3ffcc550
=> 0x40082d96: i2s_ll_get_intr_status at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/hal/esp32/include/hal/i2s_ll.h:398
      (inlined by) i2s_intr_handler_default at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/driver/i2s.c:434
=> 0x40087b91: _xt_medint2 at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/port/xtensa/xtensa_vectors.S:1203
=> 0x40081628: Segment::setPixelColor(int, unsigned int) const at wled00/FX_fcn.cpp:732 (discriminator 2)
=> 0x400e84df: Segment::setPixelColor(int, unsigned char, unsigned char, unsigned char, unsigned char) const at wled00/FX.h:691 (discriminator 2)
      (inlined by) mode_aurora() at wled00/FX.cpp:4823 (discriminator 2)
=> 0x400ed1fc: WS2812FX::service() at wled00/FX_fcn.cpp:1235
=> 0x4011d855: WLED::loop() at wled00/wled.cpp:127 (discriminator 5)
=> 0x4011dd2e: loop() at wled00/wled_main.cpp:23

Anything else?

not every crashdump shows this but often xtensa_vectors.S is somewhere in there.
I suspect these things:

  • buffer overrun somewhere in the layering code
  • misaligned memory access: if DSP functions are used (not sure vectors is one) then memory boarder alignment applies. For example: the DSP FFT needs 16-byte aligned memory (see my PR with DSP FFT code )

let me know if this can be reproduced.

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

  1. blazoncek commented on Jul 18, 2025

    @blazoncek
    Contributor

    Segment::setPixelColor(int, unsigned int) const at wled00/FX_fcn.cpp:732 (discriminator 2) indicates something unexpected happens during 1D expansion and raw pixel drawing. Prior lines say that the issue comes from I2S (interrupt?) handling.

    You will need to provide exact steps.

  2. DedeHai commented on Jul 18, 2025

    @DedeHai
    CollaboratorAuthor

    I would love to have more detailed steps to provoke this, unfortunately it happens at random. If it is due to a race condition, thats what I would expect.

  3. DedeHai commented on Jul 18, 2025

    @DedeHai
    CollaboratorAuthor

    I may have found the issue: its related to _frametime.
    the funcion waitForIt() waits for the targeted frametime, if that is shorter than what the actual frame rendering time is, the segment is not suspended when changing dimensions and the FX can still be rendering, causing the crash.
    In the crashdump above "Waited for strip to finish servicing." shows up right before the crash. The wording is a bit misleading as this is printed if a timeout happened during wait.

    to solve this, waitForIt() must not return before isServicing() returns false if afterwards buffers are changed.
    Is there a call to waitForIt() where an early return does not cause problems if its still servicing?
    If not, could the timeout be set to like 1000ms or will that cause other problems?

  4. willmmiles commented on Jul 18, 2025

    @willmmiles
    Member

    I don't think there are any cases for waitForIt() which won't risk crashes if they time out -- hence the suggestion to replace it with a formal mutex. Broadly, though, blocking of the web servicing task for a long time can be problematic. (Though we're stepping in to the "many problems have to happen at once" case there.)

    Either way, we probably do need a longer timeout; and should it actually timeout, we probably want to abort most of the operations calling in instead of blindly continuing.

  5. willmmiles commented on Jul 18, 2025

    @willmmiles
    Member

    IIRC there are a couple of other places that also risk contention. The legacy web API handleSet() is one, it could technically be interacting with or modifying segments while a preset is being applied by the main task. This applies to both web and MQTT, I think.

    Sorry, I'd stumbled on this issue a while back, never got around to doing a full analysis to make sure there weren't any other points of failure. In practice, most of the potential concurrency problems are actually solved by the JSON lock, which implicitly functions as a mutex around most system state. My original thought was to consider extending it to the render loop and then hunt down any stragglers. That said, the current approach of doing an early exit of the render loop when a write is necessary is a good idea and should be preserved.

    One thing to keep in mind is that it's also not stricly speaking safe to even read segment properties without holding the lock; it's possible some other task was in the middle of updating the segments.

  6. blazoncek commented on Jul 19, 2025

    @blazoncek
    Contributor

    The premature exit from wait loop was added intentionally to avoid issues stalling web requests. Even though I knew the implications.

    Mutex will not solve this. However, there are two possible workarounds:

    • wait "indefinitely" until frame drawing is done (@DedeHai you can increase wait by adding 2* or 3* to get frameTime())
    • schedule segment parameter update out of drawing loop (service())

    In the past we already had "scheduled" updates for segment length (it only handled length). However such approach will need a lot of RAM if we want to hamdle all 32 segments in full. 8266 is at risk here.

    As for first option, the problem can also be solved to drop requested FPS if ESP can't keep up (dynamically updating FPS).

  7. added a commit that references this issue on Jul 19, 2025
  8. DedeHai commented on Jul 19, 2025

    @DedeHai
    CollaboratorAuthor

    I added a temporary fix in #4783 but it does only mask the underlaying issue.

    @willmmiles since "blocking of the web servicing task for a long time can be problematic": does the current code prevent me from setting target FPS to 2, making the timeout 500ms?

  9. willmmiles commented on Jul 19, 2025

    @willmmiles
    Member

    Mutex will not solve this. However, there are two possible workarounds:

    • wait "indefinitely" until frame drawing is done (@DedeHai you can increase wait by adding 2* or 3* to get frameTime())

    That's what a mutex would permit. The only difference is that it blocks "properly" in the RTOS instead of a using a delay() loop -- and would also extend this protection to any other tasks, should some future integration end up doing work on yet another task (such as an MQTT or a bluetooth integration).

    • schedule segment parameter update out of drawing loop (service())

    In the past we already had "scheduled" updates for segment length (it only handled length). However such approach will need a lot of RAM if we want to hamdle all 32 segments in full. 8266 is at risk here.

    The RAM cost for just handling segment updates wouldn't be terrible; it'd be a buffer of SegmentCopy objects, just like BusConfigs before it, and so on; but I think it would be silly to add yet another special-case deferral of update handling. (Also technically we'd need to make sure that update queue is itself mutexed/task safe.) We've already had to do this for bus configuration, for wifi settings, the list just keeps going on. The specific issue here with Segments is also potentially a problem for pretty much every setting, every usermod option, you name it -- the assumption that the web server task can just read or write variables being used by the main task is extremely dangerous. (You can get away with a lot playing fast and loose with this kind of thing in a cooperative tasking model like the ESP8266 -- there, you only task switch at yield()s -- but it's not so simple with a preemptive OS like ESP32 uses.)

    Instead I think we should take to one of two approaches:

    • Commit to processing all config updates on the main/render task, so no locking is required. Functionally this could be implemented by having the web server (or other configuration calling tasks) queue the deserialization functions to be handled by the main thread using a thread-safe queue. Pros: implementation is straightforward, works for all configuration items everywhere; con: worst possible performance - main loop is blocked while updates are analyzed, even if they make no changes.
    • Commit to using granular locking during configuration updates. Pro: config functions can be called freely from any task, locking scopes are narrow, minimal impact on render loop if no changes are made; Con: every feature, component, and usermod needs to think about thread safety independently for their configuration.

    I usually lean toward the latter, but I could be talked in to the former if there's a consensus that "I don't want to have to think about task safety" is more valuable than "best possible performance". (If we do want to go that route, possibly in the future, the render loop could be broken out to a separate task from the rest of the main thread, and the bus/segment handling special cased with locking.)

  10. willmmiles commented on Jul 19, 2025

    @willmmiles
    Member

    @willmmiles since "blocking of the web servicing task for a long time can be problematic": does the current code prevent me from setting target FPS to 2, making the timeout 500ms?

    It's not so much about the timeout value as how long the render actually takes. The FPS /target/ shouldn't matter, since the timeout only applies to how long it spends inside the render, not how long it waits between renders. The actual FPS might, though: if it's running so slow that it really takes 500ms to render a frame, you're gonna have a bad time, web server or no.

    We might be able to do better for the web server by pipelining the output phase, eg. making sure the Bus::show() calls are outside of the segment mutex once the blending has been completed.

  11. added a commit that references this issue on Jul 23, 2025
  12. github-actions commented on Nov 17, 2025

    @github-actions

    Hey! This issue has been open for quite some time without any new comments now. It will be closed automatically in a week if no further activity occurs.
    Thank you for using WLED! ✨

  13. added
    stale
    on Nov 17, 2025
  14. DedeHai commented on Nov 17, 2025

    @DedeHai
    CollaboratorAuthor

    do we want to keep this open as a reminder that timing still needs proper fixing? The current workaround seems to hold up quite well, I never got any crashes anymore.

  15. blazoncek commented on Nov 17, 2025

    @blazoncek
    Contributor
  16. removed
    stale
    on Nov 18, 2025
  17. softhack007 commented on Nov 18, 2025

    @softhack007
    Member

    Hi all,

    I did not read through all your discussions, so excuse me in case I'm repeating stuff that was already said. Still I can add my 2€ of experience from WLED-MM.

    In fact, I think that only a mutex / semaphore will really solve the problem. I'm talking about FreeRTOS semaphores, not any hand-crafted spinlocks that are basically implemented with a volatile bool, because these user-space spinlocks are not sufficient to really exclude concurrent access on a multiprocessor CPU with caches.

    The general issue is that UI callsbacks are running in web server context (another task) with high priority, while the "looptask" is rendering effects, sending out LEDs, saving presets, reading buttons, serving DMX etc.

    In MM we found a workaround (not perfect, but worked) by blocking all "serialize" and "deSerialize" functions until strip.service() is done. I think upstream WLED did it similarly, with an additional mechanism to queue "segment" updates so they will be added to the segments list later by the main looptask.

    I agree with @DedeHai @willmmiles that a Mutex to protect access to "Segments" would be the proper solution. With this, we could be sure that whenever one task reads or modifies segments, any concurrent tasks will be locked out.

    PS: 8266 does not have OS based Mutex support, so not sure what to do about this aging device ... maybe let 8266 rest in peace 😉 and solve it for esp32?

  18. added
    needs investigation
    keep
    on Nov 18, 2025
  19. willmmiles commented on Nov 19, 2025

    @willmmiles
    Member

    @softhack007 Alas there is more to the thread. To sum up: if only it were just "Segments"! The underlying issue of concurrent access to shared state is endemic throughout the codebase. Bus drivers are another big one, but anywhere there's a String being stored is potentially vulnerable. (MQTT? IR? The list goes on...) It's harder to crash the system with non-heap types, but there are still ways, too...

    We can try to mutex every individual subsystem, but that's a big task. Short term, the best "fixes 'em all" answer we have is to move the web server endpoints that interact with system state to the loop task. Fortunately this is straightforward: #4808 showcases the basic technique, though I haven't yet had time to ensure it's applied to every call that needs it, and there's some interaction with the shared JSON buffer lock that will need to be cleaned up. (Of course this works just fine for ESP8266, too.)

    Longer term, I do think it's worth considering moving the LED rendering loop to an isolated task anyways, if only to better take advantage of multicore systems. At that point we will need to update it with a formal API and concurrency management (possibly with mutexes, but message passing might be a better fit). Either way, I don't anticipate any particular trouble fitting it in for the EPS8266; the cooperative multitasking model means we can stub out any mutexes on that platform.

  20. removed their assignment
    on Nov 21, 2025
  21. softhack007 commented on Mar 9, 2026

    @softhack007
    Member

    @coderabbitai please review the current source code in main for the issues discussed above.

    We haven't addressed the overall problem of concurrent access to shared state ("wishful sigle-tasking"), but we have some safeguards in place.
    I'm curious if the specific use case of changing 1D2D mapping mode can still lead to memory corruption or crashes.

  22. added this to the 17.0 milestone on Mar 9, 2026
  23. coderabbitai commented on Mar 9, 2026

    @coderabbitai
    Contributor

    Coding Plan

    Summary

    • The crash is a race condition between the AsyncWebServer task and the main loop's strip.service(), not just a setGeometry() logic bug
    • Phase 1 provides immediate mitigation by hardening waitForIt() to fail safely on timeout rather than proceeding unsafely
    • Phase 2 adds defensive stopTransition() and markForReset() calls in setGeometry() when map1D2D changes
    • Phase 3 outlines the proper fix: routing state changes through the main loop task via a FreeRTOS queue
    • Phase 4 acknowledges that other subsystems (Strings, Bus, MQTT, IR, usermods) share this vulnerability and documents long-term architectural options
    Design Choices
    Design Choice 1: Should the waitForIt() timeout failure abort the mutation or proceed anyway?

    Options Considered:

    1. Abort the mutation entirely and return an error to the web client
    2. Force-stop the transition/service and proceed (may cause visual glitches but prevents crashes)
    3. Defer the mutation to a main-loop callback queue (requires architectural change)

    Chosen Option: 1

    Rationale: Option 1 for short-term: Aborting on timeout is the safest immediate fix—it prevents the race condition crash at the cost of occasionally failing a web request during slow effects. Option 3 is the proper medium-term solution.

    Design Choice 2: Should we also mark the segment for reset when `map1D2D` changes?

    Options Considered:

    1. Only stop the transition, let effects continue with existing data allocations
    2. Also call markForReset() to force effects to reinitialize with correct virtual dimensions

    Chosen Option: 2

    Rationale: Calling markForReset() ensures effects that sized their data buffers based on virtualLength() or nrOfVStrips() will properly reallocate, preventing subtle buffer mismatches.

    💡 User Tips

    Regenerate the plan with different choices with @coderabbitai <feedback>.

    Implementation Steps

    Phase 1: Short-Term Mitigation — Harden Cross-Task Synchronization

    This phase addresses the immediate crash risk by improving the waitForIt() mechanism to fail safely rather than proceed unsafely on timeout.

    Task 1: Make _isServicing Flag Volatile

    Ensure cross-task visibility of the servicing flag on multi-core ESP32.

    • In wled00/FX.h, change bool _isServicing : 1 to a standalone volatile bool _isServicing (remove from bitfield)
    • This ensures the main loop's writes to _isServicing are visible to the web server task's waitForIt() reads without compiler reordering
    • Keep the existing volatile bool _suspend as-is
    Task 2: Increase waitForIt() Timeout and Add Abort-on-Timeout

    Prevent unsafe mutations when the render loop doesn't complete in time.

    • In wled00/FX_fcn.cpp, modify waitForIt() (around line 1696)
    • Increase timeout from 2*getFrameTime() + 100 to 3*getFrameTime() + 150 to accommodate slower effects
    • Change return type from void to bool, returning false on timeout
    • Update all callers in json.cpp, set.cpp, and FX_fcn.cpp to check the return value
    • When waitForIt() returns false, the caller should skip the mutation and optionally set an error flag for the HTTP response
    Task 3: Guard Segment Mutations in json.cpp on Timeout

    Abort segment deserialization if the strip cannot be safely suspended.

    • In wled00/json.cpp around line 465, check the return value of strip.waitForIt()
    • If waitForIt() returns false, skip the deserializeSegment() calls and set a flag to return an error response
    • Call strip.resume() in both success and failure paths to ensure proper cleanup
    • Add a debug log message when mutation is aborted due to timeout
    🤖 Prompt for AI agents
    This phase hardens the cross-task synchronization mechanism in WLED to prevent
    unsafe segment mutations when the render loop doesn't yield in time.
    
    **Task 1: Make `_isServicing` volatile (`wled00/FX.h`)**
    - Locate `bool _isServicing : 1` in the bitfield declaration inside `FX.h`
    - Remove it from the bitfield and redeclare it as a standalone `volatile bool
    _isServicing`
    - Leave `volatile bool _suspend` unchanged
    
    **Task 2: Harden `waitForIt()` (`wled00/FX_fcn.cpp`, ~line 1696)**
    - Change the return type of `waitForIt()` from `void` to `bool`
    - Increase the timeout from `2*getFrameTime() + 100` to `3*getFrameTime() + 150`
    - Return `true` on successful wait (render loop yielded in time), `false` on
    timeout
    - Update the declaration in the corresponding header file
    - Update all callers in `json.cpp`, `set.cpp`, and `FX_fcn.cpp` to check the
    return value; when `false` is returned, skip the mutation and optionally set an
    error flag for the HTTP response
    
    **Task 3: Guard segment mutations in `json.cpp` (~line 465)**
    - After calling `strip.waitForIt()`, check the returned `bool`
    - If `false`, skip the `deserializeSegment()` calls, set a flag to return an
    error response to the HTTP client, and call `strip.resume()` before returning
    - On success, proceed with deserialization as normal and call `strip.resume()`
    afterward
    - Add a debug log message (e.g., via `DEBUG_PRINT`) when a mutation is aborted
    due to timeout
    

    Phase 2: Defensive Fix — Transition Handling on Expansion Type Change

    This phase adds a defensive safeguard in setGeometry() to properly terminate transitions when map1D2D changes, preventing stale old-segment copies with incompatible virtual dimensions.

    Task 1: Stop Active Transition When map1D2D Changes

    Modify setGeometry() to stop any active transition when the expansion type changes, even when segment bounds remain unchanged.

    • In wled00/FX_fcn.cpp, locate the setGeometry() function (around line 421)
    • After the existing clear() call for map1D2D changes (line ~429), add a call to stopTransition() if _t is active
    • This must occur before the boundsUnchanged early-return to ensure transitions are terminated
    • The condition should check: segment is active (stop != 0), expansion type is changing (m12 != map1D2D), and transition is active (_t != nullptr)
    Task 2: Mark Segment for Effect Reset on map1D2D Change

    Ensure effects reinitialize their data buffers when expansion type changes, since virtualLength() and nrOfVStrips() values will differ.

    • In the same code block handling map1D2D changes, add a call to markForReset()
    • This triggers resetIfRequired() on the next render frame, which deallocates and reinitializes effect data
    • Effects like Fire 2012, Bouncing Balls, and Particle System allocate buffers based on nrOfVStrips() and need reinitialization when this value changes
    Task 3: Consolidate Expansion Type Change Handling

    Group all map1D2D-change side effects into a clear conditional block for maintainability.

    • Refactor the existing if (stop && (spc > 0 || m12 != map1D2D)) clear(); line
    • Create a dedicated block for map1D2D changes that calls: clear(), stopTransition() (if active), and markForReset()
    • Keep spacing-only changes handled separately if needed (spacing changes already trigger the bounds-changed path due to being included in boundsUnchanged calculation)
    • Add a brief comment explaining why transitions must be stopped when expansion type changes (virtual dimensions become incompatible)
    🤖 Prompt for AI agents
    This phase fixes a crash bug in `setGeometry()` (`wled00/FX_fcn.cpp`) where
    changing `map1D2D` bypasses transition cleanup due to an early-return path,
    causing mismatched virtual dimensions between old and new segment copies.
    
    - Locate the `setGeometry()` function around line 421 in `wled00/FX_fcn.cpp`
    - Refactor the existing line `if (stop && (spc > 0 || m12 != map1D2D)) clear();`
    into a dedicated conditional block specifically for `map1D2D` changes:
    - The block should trigger when the segment is active (`stop != 0`) and the
    expansion type is changing (`m12 != map1D2D`)
    - Inside this block, call `clear()`, then call `stopTransition()` if the
    transition is active (`_t != nullptr`), then call `markForReset()`
    - Add a comment explaining that transitions must be stopped when expansion type
    changes because `virtualLength()` depends on `map1D2D`, making old and new
    segment copies have incompatible virtual dimensions
    - Ensure all of these calls occur **before** the `boundsUnchanged` early-return
    path so transitions are always terminated on expansion type change
    - Keep spacing-only changes handled separately as needed (spacing changes
    already flow through the bounds-changed path)
    

    Phase 3: Medium-Term Fix — Main Loop Routing for State Changes

    This phase outlines the architectural improvement to route web server state changes through the main loop task, eliminating the race condition entirely. This follows the PR #4808 pattern.

    Task 1: Create Deferred State Change Queue

    Add a thread-safe mechanism for web handlers to post state changes to the main loop.

    • In wled00/wled.h, add a FreeRTOS queue handle QueueHandle_t stateChangeQueue for posting state change requests
    • Define a StateChangeRequest struct containing: change type enum, segment ID, and a union of change-specific data (or pointer to heap-allocated JSON fragment)
    • Initialize the queue in WLED::setup() with xQueueCreate() (capacity ~8 items, sized for typical burst of segment changes)
    • For ESP8266 compatibility, use a simple volatile flag + static buffer fallback (single pending change only)
    Task 2: Add Main Loop Queue Consumer

    Process deferred state changes from the main loop where segment access is safe.

    • In wled00/wled.cpp WLED::loop(), add a handler before strip.service() that calls xQueueReceive() with zero timeout
    • For each dequeued StateChangeRequest, call the appropriate handler (deserializeSegment(), setGeometry(), etc.)
    • Since this runs in the main loop task, no suspend()/waitForIt() is needed
    • Limit processing to a few requests per loop iteration to avoid starving the render loop
    Task 3: Route JSON Segment Changes Through Queue

    Modify web handlers to post changes to the queue rather than calling setters directly.

    • In wled00/json.cpp deserializeState(), instead of calling deserializeSegment() directly, serialize the segment JSON fragment and post to stateChangeQueue
    • The web handler can either wait for acknowledgment (blocking with timeout) or return immediately with a "processing" status
    • For backwards compatibility, keep the existing direct-call path available via a compile flag or fallback when queue is full
    • Update set.cpp HTTP API handlers similarly
    🤖 Prompt for AI agents
    This phase introduces a FreeRTOS queue-based deferred state change mechanism to
    eliminate the cross-task race condition by routing all web-initiated segment
    mutations through the main loop task.
    
    **Task 1: Create the deferred state change queue (`wled00/wled.h` and
    `wled00/wled.cpp`)**
    - Add a `QueueHandle_t stateChangeQueue` member to the `WLED` class in
    `wled00/wled.h`
    - Define a `StateChangeRequest` struct with: a change type enum, a segment ID
    field, and a union or pointer for change-specific data (e.g., pointer to a
    heap-allocated JSON fragment)
    - In `WLED::setup()`, initialize the queue with `xQueueCreate()` with a capacity
    of ~8 items
    - For ESP8266 compatibility, provide a fallback using a `volatile` flag and
    static buffer (single pending change only), guarded by a preprocessor check
    
    **Task 2: Add queue consumer in the main loop (`wled00/wled.cpp`,
    `WLED::loop()`)**
    - Before the `strip.service()` call, add a loop that calls `xQueueReceive()`
    with zero timeout to drain pending `StateChangeRequest` items
    - For each dequeued request, dispatch to the appropriate handler
    (`deserializeSegment()`, `setGeometry()`, etc.) — no `suspend()`/`waitForIt()`
    needed since this is the main loop task
    - Cap the number of requests processed per iteration (e.g., max 4) to avoid
    starving the render loop
    
    **Task 3: Route JSON segment changes through the queue (`wled00/json.cpp`,
    `wled00/set.cpp`)**
    - In `deserializeState()` in `json.cpp`, instead of calling
    `deserializeSegment()` directly, serialize the relevant segment JSON fragment
    and post it to `stateChangeQueue` via `xQueueSend()`
    - The web handler may return immediately after posting or block briefly for
    acknowledgment
    - Keep the existing direct-call path as a fallback (e.g., via a compile flag or
    when the queue is full)
    - Apply equivalent changes to HTTP API handlers in `set.cpp`
    

    Phase 4: Long-Term Architecture Considerations

    This phase documents architectural directions for comprehensive thread safety across all WLED subsystems. Implementation is out of scope for this ticket but should inform future work.

    Task 1: Document Affected Subsystems

    Identify all code paths with similar race conditions for future hardening.

    • The same suspend()/waitForIt() race affects: Strings (segment name changes), Bus drivers (bus reinitialization), MQTT (state updates), IR (command processing), and usermods (custom state)
    • Add a CONCURRENCY.md document in the repo outlining these affected areas and the chosen synchronization strategy
    • Reference this document in code comments at each suspend()/waitForIt() call site
    Task 2: Evaluate Per-Subsystem Semaphores vs. Single Task Queue

    Document tradeoffs for the two main architectural approaches.

    • Option A: Single task queue — All state changes routed through main loop; simple but adds latency and requires careful queue sizing
    • Option B: Per-subsystem FreeRTOS semaphores — Fine-grained locking (e.g., _segmentsMutex) with xSemaphoreTake()/xSemaphoreGive() around critical sections; lower latency but complex and risks deadlocks
    • ESP8266 constraint: FreeRTOS primitives are limited; task queue with fallback to volatile flags is preferred
    • Document chosen direction in CONCURRENCY.md with rationale
    🤖 Prompt for AI agents
    This phase is documentation-only and does not involve code changes to production
    source files.
    
    - Create a new `CONCURRENCY.md` file in the repository root
    - Document all subsystems affected by the `suspend()`/`waitForIt()` race
    condition: Strings (segment name changes), Bus drivers (bus reinitialization),
    MQTT (state updates), IR (command processing), and usermods (custom state)
    - Document the two main architectural options for synchronization:
    - **Option A: Single task queue** — all state changes routed through main loop;
    simple but adds latency and requires careful queue sizing
    - **Option B: Per-subsystem FreeRTOS semaphores** — fine-grained locking with
    `xSemaphoreTake()`/`xSemaphoreGive()`; lower latency but complex and risks
    deadlocks
    - Note the ESP8266 constraint: FreeRTOS primitives are limited, so the task
    queue with volatile flag fallback is preferred
    - Add a reference comment pointing to `CONCURRENCY.md` at each
    `suspend()`/`waitForIt()` call site in the codebase
    
    Research

    WLED runs a dual-task architecture on ESP32: the main Arduino loop() task executes strip.service() (the render loop), while AsyncWebServer callbacks run in a separate FreeRTOS task. Segment modifications from the web server are protected only by a cooperative suspend() → waitForIt() → modify → resume() pattern, where waitForIt() busy-waits on the non-volatile _isServicing flag with a timeout of 2*getFrameTime() + 100ms. On timeout, mutations proceed anyway—creating a race window. The setGeometry() function also has a gap: map1D2D changes bypass transition cleanup due to an early-return path, leaving stale old-segment copies with incompatible virtual dimensions.


    🚀 Next Steps

    🤖 All AI agent prompts combined
    Task: 1
    
    This phase hardens the cross-task synchronization mechanism in WLED to prevent
    unsafe segment mutations when the render loop doesn't yield in time.
    
    **Task 1: Make `_isServicing` volatile (`wled00/FX.h`)**
    - Locate `bool _isServicing : 1` in the bitfield declaration inside `FX.h`
    - Remove it from the bitfield and redeclare it as a standalone `volatile bool
    _isServicing`
    - Leave `volatile bool _suspend` unchanged
    
    **Task 2: Harden `waitForIt()` (`wled00/FX_fcn.cpp`, ~line 1696)**
    - Change the return type of `waitForIt()` from `void` to `bool`
    - Increase the timeout from `2*getFrameTime() + 100` to `3*getFrameTime() + 150`
    - Return `true` on successful wait (render loop yielded in time), `false` on
    timeout
    - Update the declaration in the corresponding header file
    - Update all callers in `json.cpp`, `set.cpp`, and `FX_fcn.cpp` to check the
    return value; when `false` is returned, skip the mutation and optionally set an
    error flag for the HTTP response
    
    **Task 3: Guard segment mutations in `json.cpp` (~line 465)**
    - After calling `strip.waitForIt()`, check the returned `bool`
    - If `false`, skip the `deserializeSegment()` calls, set a flag to return an
    error response to the HTTP client, and call `strip.resume()` before returning
    - On success, proceed with deserialization as normal and call `strip.resume()`
    afterward
    - Add a debug log message (e.g., via `DEBUG_PRINT`) when a mutation is aborted
    due to timeout
    ===============================================================================
    
    Task: 2
    
    This phase fixes a crash bug in `setGeometry()` (`wled00/FX_fcn.cpp`) where
    changing `map1D2D` bypasses transition cleanup due to an early-return path,
    causing mismatched virtual dimensions between old and new segment copies.
    
    - Locate the `setGeometry()` function around line 421 in `wled00/FX_fcn.cpp`
    - Refactor the existing line `if (stop && (spc > 0 || m12 != map1D2D)) clear();`
    into a dedicated conditional block specifically for `map1D2D` changes:
    - The block should trigger when the segment is active (`stop != 0`) and the
    expansion type is changing (`m12 != map1D2D`)
    - Inside this block, call `clear()`, then call `stopTransition()` if the
    transition is active (`_t != nullptr`), then call `markForReset()`
    - Add a comment explaining that transitions must be stopped when expansion type
    changes because `virtualLength()` depends on `map1D2D`, making old and new
    segment copies have incompatible virtual dimensions
    - Ensure all of these calls occur **before** the `boundsUnchanged` early-return
    path so transitions are always terminated on expansion type change
    - Keep spacing-only changes handled separately as needed (spacing changes
    already flow through the bounds-changed path)
    ===============================================================================
    
    Task: 3
    
    This phase introduces a FreeRTOS queue-based deferred state change mechanism to
    eliminate the cross-task race condition by routing all web-initiated segment
    mutations through the main loop task.
    
    **Task 1: Create the deferred state change queue (`wled00/wled.h` and
    `wled00/wled.cpp`)**
    - Add a `QueueHandle_t stateChangeQueue` member to the `WLED` class in
    `wled00/wled.h`
    - Define a `StateChangeRequest` struct with: a change type enum, a segment ID
    field, and a union or pointer for change-specific data (e.g., pointer to a
    heap-allocated JSON fragment)
    - In `WLED::setup()`, initialize the queue with `xQueueCreate()` with a capacity
    of ~8 items
    - For ESP8266 compatibility, provide a fallback using a `volatile` flag and
    static buffer (single pending change only), guarded by a preprocessor check
    
    **Task 2: Add queue consumer in the main loop (`wled00/wled.cpp`,
    `WLED::loop()`)**
    - Before the `strip.service()` call, add a loop that calls `xQueueReceive()`
    with zero timeout to drain pending `StateChangeRequest` items
    - For each dequeued request, dispatch to the appropriate handler
    (`deserializeSegment()`, `setGeometry()`, etc.) — no `suspend()`/`waitForIt()`
    needed since this is the main loop task
    - Cap the number of requests processed per iteration (e.g., max 4) to avoid
    starving the render loop
    
    **Task 3: Route JSON segment changes through the queue (`wled00/json.cpp`,
    `wled00/set.cpp`)**
    - In `deserializeState()` in `json.cpp`, instead of calling
    `deserializeSegment()` directly, serialize the relevant segment JSON fragment
    and post it to `stateChangeQueue` via `xQueueSend()`
    - The web handler may return immediately after posting or block briefly for
    acknowledgment
    - Keep the existing direct-call path as a fallback (e.g., via a compile flag or
    when the queue is full)
    - Apply equivalent changes to HTTP API handlers in `set.cpp`
    ===============================================================================
    
    Task: 4
    
    This phase is documentation-only and does not involve code changes to production
    source files.
    
    - Create a new `CONCURRENCY.md` file in the repository root
    - Document all subsystems affected by the `suspend()`/`waitForIt()` race
    condition: Strings (segment name changes), Bus drivers (bus reinitialization),
    MQTT (state updates), IR (command processing), and usermods (custom state)
    - Document the two main architectural options for synchronization:
    - **Option A: Single task queue** — all state changes routed through main loop;
    simple but adds latency and requires careful queue sizing
    - **Option B: Per-subsystem FreeRTOS semaphores** — fine-grained locking with
    `xSemaphoreTake()`/`xSemaphoreGive()`; lower latency but complex and risks
    deadlocks
    - Note the ESP8266 constraint: FreeRTOS primitives are limited, so the task
    queue with volatile flag fallback is preferred
    - Add a reference comment pointing to `CONCURRENCY.md` at each
    `suspend()`/`waitForIt()` call site in the codebase
    
    💡 Iterate on the plan with: @coderabbitai <feedback>
    Example Feedback
    - @coderabbitai You can skip phase 3. Add a simple unit test case for phase 2.
    - @coderabbitai For design choice 1 go ahead with option 3 and replan.
    

    💬 Have feedback or questions? Drop into our discord!

  24. coderabbitai commented on Mar 9, 2026

    @coderabbitai
    Contributor

    I've updated the plan above based on your feedback. Ready to proceed when you are!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugkeepneeds investigation

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions