You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
"Power button preset override" for on/off are retained after Factory Reset #5562
both factory reset path's call WLED_FS.format(); doReboot = true;
so either this is a bug in littleFS or it is async and gets halted by the reboot. I have no other explanation that would not wipe the file system flash. @willmmiles do you see any other reason?
@DedeHai@willmmiles just a wild guess - could it be that writing to cfg.json is needed (asyncWebserver task is in serializeConfig()), then the filesystem is formated by the main task (cfg.json write still pending/preparing JSON), and then the pending write happens directly after formatting but before the reboot executes (next turn in main loop) ?
#!/bin/bash
# Get the main loop structure of wled.cpp
cat wled00/wled.cpp | grep -n "void WLED::loop\|configNeedsWrite\|doReboot\|handleButton\|userLoop\|handleWs\|handleIR\|yield" | head -80
Length of output: 652
🏁 Script executed:
#!/bin/bash
# Get main loop context around the key lines
sed -n '41,260p' wled00/wled.cpp
Length of output: 7346
@DedeHai Here's a detailed trace of both factory reset paths:
Factory Reset Paths
Path 1 — Web UI (wled00/set.cpp Lines 628–632 + 882)
// In handleSet(), runs in async web server handler:if (request->hasArg(F("RS"))) {
WLED_FS.format(); // (1) synchronous formatserveMessage(request, 200, ...); // (2) send response
doReboot = true; // (3) set reboot flag
}
// ... at the very end of handleSet():
configNeedsWrite = subPage != SUBPAGE_LEDS && !(subPage == SUBPAGE_SEC && doReboot);
// ↑ evaluates to FALSE when factory reset was triggered // (4) guard clears write flag
Path 2 — Button (wled00/button.cpp Lines 328–330)
if (dur > WLED_LONG_FACTORY_RESET) {
WLED_FS.format(); // (1) synchronous format
doReboot = true; // (2) set reboot flag// ⚠️ NO configNeedsWrite = false guard here!
}
Main Loop Order (wled00/wled.cpp)
handleIO() ← handleButton() lives here (EARLY in loop)
...
doInitBusses block → configNeedsWrite = true ← Line 225 (can set flag!)
...
if (configNeedsWrite) serializeConfigToFS(); ← Line 232
...
if (doReboot && ...) reset(); ← Line 255
Theory Analysis
❌ DedeHai's theory (format() is async / interrupted by reboot)
Disproved.WLED_FS.format() is synchronous — it blocks until complete. doReboot = true is only set afterformat() returns, and reset() only fires from the main loop at Line 255. There is no way reboot can interrupt the format.
✅ softhack007's theory (config write after format, before reboot)
Confirmed, but the mechanism is slightly different from the description — serializeConfigToFS() is called from the main loop (Line 232), not directly from the async server. The trigger is the configNeedsWrite flag.
The critical race has two flavours:
Flavour A — Button path (deterministic bug, no race needed)
handleButton() runs inside handleIO() early in the loop, before Line 232. It calls format() + sets doReboot = true but never clears configNeedsWrite. Later in the same loop iteration:
If configNeedsWrite was already true from any prior operation → serializeConfigToFS() fires right after format ✅ reproduces
The doInitBusses block at Line 225 can also set configNeedsWrite = true in that very same iteration
Core 1 (main loop): If it reads configNeedsWrite == true (set by a prior request) and executes Line 232 concurrently while Core 0 is anywhere between format() starting and Line 882 executing, it writes cfg.json to the filesystem being formatted.
The existing comment at Line 632 (// may reboot immediately on dual-core system (race condition)) shows the devs were already aware of dual-core sensitivity in this function.
Suggested Fix
The cleanest fix covers both paths: clear configNeedsWritebefore formatting, and do it in both places:
wled00/set.cpp (Web path — move the guard earlier):
if (request->hasArg(F("RS"))) {
configNeedsWrite = false; // ← add: prevent post-format write on dual-core
doReboot = true; // ← move doReboot before format so main loop can't run serializeConfigWLED_FS.format();
serveMessage(...);
}
@coderabbitai in the webUI path, is the configNeedsWrite always set when confirming the factory reset through the UI or do conditions apply? since this is the path the issue is about it would mean that the race condition is met every time - or it is pretty much an edge case hit by bad luck.
#!/bin/bash
# Get the full handleSet function to understand the flow
echo "=== Full handleSet function in set.cpp ==="
grep -n "configNeedsWrite\|void handleSet\|void WLED_GLOBAL\|subPage\|SUBPAGE_SEC\|SUBPAGE_LEDS\|hasArg.*RS\|doReboot" wled00/set.cpp | head -80
echo ""
echo "=== Context around RS factory reset block ==="
grep -n "hasArg.*RS\|RS.*hasArg" wled00/set.cpp -A 10 -B 5
echo ""
echo "=== The configNeedsWrite assignment at end of handleSet ==="
tail -60 wled00/set.cpp
echo ""
echo "=== Where configNeedsWrite is set to true in set.cpp ==="
grep -n "configNeedsWrite\s*=\s*true" wled00/set.cpp -B3 -A3
echo ""
echo "=== Where configNeedsWrite is set anywhere globally ==="
grep -rn "configNeedsWrite\s*=" --include="*.cpp" --include="*.h" -B2 -A2
Length of output: 5872
@DedeHai — No, configNeedsWrite is not always true on the Web UI path. The race is a genuine edge case, not guaranteed. Here's the breakdown:
Why it's NOT always triggered
handleSettingsSet() does not set configNeedsWrite = true anywhere inside the function. The only assignment is at the very end (Line 882), which clears it when factory reset is detected:
configNeedsWrite = subPage != SUBPAGE_LEDS && !(subPage == SUBPAGE_SEC && doReboot);
// → evaluates to false when factory reset is triggered
So the race only fires if configNeedsWrite was already true from a prior, still-pending operation when the factory reset request arrives. That's the two-condition requirement on dual-core ESP32:
Something set configNeedsWrite = true before the factory reset request
Core 1 (main loop) reads and acts on it during the window between WLED_FS.format() completing on Core 0 and Line 882 clearing the flag
What can put configNeedsWrite into a pending-true state
From the code, these are the only setters:
Location
Trigger
wled.cpp:225
Bus re-initialization (doInitBusses block)
wled_server.cpp:460
JSON API config save
presets.cpp:242
Boot preset changed
dmx_input.cpp:25,43
DMX personality / start address changed
Most likely triggering scenario
The most plausible path to hit this in the field is:
User changes LED configuration → bus re-init runs → configNeedsWrite = true (wled.cpp:225)
User then quickly navigates to the Security page and triggers factory reset
The pending write hasn't flushed yet, and Core 1 wins the race window
Web UI path on ESP32 = race condition, bad luck required — but the probability isn't negligible if the user made any config change in the same session before factory resetting
The !doReboot guard in the main loop (if (configNeedsWrite && !doReboot) serializeConfigToFS()) would be the most defensive single-line fix covering both paths, since doReboot is set before Line 232 is reached in the button case, and on ESP32 the async handler sets it early enough for most timing scenarios.
given that it is almost impossible to have configNeedsWrite set prior to doing a factory reset through the UI I would call the rabbits analysis either incomplete or wrong. The finding of playing it save in the main loop is still a good idea. If it is in fact the root cause for the issue raised this is an extreme edge case.
Maybe the better solution is to "serialize" filesystem formatting so it only happens in the main loop. Similar to doReboot, we could add doReformat, and the main loop would take care of setting configNeedsWrite = false, then doing doCloseFile(); WLED_FS.format(); doReboot = true; in a single place. WebUI and other locations would only request doReformat = true, so the real re-formating happens later with a well-controlled sequence.
Secondary bug: both doReboot and configNeedsWrite are missing the volatile attribute, so different tasks can have different "opinions" about the value.
WLED_GLOBALbool configNeedsWrite _INIT(false); // flag to initiate saving of config
WLED_GLOBALbool doReboot _INIT(false); // flag to initiate reboot from async handlers
My experience with multitasking is "never assume <can't happen>" 😉 if there is a time window for races or a potential to get into an almost-impossible state, this will happen.
good point. Lets fix it that way.
I am not saying it can not happen, it definitely can. But it is very highly unlikely so having someone hit these exact conditions within a few millisecond window... manually. I have seen bugs that caused havoc in a sub micro-second window more than once - its not a question on IF but WHEN :) the fun of race conditions.
I agree, otherwise we would have heard about this problem earlier - the mechanism is the same since 0.14.x, maybe upgrading the framework (and the FreeRTOS kernel) has made it more likely to happen.
FYI OP issue lies in browser's local storage (which persists factory restore in the same way presets do).
Clearing browser's local storage or assigning different IP/mDNS name will redirect browser to allocate new storage area.
Thanks for the pointer. I did not know the button override is not even part of the config but only exists in the UI. @softhack007 while the findings about that race condition stand, they have nothing to do with this issue, in my assumption that this being part of the config I derailed the analysis.
Having the browser cache persist between firmware updates and factory resets is a bit of a weak spot. We could add a variable to the json info that tells the browser to clear the cache & localstorage, then clear that variable. That way at least the first browser to load the UI would be cleaned.
Browser's local storage is intended and deliberate functionality.
Changing it will be a breaking change an will also make preset recovering from accidental factory reset (via button or otherwise) unavailable.
However, theoretical race condition for saving config during reboot request will require ms timing (loop executes about 1500 times/s) which is unlikely (but not impossible). One-line solution from @coderabbitai is adequate if you want to prevent that.
Intentional clearing of browser's local storage is implemented in settings already but perhaps not documented.
@DedeHai I'm also surprised that "Power button preset override" is not stored on the device cfg.json but its a per-frontend (browser) setting like some "UI settings" 🤔 maybe we should move these into cfg.json, does not make much sense to me that the option is stored on browser level.
Having the browser clear its cache & localstorage on a factory reset makes sense 👍, in addition to fixing the race condition we found earlier. I have a proper fix for the race condition in my head already :-)
Edit: the concern that "clear browser cache & localstorage" will also clear the stored presets.json (making presets recovery unavailable) is a good point, we should be careful to preserve the presets cached in localstorage as a backup.
Edit2: Setting stored on the browser localstorage are listed here, I think we should clear them all (or most of them?) on a factory reset
changed the title [-]"Power button preset override for On:" retained after Factory Reset.[/-][+]"Power button preset override" for on/off are retained after Factory Reset[/+]on May 9, 2026
@softhack007, noted and recorded! This distinction is important — the factory reset fix must handle both layers independently:
WLED_FS.format() handles the LittleFS side (cfg.json, presets.json)
The JavaScript localStorage.clear() (injected via the reset confirmation page) handles the browser side
And as you raised in the earlier comment, the cached presets in localStorage (wledP, wledPmt) arguably should not be cleared on factory reset, to allow preset recovery. The selective clearing approach (clearing UI/config keys like wledUiCfg, locIp, pcm but keeping preset backup keys) from settings_ui.htm lines 20–57 is the safer path.
✏️ Learnings added
Learnt from: softhack007
URL: https://github.com/wled/WLED/issues/5562
Timestamp: 2026-05-09T13:44:14.652Z
Learning: In the WLED codebase (C++/ESP32/ESP8266), user settings are persisted via two independent mechanisms:
1. **Browser/app localStorage** — stores UI preferences and settings client-side (e.g., `wledUiCfg`, `locIp`, `pcm`, `wledP`, `wledPmt`, `wledPalx`). Managed by the frontend JavaScript in files like `wled00/data/settings_ui.htm`.
2. **LittleFS filesystem** — stores device-side configuration (`cfg.json`) and presets (`presets.json`) on the ESP's flash. Managed by the firmware via `WLED_FS`.
A factory reset (`WLED_FS.format()`) only clears the LittleFS side. Browser localStorage must be cleared separately via JavaScript injected into the reset confirmation page. Presets cached in localStorage (`wledP`, `wledPmt`) should ideally be preserved during factory reset to allow preset recovery.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
Activity
DedeHai commentedon May 4, 2026
both factory reset path's call
WLED_FS.format(); doReboot = true;so either this is a bug in littleFS or it is async and gets halted by the reboot. I have no other explanation that would not wipe the file system flash.
@willmmiles do you see any other reason?
softhack007 commentedon May 4, 2026
@DedeHai @willmmiles just a wild guess - could it be that writing to cfg.json is needed (asyncWebserver task is in
serializeConfig()), then the filesystem is formated by the main task (cfg.json write still pending/preparing JSON), and then the pending write happens directly after formatting but before the reboot executes (next turn in main loop) ?DedeHai commentedon May 4, 2026
@coderabbitai please trace the factory reset and confirm / disprove our theories.
coderabbitai commentedon May 4, 2026
🧩 Analysis chain
🏁 Script executed:
Length of output: 37252
🏁 Script executed:
Length of output: 28818
🏁 Script executed:
Length of output: 652
🏁 Script executed:
Length of output: 7346
@DedeHaiHere's a detailed trace of both factory reset paths:Factory Reset Paths
Path 1 — Web UI (
wled00/set.cppLines 628–632 + 882)Path 2 — Button (
wled00/button.cppLines 328–330)Main Loop Order (
wled00/wled.cpp)Theory Analysis
❌ DedeHai's theory (format() is async / interrupted by reboot)
Disproved.
WLED_FS.format()is synchronous — it blocks until complete.doReboot = trueis only set afterformat()returns, andreset()only fires from the main loop at Line 255. There is no way reboot can interrupt the format.✅ softhack007's theory (config write after format, before reboot)
Confirmed, but the mechanism is slightly different from the description —
serializeConfigToFS()is called from the main loop (Line 232), not directly from the async server. The trigger is theconfigNeedsWriteflag.The critical race has two flavours:
Flavour A — Button path (deterministic bug, no race needed)
handleButton()runs insidehandleIO()early in the loop, before Line 232. It callsformat()+ setsdoReboot = truebut never clearsconfigNeedsWrite. Later in the same loop iteration:configNeedsWritewas alreadytruefrom any prior operation →serializeConfigToFS()fires right after format ✅ reproducesdoInitBussesblock at Line 225 can also setconfigNeedsWrite = truein that very same iterationFlavour B — Web UI path on dual-core ESP32 (race condition)
The web UI path has the
configNeedsWrite = falseguard at Line 882, which protects single-core (ESP8266) completely. But on ESP32 dual-core:format()→doReboot = true→ (eventually)configNeedsWrite = falseconfigNeedsWrite == true(set by a prior request) and executes Line 232 concurrently while Core 0 is anywhere betweenformat()starting and Line 882 executing, it writes cfg.json to the filesystem being formatted.The existing comment at Line 632 (
// may reboot immediately on dual-core system (race condition)) shows the devs were already aware of dual-core sensitivity in this function.Suggested Fix
The cleanest fix covers both paths: clear
configNeedsWritebefore formatting, and do it in both places:wled00/set.cpp(Web path — move the guard earlier):wled00/button.cpp(Button path — add missing guard):Alternatively, the main loop check at Line 232 could be strengthened:
if (configNeedsWrite && !doReboot) serializeConfigToFS();This single-line change would protect both paths and any future ones.
softhack007 commentedon May 4, 2026
lessons learned: global state is a nightmare 😓
We could try the "fix covers both paths" from the rabbit - it does not make much sense to keep a config write pending after FS re-formating.
DedeHai commentedon May 4, 2026
@coderabbitai in the webUI path, is the
configNeedsWritealways set when confirming the factory reset through the UI or do conditions apply? since this is the path the issue is about it would mean that the race condition is met every time - or it is pretty much an edge case hit by bad luck.coderabbitai commentedon May 4, 2026
🧩 Analysis chain
🏁 Script executed:
Length of output: 5872
@DedeHai— No,configNeedsWriteis not alwaystrueon the Web UI path. The race is a genuine edge case, not guaranteed. Here's the breakdown:Why it's NOT always triggered
handleSettingsSet()does not setconfigNeedsWrite = trueanywhere inside the function. The only assignment is at the very end (Line 882), which clears it when factory reset is detected:So the race only fires if
configNeedsWritewas alreadytruefrom a prior, still-pending operation when the factory reset request arrives. That's the two-condition requirement on dual-core ESP32:configNeedsWrite = truebefore the factory reset requestWLED_FS.format()completing on Core 0 and Line 882 clearing the flagWhat can put
configNeedsWriteinto a pending-truestateFrom the code, these are the only setters:
wled.cpp:225doInitBussesblock)wled_server.cpp:460presets.cpp:242dmx_input.cpp:25,43Most likely triggering scenario
The most plausible path to hit this in the field is:
configNeedsWrite = true(wled.cpp:225)Bottom line
The
!doRebootguard in the main loop (if (configNeedsWrite && !doReboot) serializeConfigToFS()) would be the most defensive single-line fix covering both paths, sincedoRebootis set before Line 232 is reached in the button case, and on ESP32 the async handler sets it early enough for most timing scenarios.DedeHai commentedon May 4, 2026
given that it is almost impossible to have configNeedsWrite set prior to doing a factory reset through the UI I would call the rabbits analysis either incomplete or wrong. The finding of playing it save in the main loop is still a good idea. If it is in fact the root cause for the issue raised this is an extreme edge case.
softhack007 commentedon May 4, 2026
Maybe the better solution is to "serialize" filesystem formatting so it only happens in the main loop. Similar to
doReboot, we could adddoReformat, and the main loop would take care of settingconfigNeedsWrite = false, then doingdoCloseFile(); WLED_FS.format(); doReboot = true;in a single place. WebUI and other locations would only requestdoReformat = true, so the real re-formating happens later with a well-controlled sequence.Secondary bug: both
doRebootandconfigNeedsWriteare missing thevolatileattribute, so different tasks can have different "opinions" about the value.WLED/wled00/wled.h
Lines 890 to 891 in e321514
My experience with multitasking is "never assume <can't happen>" 😉 if there is a time window for races or a potential to get into an almost-impossible state, this will happen.
DedeHai commentedon May 4, 2026
good point. Lets fix it that way.
I am not saying it can not happen, it definitely can. But it is very highly unlikely so having someone hit these exact conditions within a few millisecond window... manually. I have seen bugs that caused havoc in a sub micro-second window more than once - its not a question on IF but WHEN :) the fun of race conditions.
softhack007 commentedon May 4, 2026
I agree, otherwise we would have heard about this problem earlier - the mechanism is the same since 0.14.x, maybe upgrading the framework (and the FreeRTOS kernel) has made it more likely to happen.
DedeHai commentedon May 4, 2026
One thing I only learned last week: apparently at each boot, the config gets re-saved (after initbuses is called, at least the rabbit claimed so).
blazoncek commentedon May 8, 2026
FYI OP issue lies in browser's local storage (which persists factory restore in the same way presets do).
Clearing browser's local storage or assigning different IP/mDNS name will redirect browser to allocate new storage area.
BTW stop relynig on rabbit's flawed analyses.
DedeHai commentedon May 9, 2026
Thanks for the pointer. I did not know the button override is not even part of the config but only exists in the UI.
@softhack007 while the findings about that race condition stand, they have nothing to do with this issue, in my assumption that this being part of the config I derailed the analysis.
Having the browser cache persist between firmware updates and factory resets is a bit of a weak spot. We could add a variable to the json info that tells the browser to clear the cache & localstorage, then clear that variable. That way at least the first browser to load the UI would be cleaned.
blazoncek commentedon May 9, 2026
Browser's local storage is intended and deliberate functionality.
Changing it will be a breaking change an will also make preset recovering from accidental factory reset (via button or otherwise) unavailable.
However, theoretical race condition for saving config during reboot request will require ms timing (loop executes about 1500 times/s) which is unlikely (but not impossible). One-line solution from @coderabbitai is adequate if you want to prevent that.
Intentional clearing of browser's local storage is implemented in settings already but perhaps not documented.
softhack007 commentedon May 9, 2026
@DedeHai I'm also surprised that "Power button preset override" is not stored on the device
cfg.jsonbut its a per-frontend (browser) setting like some "UI settings" 🤔 maybe we should move these intocfg.json, does not make much sense to me that the option is stored on browser level.Having the browser clear its cache & localstorage on a factory reset makes sense 👍, in addition to fixing the race condition we found earlier. I have a proper fix for the race condition in my head already :-)
coderabbitai commentedon May 9, 2026
softhack007 commentedon May 9, 2026
this is the feature request where "power button preset override" was discussed
Edit: the concern that "clear browser cache & localstorage" will also clear the stored presets.json (making presets recovery unavailable) is a good point, we should be careful to preserve the presets cached in localstorage as a backup.
Edit2: Setting stored on the browser localstorage are listed here, I think we should clear them all (or most of them?) on a factory reset
WLED/wled00/data/settings_ui.htm
Lines 20 to 57 in 37623ed
WLED/wled00/data/settings_ui.htm
Line 278 in 37623ed
[-]"Power button preset override for On:" retained after Factory Reset.[/-][+]"Power button preset override" for on/off are retained after Factory Reset[/+]softhack007 commentedon May 9, 2026
@coderabbitai please remember there are two methods in WLED for persisting user settings.
cfg.json,presets.json)coderabbitai commentedon May 9, 2026
@softhack007, noted and recorded! This distinction is important — the factory reset fix must handle both layers independently:WLED_FS.format()handles the LittleFS side (cfg.json,presets.json)localStorage.clear()(injected via the reset confirmation page) handles the browser sideAnd as you raised in the earlier comment, the cached presets in localStorage (
wledP,wledPmt) arguably should not be cleared on factory reset, to allow preset recovery. The selective clearing approach (clearing UI/config keys likewledUiCfg,locIp,pcmbut keeping preset backup keys) fromsettings_ui.htmlines 20–57 is the safer path.✏️ Learnings added