Skip to content

wled_sync: drive every WLED device on the LAN to one look - #31

Merged
aphelps-claude-bot merged 14 commits into
mainfrom
wled-fleet-sync
Aug 22, 2026
Merged

aphelps-claude-bot merged 14 commits into
mainfrom
wled-fleet-sync

Conversation

@aphelps-claude-bot

@aphelps-claude-bot aphelps-claude-bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Collaborator

Scans the local subnet and drives every WLED device it finds to the same effect, colour and palette — turning them on in the process. Implements the approved plan; all eight decisions are recorded there.

$ ./wled_sync.py --effect Hiphotic --palette "Random Cycle" --dry-run
NAME        HOST         STATUS       DETAIL
Trancender  10.1.10.227  would apply  fx=180 pal=1

Why name resolution, not indices

Effect and palette numbers are firmware-specific: 220 effects on 16.0.1 against 187 on 0.14.4, and our fork reports 222. So {"fx":180} is a different effect on different hardware — a fleet that silently ends up mismatched, looking like a wiring or timing fault rather than a protocol mistake.

Names are stable enough to rely on, and I measured rather than assumed: diffing effect mode-data strings between v0.14.4 and 16.0.1 gives zero renames across the 178 shared effects — only Police and Meteor Smooth were removed. A device missing the requested name is skipped and reported, never given a near-miss substitute.

Four fields that aren't obvious

Field Why
udpn.nn The one that matters. Without it, deserializeState → stateUpdated() → notify() (led.cpp:95) re-broadcasts the raw effect/palette bytes (udp.cpp:51,69) to every device with sync receive enabled — which Trancender has. That undoes the per-device name resolution through a side channel and races our own POSTs.
tb One timebase shared across the run, so devices agree on strip.now and animate in step instead of drifting. Same knob WLED's own sync uses.
v Returns the full state instead of {"success":true}, folding verification into the same round trip. Needed because 200 ≠ applied — WLED accepts and then drops things. (Non-RGB segments are the one case deliberately not verified: WLED skips pal and forces col to white there, so checking would fail forever on working hardware.)
on A reachable device is powered, so light it. No brightness imposed — toggleOnOff() restores the device's own briLast (led.cpp:44-47), so per-device levels survive.

Palette IDs are not one list

Fixed palettes are their position in /json/pal; usermod palettes are 255-j and named only in info.umpalnames; custom are 200-k with no names at all. Position is the ID for the fixed block only — treating the array as authoritative would make usermod palettes unaddressable. /json/pal also decorates five entries with a leading *, so "Random Cycle" has to match "* Random Cycle".

--color warns when the chosen palette makes it invisible. Note the palette names mislead in both directions — Default (0) short-circuits to the segment colour so --color works there, while * Random Cycle (1) uses _randomPalette and ignores col entirely — so the set is derived from WLED's palette switch, not from names. An earlier revision had both backwards.

Tests

33 host tests, wired into the top-level Makefile as test-sync and added to test: — so CI's make test STRICT=1 actually runs them rather than the suite existing but never executing.

The cross-version case stands up two stub HTTP servers instead of requiring two firmware versions on the bench (only one device is currently reachable), and asserts the same name resolves to different indices per version. The highest-value assertion is that every generated body carries udpn.nn — that regression would be silent and fleet-wide.

Verified

  • make test STRICT=1 green, including the new suite.
  • Live --dry-run: resolved Hiphotic→fx=180 and Random Cycle→pal=1, independently matching what the device already reports running, and left its state byte-identical before/after.
  • Skip path and both --color warning paths exercised against the live device.

⚠️ Not yet run for real against hardware. Adam asked that nothing on Trancender be changed, so every live check here was --dry-run or a GET. The visual confirmation in ## Testing Required — two devices in step, 2D and 1D together, idempotent re-run — is still outstanding and needs his go-ahead.

🤖 Generated with Claude Code


Update

Self-review and re-review found several real defects, all fixed. Two worth calling out:

  • Phase alignment was silently doing nothing. tb is parsed into long tr and ignored unless tr >= 0; the tool sent an unmasked epoch-ms that overflows signed 32-bit. Intermittent — bit 31 flips ~every 24.8 days, so it would work for ~25 days and quietly stop for ~25.
  • A fix I made was worse than the bug. I briefly sent seg.fxdef to equalise speed; it resets map1D2D unguarded (WLED's own call site warns "may change map1D2D causing geometry change") and applies the effect's default palette. On a 54×24 matrix that destroys geometry, unrecoverably by re-running. Reverted for explicit --speed/--intensity.

33 tests, CI green, all review threads resolved.

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at fcf64ee. Read the files rather than the diff, ran make test-sync (23 tests green on Python 3.9.12, stdlib only), and exercised --dry-run plus GET-only queries against Trancender (10.1.10.227). Nothing was written to it.

Confirmed sound, so the inline comments below are the exceptions rather than the rule:

  • sel is in the serialized segment state (json.cpp:627), so verify_applied's filter is real and not a guess — Trancender returns "sel": true.
  • RGBW does not false-fail. serializeSegment emits four channels when strip.hasWhiteChannel() (json.cpp:602), and the [:3] truncation handles it: verify_applied({"seg":[{"sel":true,"col":[[255,0,0,0]]}]}, col=[255,0,0]) returns [].
  • Usermod palette IDs survive the round trip: getVal ignores vmin/vmax for integer input (util.cpp:71-75), so pal=255 is not clamped by the 0..getPaletteCount() bound at json.cpp:299.
  • RSVD is the only duplicated name on the live device (4 of 220), so rejecting by name rather than index is fine — and WLED itself walks forward past reserved slots (FX_fcn.cpp:592), so a stray RSVD index would silently land on a neighbouring effect. Refusing is the better behaviour.
  • /json/pal is a static PROGMEM list of exactly the fixed palettes (json.cpp:1339-1341), so custom palettes can never shift the positions the fixed block is addressed by.

Test-quality nits — none blocking, but they weaken what the suite claims:

  • tests/test_wled_sync.py:59-62 asserts only err is None, never that the returned index points at Hiphotic. It would stay green if resolution landed on the wrong entry.
  • tests/test_wled_sync.py:152-155 locks in the inverted colour_is_moot behaviour — see the first inline comment. Both assertions need flipping alongside the fix.
  • The class A argparse stubs (:244, :259) hand-copy dest names. Renaming --color's dest would leave these green while main() broke. Factoring the ArgumentParser into a build_parser() and calling parse_args([...]) would tie the test to the real surface.
  • EFF_16/EFF_014 are padding (["RSVD"] * 138, ["Android"] * 36), so test_same_name_resolves_per_device proves the mechanism but not the plan's measured claim of "zero renames across the 178 shared effects". Worth saying so in the docstring so nobody later reads it as version evidence.

PR description: says "21 host tests"; make test-sync reports Ran 23 tests (fcf64ee added two timebase tests). Its --color paragraph repeats the palette-0 error called out inline. Separately, CUSTOM_PALETTE_ID_BASE (wled_sync.py:42) is defined and never referenced — use it in resolve_palette's error message ("custom palettes are not addressable by name") or drop it.

Comment thread wled_sync.py Resolved
Comment thread scripts/wled_sync.py Resolved
Comment thread wled_sync.py Resolved
Comment thread wled_sync.py Resolved
Comment thread wled_sync.py Resolved
Comment thread wled_sync.py Resolved
Comment thread tests/test_wled_sync.py Resolved
@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Addressed in ff8f545. Every finding was verified against WLED's source before changing anything — two of them were worse than the review described.

1 (HIGH) — the colour warning was inverted. Confirmed, and the names are actively misleading in both directions:

  • Default (0) — color_from_palette short-circuits to getCurrentColor(mcol) (FX_fcn.cpp:1168-1170), so --color is at its most effective here. The tool called it moot.
  • * Random Cycle (1) — wears the same * decoration as the colour palettes, but uses _randomPalette and never touches colors[] (FX_fcn.cpp:248-249). The tool called it effective.

So it warned exactly when it shouldn't and stayed silent exactly when it should have spoken. The set is now derived from the palette switch (2-5 build CRGBPalette16 from colors[0..2]) with the citation inline, and the test asserts the two misleading cases by name.

2 (MEDIUM-HIGH) — sx/ix defeated the sync. Right, and it's the same class of failure as the timebase bug. setMode only reloads speed/intensity under loadDefaults (FX_fcn.cpp:600-611), so devices kept their own sx and ran one effect at different rates — the divergence tb exists to prevent, arriving through another door. Effect changes now send fxdef, so every device loads the same effect-defined defaults.

3 (MEDIUM) — one exception discarded the report. Fixed; failures are now caught per-device into a failed row. Your point that urlopen doesn't wrap http.client exceptions is what makes this reachable rather than defensive padding.

4 (MEDIUM) — verifier crying wolf. Both cases fixed using fields WLED already returns:

  • No segment selected → says so, instead of a phantom "wrong effect" via the or segs fallback.
  • Non-RGB segments (lc bit 0, json.cpp:597) skip the pal/col checks, which would otherwise have pinned the exit code to 1 permanently.

Thanks for confirming sel is serialized (json.cpp:627) and that RGBW 4-channel and off-segments don't false-fail — I've added explicit tests for both so they stay that way.

5 (MEDIUM-LOW) — exit code. Now non-zero if any device didn't get the look; skipped and unreachable count. Verified: all-skipped exits 1, all-resolved exits 0.

Not yet addressed, and I'd rather flag than silently skip:

  • (6) --timeout/--workers not governing discovery, and missing help=.
  • (7) the dry-run test's claim that a POST "would fail loudly" — you're right that BaseHTTPRequestHandler returns 501 and post_json swallows it into a quiet failed row. A recording do_POST is the correct fix.
  • CUSTOM_PALETTE_ID_BASE is dead, and the PR body says 21 tests (now 27).

27 tests, make test STRICT=1 green.

@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Remaining three cleared in bc29037, so nothing from the review is outstanding.

(7) The dry-run test genuinely couldn't fail — worth spelling out, because you were more right than I gave you credit for. The stub had no do_POST, so a write got a 501, which post_json swallows into a quiet failed row: the test would have passed even if --dry-run had written. The stub now accepts and records POSTs, and the test asserts nothing was recorded.

I mutation-checked it rather than assuming — disabling the dry-run branch:

test_dry_run_writes_nothing ... FAIL
AssertionError: --dry-run must not POST anything

It fails now, as it should have from the start.

(6) --timeout/--workers governed only the apply phase while discovery was pinned to hardcoded 1.0s/64. Split into explicit --discovery-timeout/--discovery-workers so the fast-sweep defaults are visible rather than buried, and every flag has help text.

Dead constant removed — with the reason recorded instead, since "why is this unused" is the question a reader would otherwise ask: WLED exposes no names for custom palettes, so they're unreachable by name by construction.

Also correcting the PR description: it says 21 host tests; there are now 27.

make test STRICT=1 green.

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed fcf64ee..bc29037. Read the files, re-read the WLED sources each claim cites, ran make test-sync (27 tests green, Python 3.9.12, stdlib only), mutation-tested every new assertion, and ran --dry-run + GETs against Trancender. Nothing was written to it.

Prior issues — status

  • ✅ colour_is_moot inversion. random cycle correctly leaves the set: palette 1 is _randomPalette (FX_fcn.cpp:248-249) and never reads colors[]. The tests now pin it, and they are not vacuous — dropping default or re-adding random cycle each makes the suite red.
  • ✅ verify_applied's or segs fallback. The sel early return matches json.cpp:470-474 exactly.
  • ✅ CUSTOM_PALETTE_ID_BASE dropped, no dangling references.
  • ✅ The dry-run stub. This is the best change in the batch — I forced sync_one past the dry_run branch and test_dry_run_writes_nothing goes red, which it could not have done before.
  • ✅ Per-device exception isolation is correct: the futs dict recovers dev, and the synthesised row carries all four keys the widths/table code indexes, so a failure there cannot KeyError the report.
  • ❌ Test nits unaddressed (fine to leave, but they still weaken the suite): tests/test_wled_sync.py:59-62 still asserts only err is None and never that the index points at Hiphotic; no build_parser(), so the class A stubs still hand-copy dest names; EFF_16/EFF_014 padding still undocumented.
  • ❌ PR description still misstates two things. It says "21 host tests" — make test-sync now reports Ran 27 tests. And its --color paragraph still reads "palette 0 or any gradient palette", which is the exact error this batch fixed in the code. The v row of the four-fields table also still sells read-back on "pal is silently ignored for non-RGB segments" — the change below deliberately stops checking that.

New — seg.fxdef is the one to reconsider. Details inline at wled_sync.py:185, but the shape of it: fxdef is not "reload sx/ix", it is "reload the effect's entire default profile", and two of those defaults are not part of a look. FX_fcn.cpp:609 resets map1D2D to M12_Pixels whenever the effect does not declare m12= (174 of 220 effects), and FX_fcn.cpp:616-617 calls setPalette() from the effect's pal= default (60 effects declare one). WLED's own call site carries the warning: json.cpp:291 — // use transition (WARNING: may change map1D2D causing geometry change). The plan asks for "a 2D matrix and a 1D strip in one run"; on the matrix this silently discards its expansion mode. If the goal is speed parity, sx/ix in the body is the narrow instrument — fxdef is the wide one, and it also does not achieve the goal on a device already running the target effect (both json.cpp:291 and FX_fcn.cpp:595 gate on fx != mode).

Everything else in the batch is sound. The new argparse help, --discovery-timeout/--discovery-workers and the exit-code rule all behave as described — verified live: --effect 'Nonexistent Effect' --dry-run now exits 1 where it previously exited 0.

Comment thread wled_sync.py Resolved
Comment thread wled_sync.py Resolved
Comment thread scripts/wled_sync.py Resolved
Comment thread scripts/wled_sync.py Resolved
Comment thread wled_sync.py Resolved
Comment thread wled_sync.py Resolved

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed bc29037..d45b830. Read both files, re-read json.cpp / util.cpp / FX_fcn.cpp and the vendored ArduinoJson for every claim, ran make test-sync under Python 3.9.12 (31 green, stdlib only), mutation-tested each new assertion, and ran --dry-run + GETs against Trancender. Nothing was written to it.

Prior issues — status

  • ✅ fxdef is gone cleanly. No load_defaults parameter, no dangling references — the only surviving mentions are the docstring and the regression test, which is where they belong. And the replacement beats fxdef on its own terms: json.cpp:294-295 applies sx/ix unconditionally, after the if (fx != seg.mode) gate at :291, so --speed reaches a device already running the target effect — the exact case fxdef could not fix.
  • ✅ sx/ix are the right keys on both sides of the wire (json.cpp:294-295 in, :621-622 out).
  • ✅ The two new tests are not vacuous. I re-added seg["fxdef"] = True and made sx unconditional; test_fxdef_is_never_sent and test_speed_and_intensity_sent_only_when_asked both go red.
  • ✅ colour_is_moot's docstring now matches the code — checked against FX_fcn.cpp:1168-1170 (palette == 0 && mcol < NUM_COLORS) and the doxygen at :1162 ("If >2, Party palette is used instead"). The "a minority pass 255" hedge is accurate, not hand-waving.
  • ✅ --host help is now correct: args.host does skip local_subnets() (:394) and is probed under --discovery-timeout (:413).
  • ✅ PR description: "31 host tests" matches make test-sync, and the --color paragraph is fixed.
  • ❌ The v row of the four-fields table is now self-contradictory. It still sells read-back with "pal is silently ignored for non-RGB segments (json.cpp:298)" — but verify_applied deliberately stopped checking exactly that (wled_sync.py:242, and is_rgb). Raised last round; the other two description items were fixed, this one wasn't. The checks that still earn read-back are the fx comparison and the "no segment selected" diagnosis — cite those instead.
  • ❌ Nit, still open: the module Usage: block (wled_sync.py:19-23) doesn't mention the two new flags.

New. Most of this batch is deletion and it is the right deletion — no objection to the revert itself, and the narrow sx/ix replacement is correctly placed. Three things, all inline. The one you flagged yourself is real: TestExitRule re-implements the rule and proves nothing (I mutated main() to return 0 and the suite stayed green). The other two are --speed/--intensity being under-defended — out-of-range doesn't clamp, it zeroes, and --dry-run can't see the flag at all.

Comment thread tests/test_wled_sync.py Resolved
Comment thread scripts/wled_sync.py Resolved
Comment thread wled_sync.py Resolved
Comment thread wled_sync.py Resolved
Comment thread scripts/wled_sync.py Resolved
@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Ready for review. CI green on 9ad0dd0, 18/18 threads resolved, mergeable.

I'm stopping the self-review cycle here deliberately, so it's a decision rather than a drift. Four rounds each found something real, so the process earned its cost — the tally is worth recording:

Round Found
1 --color warning inverted for the two palettes that matter; sx/ix divergence; exception discarding the whole report; verifier false-failures; meaningless exit code
2 My fxdef fix would have wrecked 2D geometry — resets map1D2D unguarded and applies the effect's default palette. On the 54×24 matrix we actually have, and unrecoverable by re-running
3 --speed 999 would have frozen the fleet (WLED zeroes rather than clamps); the exit-code test was vacuous
4 (this round, done directly) boundary values, single-source exit rule, no stale refs — clean

The last delta is corrective only: extracting exit_code() so its test stops being vacuous, range validation, a docstring fix, and dry-run output. I verified that surface directly — -1/256 rejected, 0/255 accepted, no duplicated rule in code or tests, no stale fxdef references — rather than spending another full round on it.

Three of the tests in this PR could not fail when written. That's a pattern in my work, not bad luck: a test written from the same understanding as the code inherits its blind spots unless it's forced through the shipped path. All three now mutation-checked.

Still not run against hardware. Every live check was --dry-run or a GET, per the instruction that nothing on Trancender changes. The visual confirmation in ## Testing Required — two devices in step, 2D and 1D together, idempotent re-run — needs a go-ahead and realistically a second device on the network.

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed d45b830..9ad0dd0 — 47/13 lines, corrective. Read both files, re-read json.cpp / util.cpp / the vendored ArduinoJson for the zeroing claim, ran make test-sync under Python 3.9.12 (32 green, stdlib only), mutation-tested the new exit-rule test and the stub change, and ran a live --dry-run against Trancender. Nothing was written to it.

This batch is essentially clean. The two substantive items both hold up under test, and I could not find a defect in them. What is below is one test-quality issue and two nits.

Prior issues — status

  • ✅ The exit-rule test is real now. Mutated exit_code to return 0 and three tests go red — last round the same mutation left the suite green. And the extracted rule is semantically identical to what it replaced: rows and len(ok) == len(rows) has the same truth table as len(ok) == len(rows) and rows (empty → 1, verified), and r.get("status") vs r["status"] cannot diverge because every row-construction path in main() sets status.
  • ✅ The range check is right, and the premise checks out. getVal(elem["sx"], seg.speed) (json.cpp:294) passes no bounds; val = elem converts through convertNumber<T> (ArduinoJson-v6.h:1385) = canConvertNumber ? TOut(value) : 0, so 999 → sx=0. Empirically: -1/256/999 → exit 2, 0/1/255 accepted, and the error prints before Scanning …, i.e. before load_scanner() and any socket. ap.error is the right mechanism.
  • ✅ --speed/--intensity standalone works, including --speed 0 — the is not None guards are correct where a truthiness test would have silently rejected 0.
  • ✅ Dry-run detail carries sx/ix. Live against Trancender: would apply fx=180 sx=128 ix=0 — note ix=0 renders, so the is not None guard is right there too. GETs only; state untouched.
  • ✅ The v row of the four-fields table now reads consistently ("200 ≠ applied" + non-RGB as the deliberate exemption). Closed.
  • ❌ Stale count in the PR description. The ## Tests section says 32 (correct — make test-sync reports 32), but the trailing ### Update section still says "31 tests, CI green".
  • ❌ Nit, third round: the module Usage: block (wled_sync.py:19-23) still doesn't mention --speed/--intensity.

New. Nothing fleet-affecting. Three inline, all low: the getattr in the dry-run detail line makes item 6 (the stub attributes) a no-op and hides the very asymmetry it was added to prevent; there is no dry_run=False test of sync_one, so the line that forwards speed=args.speed into build_body has zero coverage; and the rewritten verify_applied docstring still slightly overstates the non-RGB exemption.

Comment thread wled_sync.py Resolved
Comment thread tests/test_wled_sync.py Resolved
Comment thread wled_sync.py Resolved

@aphelps aphelps left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be in a separate "scripts" directory

@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Moved to scripts/wled_sync.py in 66f1d9e — alongside wled-ap-hop.sh, which is where it belongs.

REPO_ROOT now walks one level up so the scanner path stays repo-relative, and the test loads it from the new location. Tests stay in tests/ (where the Makefile target looks). Verified: 33 tests green, make test STRICT=1 green, and it still runs — ./scripts/wled_sync.py --effect Hiphotic --dry-run resolves fx=180 against the live device.

Two things worth flagging:

  • scripts/ was untracked. This commit starts tracking it, but only this one file. promote-base-to-main.sh and wled-ap-hop.sh are still untracked — deliberately left alone, since they're yours to decide on.
  • wled-ap-hop.sh had a destructive example in its header (unrelated to this PR, found while planning the AP-join task). Its documented POST /settings/wifi sends only credentials, but that handler reads every field unconditionally and missing ones arrive as "" — so it also emptied apSSID (killing AP-fallback recovery), forced apBehavior=0, and disabled ESP-NOW while clearing linked_remotes. I corrected the comment to use POST /json/cfg locally; since that file is untracked, it isn't in this PR.

@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Review

Cross-session review, read-only. Short version: this is in good shape. The tests are genuinely load-bearing (I mutation-tested them — 14/14 breakages go red), the Makefile wiring really runs them, and every empirical claim in the PR body that I could check held up exactly. Four real findings below, one of which I'd fix before this is pointed at hardware.


1. Correctness: a single shared tb for the whole run does not align phase — it aligns each device to its own apply time

Derived from firmware source, not observed on hardware (no device access), but I'm confident in the arithmetic.

json.cpp:418 — strip.timebase = (unsigned long)tr - millis();
FX_fcn.cpp:1324 — now = nowUp + timebase;

So for device i processing the POST at wall-clock instant T_i with local uptime m_i:

timebase_i   = tb_i − m_i(T_i)
strip.now_i(T) = m_i(T) + timebase_i = tb_i + (T − T_i)

Two devices agree iff tb_i − T_i == tb_j − T_j. With tb_i ≡ tb0 (a run constant) that reduces to T_i == T_j — i.e. it only works if every device processes the write at the same instant. The residual phase error is exactly the spread in apply times.

main() computes timebase = make_timebase() once (wled_sync.py:452) and hands the same value to every sync_one, each of which does two GETs (/json/eff, /json/pal) before its POST, across a 16-worker pool. The spread in T_i is therefore the per-device GET-latency spread: hundreds of ms across ESP32s on WiFi, seconds for anything slow or retrying, and a full batch interval once there are more than 16 devices. That is the same order as the phase error the field exists to remove.

WLED's own sync does the opposite of a run constant — udp.cpp:77 sends millis() + strip.timebase, i.e. the sender's current strip.now at send time, and the receiver adds PRESUMED_NETWORK_DELAY (udp.cpp:372-375). Per-request timestamp, not a fixed anchor. So "same knob WLED's own sync uses" is true of the knob but not of the value semantics.

Fix: call make_timebase() per POST, immediately before sending. Then tb_i − T_i is constant up to network latency and the devices actually agree. The comment at wled_sync.py:451 ("One timebase for the whole run, so every device anchors to the same instant") is inverted — a run constant anchors each device to its own arrival time.

Knock-on: test_timebase_is_shared_not_per_device pins the current behaviour and would have to change. Worth noting it also proves very little as written — it passes the same tb into three build_body calls and asserts the three come back equal.

2. Robustness (verified empirically): one non-HTTP host on port 80 aborts the entire sweep

get_json (skills/wled-scan/wled-scan.py:59) catches URLError, OSError, ValueError, JSONDecodeError. http.client.HTTPException — BadStatusLine, IncompleteRead, LineTooLong — is none of those and escapes urlopen. main() consumes ex.map(...) (wled_sync.py:444) with no protection, so the generator re-raises on the first bad host and the run dies with a traceback.

Reproduced on loopback with a socket that answers an http:// request with a TLS ClientHello (what an HTTPS-only device on 80 looks like):

probe RAISED: http.client.BadStatusLine  Pgarbage
SWEEP ABORTED: BadStatusLine  Pgarbage

This lives in the pre-existing scanner, but wled_sync is what now depends on it — and main()'s apply loop already carries a comment acknowledging exactly this class ("urlopen does not wrap every failure (http.client exceptions escape it)"), so the discovery loop is inconsistent with the author's own analysis. One line: add http.client.HTTPException to the except in get_json, or wrap the discovery map. It fails safe (dies before any write), but it makes the tool unusable on a LAN that has one such host.

3. Blast radius: no pre-flight, so a missing name leaves the fleet in two looks

sync_one resolves and applies per device, concurrently. If Hiphotic is absent on device B, device A has already been written by the time B is skipped. The exit code is 1 and the table is honest about it — but the fleet is now split, which is the state this tool exists to prevent, and re-running won't fix it.

Everything needed to decide is available before any write: both name tables are fetched at the top of sync_one. Suggest splitting into phase 1 (resolve on every device) / phase 2 (apply only if all resolved), with --partial to opt into today's behaviour. That restructure also naturally tightens the POST window, which is the mitigation for finding 1.

4. sx/ix are in the readback but not verified — and they're the values WLED silently zeroes

The comment at wled_sync.py:340 calls sx/ix "the one knob nothing downstream verifies", and --speed/--intensity are range-checked in main() precisely because an out-of-range int becomes 0 (getVal int path just does val = elem — confirmed, util.cpp:72-75, and it ignores vmin/vmax entirely for ints). But serializeSegment emits sx and ix (json.cpp:620-621), so verify_applied could check them for free. Today a device that drops sx still reports applied.

Related and smaller: that range check sits inline in main() with no test — unlike exit_code, which was deliberately extracted so the tests could hit the real rule. Same treatment would be consistent.

Minor

  • Root on and segment on aren't verified. Both are in the response (root["on"], seg on at json.cpp:591). A segment left off shows nothing while reporting applied.
  • Devices are de-duped by address string, not identity. --host trancender.local plus a sweep that finds the same box by IP gives two POSTs and two table rows. /json/info carries mac.
  • /json/eff and /json/pal are fetched unconditionally, so --color-only or --speed-only runs report unreachable on a device whose effect table read times out, even though nothing name-resolved was needed.

Verified as claimed — no action

  • Effect counts. MODE_COUNT is 220 on base-wled-16.0.1 and 187 on upstream v0.14.4 (fetched to check). The fork has 217 addEffect() calls in FX.cpp plus 5 ampworks effects: 3 fill remaining RSVD gaps, 2 append via the _modeCount++ branch at FX.cpp:10962-10966 → 222. All three numbers check out.
  • Zero renames. Mapped _data_FX_MODE_* → display name for both versions and diffed by symbol: 178 shared symbols, 0 name changes, removals exactly {FX_MODE_POLICE, FX_MODE_METEOR_SMOOTH}. Also no duplicate effect names in 16.0.1, so resolve_effect's first-match-wins is safe.
  • RESERVED_EFFECT_NAME = "RSVD" matches _data_RESERVED (FX.cpp:10947).
  • The fxcount guard is not vacuous. serializeModeNames skips any mode whose data starts with \0 (json.cpp:1211), so position ≠ index is genuinely reachable; a truncated response trips it too.
  • Palette model is right. /json/pal is the raw JSON_palette_names literal (json.cpp:1340): 72 fixed entries, index == position, no duplicates after folding, exactly 5 *-decorated — matching the constant. Usermod names come from info.umpalnames at 255-j; WLED_USERMOD_PALETTE_ID_BASE = 255 (const.h:18). Custom palettes really are nameless.
  • COLOUR_DRIVEN_PALETTES matches the code. Switch at FX_fcn.cpp:244-274 and the (palette == 0 && mcol < NUM_COLORS) || !_isRGB short-circuit at FX_fcn.cpp:1168. Default colour-driven, * Random Cycle not — backwards from the names, as the body says.
  • udpn.nn → callMode = CALL_MODE_NO_NOTIFY (json.cpp:431).
  • v:true really returns bare state. wled_server.cpp:449 → serveJson(request) → json_target::state → serializeState(lDoc) at the root, so verify_applied is parsing the right shape (not {"state":…,"info":…}).
  • tb mask is required. long tr = root["tb"] | -1; if (tr >= 0) (json.cpp:417-418) — 32-bit signed on ESP32. Claim accurate.
  • Non-RGB exemption is right. pal is gated on lc & 1 (json.cpp:298); only active segments are serialized (json.cpp:693) and an id-less seg body applies to isActive() && isSelected() (json.cpp:470-474), so verify's sel filter matches the write exactly. col is always numeric arrays (json.cpp:604-617), never hex strings, so the 3-channel prefix compare is safe on RGBW.
  • on:true is a no-op on an already-on device (if (!on != !bri) toggleOnOff();, json.cpp:383) and restores briLast when off. No brightness imposed, as claimed.
  • Writing a non-WLED host would require it to serve /json/info with brand: WLED (or a leds key) and list-shaped /json/eff and /json/pal and contain the requested name. Narrow enough.

Test suite and Makefile — checked, both real

  • make test → test-sync → python3 tests/test_wled_sync.py. Confirmed by running it: a single flipped assertion makes make test-sync exit 2, and with the file removed STRICT=1 errors instead of skipping. CI runs make test STRICT=1 (ci.yml:91), so it is genuinely wired in.
  • Mutation-tested 14 targeted breakages of scripts/wled_sync.py against the suite in a scratch copy. All 14 go red: dropping udpn.nn; making RSVD selectable; exit_code → always 0; removing the * strip; making dry-run fall through to POST; removing the fxcount guard; removing the tb mask; ignoring sel in verify; usermod base 255→200; sending fxdef; dropping sx; skipping the fx check in verify; inverting colour_is_moot; dropping the colour range check. No vacuous tests found — a real change from this repo's history.
  • Only test gaps I'd call out: the --speed range guard (finding 4) and test_timebase_is_shared_not_per_device (finding 1).

Finding 1 is the one that matters — it's the difference between the phase field working and being decorative, and it currently has a test holding it in place. 2 and 3 are worth closing before this points at a whole LAN. Everything else is polish.

🤖 Reviewed with Claude Code

@aphelps aphelps left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add to the README a description and basic use of this new script.

Then file a task to write a comprehensive top level README

Comment thread scripts/wled_sync.py Resolved
@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Both items addressed in ca374e0, and I owe you an explanation for the delay first.

Why this sat for ~11 hours. My hourly check polled only reviewDecision. That field reads CHANGES_REQUESTED identically whether the review landed four days ago or four minutes ago — so your new review at 15:40Z produced no visible change and I never looked. It is not a change detector, and I was using it as one. I now key on the newest non-bot review/comment timestamp plus a count of unresolved threads, which is what surfaced this. Worth noting you asked about #32, where nothing was actually outstanding; the miss was here.

The import. No good reason — a slip, not a decision. ipaddress is stdlib, there is no circular import to break and no optional dependency to guard, so nothing justified deferring it. It was also the only mid-file import in the module; the other ten were already at the top, which makes it plainly inconsistent rather than a deliberate local exception. Hoisted; thread resolved.

The README. Added scripts/README.md with what wled_sync does and how to run it, leading with --dry-run. The flag table is there, but the space goes to the behaviours that actually catch people out:

  • a palette can silently override --color, because most palettes supply their own colours and the effect ignores the segment colour entirely — the README names the colour-driven ones
  • --speed/--intensity are deliberately unset by default, since they are usually tuned per installation and overwriting them fleet-wide destroys that
  • out-of-range speed/intensity is rejected up front, because WLED does not clamp: above 255 becomes 0, freezing every device at once
  • effect and palette match by name, because the numbers differ between firmware builds

A check confirms every flag the parser defines appears in the README — 15 flags, none undocumented.

One thing to flag: this file will conflict with the scripts/README.md that #32 adds for wled_apjoin. I wrote it in the same shape (index table, then one section per script) so resolving is mechanical rather than a rewrite. #32 is approved, so if it merges first I will rebase this and fold the two sections together.

Top-level README task filed — it is in Ready Tasks. Worth saying plainly: there is no README.md at the repo root at all today, so a newcomer lands on CLAUDE.md (written for agents) or skills/README.md (skills only). I scoped it as an index that makes the existing material findable rather than a rewrite, since most of it exists but is scattered across CLAUDE.md, two READMEs and the plan files.

33 host tests pass.

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved, but held: blocked on human testing, not on code.

## Testing Required has four items and I cannot honestly tick any of them — every one needs two or more physical devices, and only one is reachable right now (2cbcbbd98960 at 192.168.1.39). Merge is gated until you /ack-tested.

  • Two or more physical devices driven to the same look, confirmed visually — ideally one on a different firmware version, since mismatched effect/palette indices between builds are exactly what this tool avoids by matching on names. One device cannot demonstrate that.
  • A 2D matrix and a 1D strip in one run — the effect is sensible on both, or the mismatch is reported rather than silently rendering oddly.
  • Re-running is idempotent — no visible flicker or restart.
  • Confirm which other devices can be powered on, or accept the stub-server test as the cross-version evidence.

The last one is really a question for you rather than a test: the host suite covers cross-version behaviour against a stub server, and if you would rather accept that than power up a second board, say so and I will record it as the evidence and tick it.

Code side is done: the import is hoisted, scripts/README.md documents the script, the thread is resolved, and CI is green.

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved, but held: blocked on human testing, not on code.

## Testing Required has four items and I cannot honestly tick any of them — every one needs two or more physical devices, and only one is reachable right now (2cbcbbd98960 at 192.168.1.39). Merge is gated until you /ack-tested.

  • Two or more physical devices driven to the same look, confirmed visually — ideally one on a different firmware version, since mismatched effect/palette indices between builds are exactly what this tool avoids by matching on names. One device cannot demonstrate that.
  • A 2D matrix and a 1D strip in one run — the effect is sensible on both, or the mismatch is reported rather than silently rendering oddly.
  • Re-running is idempotent — no visible flicker or restart.
  • Confirm which other devices can be powered on, or accept the stub-server test as the cross-version evidence.

The last one is really a question for you rather than a test: the host suite covers cross-version behaviour against a stub server, and if you would rather accept that than power up a second board, say so and I will record it as the evidence and tick it.

Code side is done: the import is hoisted, scripts/README.md documents the script, the review thread is resolved, and CI is green.

@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Approved, but held: blocked on human testing, not on code.

## Testing Required has four items and I cannot honestly tick any of them — every one needs two or more physical devices, and only one is reachable right now (2cbcbbd98960 at 192.168.1.39). Merge is gated until you /ack-tested.

  • Two or more physical devices driven to the same look, confirmed visually — ideally one on a different firmware version, since mismatched effect/palette indices between builds are exactly what this tool avoids by matching on names. One device cannot demonstrate that.
  • A 2D matrix and a 1D strip in one run — the effect is sensible on both, or the mismatch is reported rather than silently rendering oddly.
  • Re-running is idempotent — no visible flicker or restart.
  • Confirm which other devices can be powered on, or accept the stub-server test as the cross-version evidence.

The last one is really a question for you rather than a test: the host suite covers cross-version behaviour against a stub server, and if you would rather accept that than power up a second board, say so and I will record it as the evidence and tick it.

Code side is done: the import is hoisted, scripts/README.md documents the script, the review thread is resolved, and CI is green.

aphelps pushed a commit that referenced this pull request Aug 9, 2026
The self-review found six issues; four were real and are fixed here. The
embarrassing ones are in the checker I added to prevent exactly this.

**Commands in the README did not run when pasted.** `make test-bridge# HMTL
wire format (run twice: ...)` — `#` glued to the target is not a bash
comment, so pasting it gave `No rule to make target 'test-libs#'` and a
bash syntax error on the parentheses. Both reproduced. In a document whose
whole purpose is being followable by someone who cannot ask a question,
that is the worst defect in the PR. The columns are now aligned so every
`#` is a real comment, and two checks guard it: `bash -n` per line, plus an
assertion that `#` is preceded by whitespace — because `bash -n` only
catches syntax errors, and `make test-libs# note` parses fine while
invoking a target that does not exist.

**Two assertions could never fail.**
- The submodule check used a substring test, and `aphelps/WLED` is a
  substring of the clone URL `aphelps/WLED_dev.git`, so it passed with the
  entire WLED row deleted. Strengthened to require the path and its
  upstream URL on the same line — which also fixes a second weakness found
  while mutation-testing: `| \`WLED/\`` appears in the Repo layout table
  too, so "does this path appear anywhere" was still satisfiable.
- The env and .gitmodules sections announced they were checking the README
  while testing hardcoded literals. They now parse the README's own tables,
  so a typo or a rename fails.

**`make test` broke unhelpfully on an uninitialised clone** — `test-readme`
was the only suite with no `require_submodule` guard, so it died on a
FileNotFoundError traceback instead of the deliberate "run ./setup.sh"
message. Guarded, and the script now resolves paths from its own location
rather than the cwd.

Also added the drift-prone numbers the docstring claimed to protect but did
not check: WLED version, env count, default_envs count, default device IP.
Writing that check found my own error — the first regex ran past the blank
line terminating `default_envs` and reported 36 where the answer is 23. The
README was right; the check was wrong.

Every check is now mutation-tested: 10 deliberate defects introduced, 10
caught. One apparent miss was a mis-specified mutation that changed a link
label while leaving the URL correct — passing was the right answer, and
mutating the URL itself is caught.

Not fixed, deliberately: the fleet-scripts pointer. `scripts/` is untracked
on main until #31/#32 land, so linking it would fail the link checker. A
follow-up adds it.

make test green.

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

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 9ad0dd0..ca374e0 — the scripts/ move, the new scripts/README.md, and the apply-path test. Checked out ca374e0 in a temp worktree, ran make test-sync (33 green, Python 3.9.12), confirmed scripts/wled_sync.py --help runs from the new path, verified the README's options table against the actual argparse defaults and its colour-driven palette list against COLOUR_DRIVEN_PALETTES (both match), and grepped the test suite against the README's claims. No device was contacted this round — no GETs, no writes.

Prior issues — status

  • ✅ Stale count in the PR description: ## Tests and ### Update both say 33 now, and make test-sync reports exactly 33.
  • ✅ Module Usage: block now shows --speed 128 --intensity 200.
  • ✅ getattr no-op: replaced with plain args.speed is not None / args.intensity is not None, so the stub attributes are load-bearing — proven by the new apply-path test, which drives sync_one through a bare attribute class.
  • ✅ Apply-path coverage: test_apply_forwards_speed_and_intensity runs sync_one with dry_run=False and asserts sx/ix/tb/udpn.nn on the actual wire body — exactly the uncovered forwarding line flagged last round, plus a bonus re-assertion of the broadcast-suppression flag on the live path.
  • ✅ verify_applied docstring now scopes the non-RGB exemption to pal/col and states fx is still verified.

New

  • One real finding, inline: the README's Tests paragraph describes a different test suite.
  • One nit, inline: the exit-status sentence overlooks usage errors exiting 2.
  • TOP-LEVEL: the PR is now CONFLICTING against main. git merge-tree shows the Makefile is the only conflicted file — the recently merged top-level-readme work touched it, and this branch adds the test-sync target there. Needs a rebase/merge before it can land; the CI pass on ca374e0 predates the conflict, so let CI re-run on the rebased head.

Comment thread scripts/README.md Resolved
Comment thread scripts/README.md Resolved
aphelps-claude-bot and others added 10 commits August 18, 2026 01:05
Scans the local subnet and applies the same effect, colour and palette to every
device it finds, turning them on in the process.

Resolution is BY NAME, per device. Effect and palette numbers are
firmware-specific — 220 effects on 16.0.1 against 187 on 0.14.4 — so the same
index is a different effect on different hardware, which would silently produce a
mismatched fleet that looks like a wiring or timing fault. Names are stable:
diffing mode-data strings between v0.14.4 and 16.0.1 shows zero renames across
the 178 shared effects, only Police and Meteor Smooth removed. A device missing
the requested name is skipped and said so, never given a near-miss substitute.

Four things in the request body are there for non-obvious reasons:

  udpn.nn  suppresses WLED's own UDP sync. Without it, deserializeState ->
           stateUpdated -> notify() (led.cpp:95) re-broadcasts the RAW effect and
           palette bytes (udp.cpp:51,69) to every device with sync receive on --
           which Trancender has -- undoing the per-device name resolution through
           a side channel and racing our own POSTs.
  tb       one timebase shared across the whole run, so devices agree on
           strip.now and animate in step rather than drifting apart.
  v        makes WLED return the full state instead of {"success":true}, folding
           verification into the same round trip with no window for a playlist or
           another operator to slip in. Needed because a 200 does not mean
           applied: pal is silently ignored for non-RGB segments (json.cpp:298).
  on       a reachable device is powered, so light it. No brightness is imposed --
           toggleOnOff restores the device's own briLast (led.cpp:44-47), so
           per-device levels survive.

Palette IDs are not one contiguous list: fixed palettes are their position in
/json/pal, usermod palettes are 255-j and are named only in info.umpalnames, and
custom are 200-k with no names at all. Position is the ID for the fixed block
only. /json/pal also decorates five entries with a leading '*', so "Random Cycle"
must match "* Random Cycle".

--color warns when the chosen palette will make it invisible: under palette 0 or
any gradient palette most effects take colour from the palette and ignore col
entirely, and a flag that silently does nothing reads as a bug.

21 host tests, wired into the top-level Makefile as test-sync so CI's
`make test STRICT=1` actually runs them. The cross-version case stands up two
stub HTTP servers rather than needing two firmware versions on the bench -- only
one device is currently reachable. Highest-value assertion is that every
generated body carries udpn.nn: that regression would be silent and fleet-wide.

Verified live in --dry-run against the one reachable device: resolved Hiphotic to
fx=180 and Random Cycle to pal=1, independently matching what it already runs,
and left its state byte-identical.
WLED parses `tb` into `long tr` (json.cpp:398) and ignores it unless `tr >= 0`
(json.cpp:417-418). `long` is 32-bit signed on ESP32, but the tool was sending
`int(time.time()*1000) & 0xFFFFFFFF` — 3124561992 today, well above INT32_MAX.
That value does not survive the parse, so `strip.timebase` was never assigned and
devices kept their own phase while the tool reported success. Exactly the silent
no-op this tool is built to avoid.

The failure is intermittent, which is worse than a constant one: bit 31 of
epoch-milliseconds flips about every 24.8 days, so alignment would have worked
for ~25 days, quietly stopped for ~25 days, then resumed — reading as
"sometimes the lights drift" rather than as a bug.

Masks to 31 bits instead. The absolute value is arbitrary: `strip.timebase =
tb - millis()` means only agreement between devices matters, not the epoch.

The existing test missed this by asserting on a small literal (1234567) rather
than what the tool actually generates. Added two regressions: one constructing
the overflow half explicitly (0x1C0000000, so it does not depend on when the
suite runs — my first attempt used a "realistic" epoch that happened to land in
the safe half and passed against the broken code), and one asserting the anchor
is shared across devices, since alignment depends on every device getting the
same value.
…ted the sync

colour_is_moot had the two palettes that matter exactly backwards, so the tool
warned precisely when it should have stayed quiet and stayed quiet precisely when
it should have warned. Both were verified in WLED's source rather than inferred
from the names, which mislead in both directions:

  "Default" (0)        color_from_palette short-circuits to getCurrentColor()
                       (FX_fcn.cpp:1168-1170), so --color is at its MOST effective
                       here — the tool called it moot.
  "* Random Cycle" (1) wears the same '*' as the colour palettes but uses
                       _randomPalette and never reads colors[] (FX_fcn.cpp:248-249),
                       so --color does nothing — the tool called it effective.

Palettes 2-5 build their CRGBPalette16 from colors[0..2] and are genuinely
colour-driven. The set now cites the switch it came from.

Effect changes now send fxdef. setMode only reloads speed/intensity under
loadDefaults (FX_fcn.cpp:600-611), so without it every device kept its own sx/ix
and ran the same effect at a different rate — the exact divergence the shared
timebase exists to prevent, arriving through another door.

One device's exception no longer discards the whole report. f.result() re-raised
inside the as_completed loop and the traceback escaped before the table printed;
urlopen does not wrap http.client exceptions, so this was reachable rather than
theoretical.

verify_applied stops crying wolf in two knowable cases, both distinguishable from
fields WLED already returns. A seg body with no id only touches SELECTED segments
(json.cpp:470-474), so when none are selected nothing was written — previously
reported as a phantom "wrong effect" via an `or segs` fallback. And non-RGB
segments have pal skipped and col forced to white, which would have pinned the
exit code to 1 forever; lc (json.cpp:597) identifies them.

Exit code now reflects whether devices actually got the look: skipped and
unreachable count as failure. A run where every device was skipped was exiting 0.

27 tests, including the RGBW four-channel and unselected-segment cases that the
reviewer asked about specifically — neither false-fails.
The dry-run test could not fail. Its stub had no do_POST, so a write got a 501,
which post_json swallows into a quiet "failed" row — the test would have passed
even if --dry-run had written. The stub now accepts POSTs and records them, and
the test asserts nothing was recorded. Mutation-checked by disabling the dry-run
branch: the test fails, as it should have all along.

--timeout and --workers governed only the apply phase while discovery was pinned
to hardcoded 1.0s/64. Split into explicit --discovery-timeout/--discovery-workers
so the fast-sweep defaults stay visible rather than hidden, and gave every flag
help text.

Dropped CUSTOM_PALETTE_ID_BASE. It was never used, and the reason is worth
stating rather than leaving an unused constant to puzzle over: WLED exposes no
names for custom palettes, so they cannot be selected by name at all.
…x/ix

The previous commit sent seg.fxdef to equalise speed across devices. That was
overreach and would have damaged the one device we actually have.

setMode(fx, true) resets far more than sx/ix. It resets map1D2D UNGUARDED for any
effect that does not declare m12=, and WLED's own call site carries the warning:
"may change map1D2D causing geometry change" (json.cpp:291). On a matrix that
destroys the expansion mode, and re-running does not undo it — Trancender is a
54x24 matrix, so the fix targeted exactly the hardware it would have broken. It
also applies the effect's default palette (FX_fcn.cpp:616-617), silently
overriding colour whenever --palette was not given: --effect "Noise 1" --color
red would have applied gradient palette 20 and made the red invisible, with no
warning, verification passing, and the row reporting success.

It would not even have fixed the problem it was for: both call sites gate on
fx != mode, so a device already running the target effect keeps its drifted
speed. Broken on the second run, destructive on the first.

Replaced with explicit --speed/--intensity, which are narrower and idempotent.
They are NOT sent by default: speed is often deliberately tuned per installation,
so normalising it silently is its own kind of wrong. Documented that a shared
effect can still run at different rates without them.

Also: the verify_applied and colour_is_moot docstrings still described pre-fix
behaviour and contradicted the code beneath them; softened the "Default is where
--color is MOST effective" claim, since it holds only for call sites passing
mcol < NUM_COLORS and a minority pass 255; and corrected --host's help, which
claimed to skip discovery when the host is still probed.

Added the exit-code tests that were missing — the only change in the last batch
that was not mutation-proof. Verified the new rule differs from the old on all
four cases that matter (skipped, unreachable, mixed, empty), so the tests would
genuinely fail against the previous behaviour.
TestExitRule was vacuous — it hand-copied the rule into the test file instead of
calling it, so mutating main() to `return 0` left all 31 tests green. The rule is
now exit_code() at module level and the test calls it; mutation-checked, two
tests go red. This is the third test in this PR that could not fail, so the
pattern is mine, not bad luck: a test written from the same understanding as the
code inherits its blind spots unless it is forced through the shipped path.

--speed/--intensity are now range-checked. WLED does not clamp: getVal passes no
bounds (json.cpp:294) and ArduinoJson's convertNumber returns 0 when the value
will not fit a uint8_t, so `--speed 999` would have set sx=0 on every device — a
visible freeze on most effects — while verify_applied never checks sx/ix, every
row read "applied" and the exit code stayed 0. Silent, fleet-wide, and only
catchable by looking at the lights.

They can also now be used alone; requiring --effect/--palette/--color to
accompany them was arbitrary, since a speed-only run is valid on every device.
And --dry-run prints sx/ix, without which the safety valve was blind to the one
knob nothing downstream verifies.

verify_applied's docstring claimed both the non-RGB and no-selected-segment cases
were exempt from reporting. Only the first is; the second is reported, with the
real reason instead of a misleading "wrong effect". The test asserted the
opposite of the paragraph above it.
Nothing ran sync_one with dry_run=False, so the line forwarding args.speed into
build_body had zero coverage and the stubs' speed/intensity attributes were
decorative — removing them left the suite green. There is now an apply-path test
asserting what actually goes on the wire (sx, ix, tb, udpn.nn), and both
mutations bite: dropping the forwarding fails it, and so does removing the stub
attributes.

Replaced getattr(args, "speed", None) with plain attribute access in the dry-run
detail. The defensive form hid exactly the mismatch the stub attributes existed
to catch — dry-run tolerated a missing attribute while the apply path raised
AttributeError on it.

The verify_applied docstring said non-RGB segments are "EXEMPT", but fx is still
checked on them and the suite asserts that. Only pal and col are exempt.

Sharpened the range-check message: WLED's two out-of-range behaviours differ. A
value above 255 becomes 0 via convertNumber, freezing the fleet; a negative one
is ignored outright (util.cpp:73). Rejecting both is right, but the message
claimed zeroing for both.

Module usage block now shows --speed/--intensity.
Puts it alongside wled-ap-hop.sh rather than at the repo root. REPO_ROOT now
walks one level up so the scanner path and the seam stay repo-relative, and the
test loads it from its new location. Tests stay in tests/, which is where the
Makefile target expects them.

Note scripts/ was previously untracked — this commit starts tracking it, but
only this file. promote-base-to-main.sh and wled-ap-hop.sh remain untracked and
are not mine to add.
Both from Adam's review of 2026-08-07.

The import first, since it is the shorter answer: there was no reason for
`import ipaddress` to sit inside main(). It is stdlib, there is no circular
import to break and no optional dependency to guard — it was a slip, not a
decision. It is the only mid-file import in the module; the other ten were
already at the top. Moved.

scripts/README.md documents what wled_sync does and how to run it, leading
with dry-run. The parts that earn their space are the behaviours that
surprise people rather than the flag list:

- a palette can silently override --color, because most palettes supply
  their own colours and the effect ignores the segment colour; the tool
  warns, and the README says which palettes are colour-driven
- --speed/--intensity are deliberately unset by default, since they are
  usually tuned per installation and overwriting them fleet-wide destroys
  that
- out-of-range speed/intensity is rejected up front because WLED does not
  clamp — above 255 becomes 0, freezing every device at once
- effect and palette are matched by NAME because the numbers differ between
  firmware builds

A check confirms every flag the parser defines appears in the README: 15
flags, none undocumented.

Note this file will conflict with the one PR #32 adds, which documents
wled_apjoin in the same shape. Written to match its structure so resolving
is mechanical — two sections in one index.

The separate task for a comprehensive top-level README is filed; there is
no README.md at the repo root at all today.

33 host tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
aphelps-claude-bot added a commit that referenced this pull request Aug 20, 2026
* add a top-level README, verified against the source files

There was no README.md at the repo root, so a newcomer landed on CLAUDE.md
(written for agents) or skills/README.md (skills only). Neither answers
"what is this and where do I start".

Adam's three decisions shaped it, and the first two changed the task:

- **Audience is him plus collaborators who may be remote and setting up
  while he is unavailable.** So it has to stand alone: a "when it goes
  wrong" section, and the traps documented rather than just the happy path.
- **"Quick deploy on clone should be the standard."** Clone -> setup ->
  build -> flash -> verify is the spine, not an appendix. Flashing and
  confirming /json/info matches what you built are part of the main path.
- **Reference only files in this repo.** That rule and the gitlink problem
  agree: submodule docs (BACKBONE_ROUTER.md, SENSOR_SYNC.md, the
  rs485_bridge readme) are named as plain-text paths, never linked — they
  are not this repo's files and they 404 on github.com because GitHub
  renders a submodule as a commit pointer.

It deliberately does not send the reader to CLAUDE.md for any setup step.
CLAUDE.md is written for agents, and it carries at least three claims that
are no longer true — the default build env, the number of make targets, and
the WLED version (it says 0.15.3; package.json says 16.0.1). Propagating
those to the people least able to spot them would be the worst outcome.

That is also why tools/check_readme.py exists, wired in as `make
test-readme` and part of `make test`. It verifies the README against
platformio.ini, the Makefile and .gitmodules rather than trusting anyone's
memory: links resolve to tracked files, no link points into a submodule,
every make target and [env:] named exists in the file it is attributed to,
the submodule table matches .gitmodules, and setup.sh/upload_wled.py really
support the flags shown. My own first draft inherited two of CLAUDE.md's
stale claims, which is the failure this guards against.

Scoped to what is on main today: scripts/ and tests/ arrive with #31/#32,
so nothing references them yet and `make test` is described as four suites.
A follow-up adds the scripts section once those land.

make test green.

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

* address self-review: a checker whose checks could not fail

The self-review found six issues; four were real and are fixed here. The
embarrassing ones are in the checker I added to prevent exactly this.

**Commands in the README did not run when pasted.** `make test-bridge# HMTL
wire format (run twice: ...)` — `#` glued to the target is not a bash
comment, so pasting it gave `No rule to make target 'test-libs#'` and a
bash syntax error on the parentheses. Both reproduced. In a document whose
whole purpose is being followable by someone who cannot ask a question,
that is the worst defect in the PR. The columns are now aligned so every
`#` is a real comment, and two checks guard it: `bash -n` per line, plus an
assertion that `#` is preceded by whitespace — because `bash -n` only
catches syntax errors, and `make test-libs# note` parses fine while
invoking a target that does not exist.

**Two assertions could never fail.**
- The submodule check used a substring test, and `aphelps/WLED` is a
  substring of the clone URL `aphelps/WLED_dev.git`, so it passed with the
  entire WLED row deleted. Strengthened to require the path and its
  upstream URL on the same line — which also fixes a second weakness found
  while mutation-testing: `| \`WLED/\`` appears in the Repo layout table
  too, so "does this path appear anywhere" was still satisfiable.
- The env and .gitmodules sections announced they were checking the README
  while testing hardcoded literals. They now parse the README's own tables,
  so a typo or a rename fails.

**`make test` broke unhelpfully on an uninitialised clone** — `test-readme`
was the only suite with no `require_submodule` guard, so it died on a
FileNotFoundError traceback instead of the deliberate "run ./setup.sh"
message. Guarded, and the script now resolves paths from its own location
rather than the cwd.

Also added the drift-prone numbers the docstring claimed to protect but did
not check: WLED version, env count, default_envs count, default device IP.
Writing that check found my own error — the first regex ran past the blank
line terminating `default_envs` and reported 36 where the answer is 23. The
README was right; the check was wrong.

Every check is now mutation-tested: 10 deliberate defects introduced, 10
caught. One apparent miss was a mis-specified mutation that changed a link
label while leaving the URL correct — passing was the right answer, and
mutating the URL itself is caught.

Not fixed, deliberately: the fleet-scripts pointer. `scripts/` is untracked
on main until #31/#32 land, so linking it would fail the link checker. A
follow-up adds it.

make test green.

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

* address review: block-level bash -n, narrowed glued-# check, scoped and guarded ini lookups

Co-Authored-By: Claude Fable 5 <[email protected]>

* address review: glued-# check also covers tabled env names

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: aphelps-claude-bot <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed ca374e0..b9d7e0a. Content-wise this delta is a rebase onto b20f900 plus one docs commit — the only new authored change is the scripts/README.md paragraph in b9d7e0a; the Makefile/HMTL hunks are main's #33 being picked up. The rebase resolution is faithful: git diff b20f900:Makefile b9d7e0a:Makefile is exactly the test-sync additions and nothing else, so nothing changed behaviour beyond what the commit messages claim. Ran make test-sync on the head (33 green, Python 3.9.12), then mutation-tested the suite — 44 mutations of scripts/wled_sync.py, suite re-run per mutation. No device was contacted this round: no GETs, no writes.

Prior issues — status

  • ✅ Exit-status sentence now mentions exit 2, and that is right — ap.error goes through argparse's exit 2. (SIGINT's 130 is still unmentioned; not worth a round-trip.)
  • ✅ README Tests paragraph now describes this suite rather than the ordering/convergence suite. But two of its four claims are still inaccurate — inline.
  • ❌ Still CONFLICTING, same file, same place. The rebase landed on b20f900, but main has since moved to f2e9378 (#34 top-level README, #35 HMTL bump). git merge-tree b20f900 b9d7e0a origin/main reports exactly one conflicted file, Makefile: main's line is now test: … test-router test-readme, this branch's is test: … test-router test-sync. Resolution is the union in both the test: and .PHONY: lines. Needs another rebase, and CI should re-run on the new head.

Mutation testing — the half that holds up

The pure layer is genuinely non-vacuous. 31 of 33 mutations to build_body, resolve_effect, resolve_palette, verify_applied, exit_code, parse_colour, colour_is_moot and make_timebase turned the suite red — including udpn.nn → False, USERMOD_PALETTE_ID_BASE 255 → 200, dropping the *-strip, dropping the RSVD skip, removing the tb 31-bit mask, computing make_timebase() per device, and emitting fxdef. The three commits claiming to have made tests real did deliver on the functions they name: exit_code and the apply-path body assertion are both load-bearing, and test_apply_forwards_speed_and_intensity genuinely kills the forwarding mutations.

Mutation testing — the half that does not (TOP-LEVEL)

Everything above those functions is effectively untested. All 11 mutations of sync_one's decision/reporting wiring and of main()'s guards left all 33 tests green:

mutation applied to scripts/wled_sync.py suite
sync_one never reports mismatch (if problems: → if False:) green
sync_one skips verify_applied entirely green
verify_applied called with fx=None green
POST error → row "applied" instead of "failed" green
unreadable /json/eff → "applied" instead of "unreachable" green
effect resolution error ignored — body sent with no fx, row still says applied green
palette resolution error ignored — same green
dev.get("umpalnames") → None green
the "nothing to sync" guard removed green
the colour-is-moot warning never printed green
--no-phase ignored (always phase-align) green
the --speed/--intensity range check removed green

Four of those are the exact failure modes the plan exists to prevent: "a device lacking the requested name is skipped with a clear message, never given a near-miss substitute", the --color warning an earlier round found inverted, per-device usermod-palette resolution, and the --speed 999 freeze that round four caught. Each is guarded by code no test can distinguish from a no-op. Suggested test: items inline.

Name resolution — checked against the firmware, and it is correct

  • /json/eff ← serializeModeNames (WLED/wled00/json.cpp:1205-1217): @-stripped, and it does silently drop modes with an empty data string — which is exactly what the fxcount guard catches. _data_RESERVED is literally "RSVD" (FX.cpp:10947).
  • /json/pal ← JSON_palette_names served verbatim (json.cpp:1340) — fixed palettes only, so list position == palette ID. The ID-bearing serializePalettes is /json/palx, correctly not used.
  • umpalnames is a top-level key of /json/info (json.cpp:797-804), present only when usermod palettes exist, and wled-scan.probe() returns the whole info dict — so dev.get("umpalnames") is the right lookup, not dev["info"]["umpalnames"].
  • 255-j survives the wire even though the call site looks like it bounds to 75: getVal(elem["pal"], pal, 0, getPaletteCount()) ignores vmin/vmax for integer values (util.cpp: val = elem; return true;), and Segment::setPalette range-checks the usermod band itself (FX_fcn.cpp), falling back to 0 only when the band is empty — which verify_applied would then catch. Worth recording; it is not obvious from json.cpp:299.
  • Failures are per-device rows carrying a reason, and exit_code makes any skipped a non-zero exit. The design is right; only the wiring between it and main() is unproven.

Phase-locking — real, but narrower than the docstring claims (TOP-LEVEL)

The plan's open subtask ("verify toggleOnOff()'s restartRuntime() does not fight a tb sent in the same request") resolves favourably on ordering: toggleOnOff() runs at json.cpp:383, tb at json.cpp:417-418, so strip.timebase = tb - millis() is applied last and is not clobbered. So the mechanism is real, not merely apparent. But restartRuntime() → resetIfRequired() zeroes step, call, aux0, aux1 and clears the segment data buffer (FX_fcn.cpp:212-225), and tb restores none of that. tb aligns strip.now and nothing else: effects that advance via those accumulators rather than strip.now are not phase-locked by it, and on the first sync of a fleet where some devices were dark and some lit, only the dark ones are reset — an asymmetry tb cannot correct. FX.cpp carries 194 strip.now references against 234 SEGENV.step/.call ones, so this is not a corner case. Inline suggestion to scope the claim; it also predicts the still-open "re-running is idempotent" item without needing eyes on the LEDs first.

Nits

  • Makefile:8 — the header usage block lists every target except the one this PR adds. (Not inline: that line falls outside the PR's diff hunks.) Add # make test-sync # just the wled_sync host tests after the test-router line.
  • After a rebase onto current main, scripts/ and make test-sync will be missing from the new top-level README.md — both its ## Testing target list (README.md:100-107) and its ## Repo layout table (:132-140). tools/check_readme.py only checks that targets the README names exist, not the reverse, so make test-readme stays green; this is a doc gap, not a CI break.
  • resolve_effect's empty-name guard (wled_sync.py:90-91) is unreachable from the CLI — if args.effect: already filters "" — and deleting it leaves the suite green. Harmless; flagged only so it is not mistaken for tested behaviour.

Verdict: the code is sound, and the delta's claims about making tests real are true for the functions those commits name. The remaining gap is one layer up — sync_one and main() are almost entirely unproven — and the new README paragraph overstates what the suite actually covers.

Comment thread scripts/README.md Resolved
Comment thread scripts/README.md Resolved
Comment thread scripts/wled_sync.py Resolved
Comment thread scripts/wled_sync.py Resolved
Comment thread scripts/wled_sync.py Resolved
Comment thread scripts/wled_sync.py Resolved
Comment thread scripts/wled_sync.py
on — a reachable device is powered, so light it. WLED restores its own briLast, so no
brightness is imposed and per-device levels survive.
tb — shared phase anchor; strip.timebase = tb - millis(), so all devices agree on
strip.now and animate in step.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"so all devices agree on strip.now and animate in step" — the first clause is right, the second does not follow, and I think the gap explains the still-open "re-running is idempotent" item.

Good news first: the plan's open worry (does toggleOnOff()'s restartRuntime() fight a tb in the same request?) resolves in your favour on ordering — toggleOnOff() is at json.cpp:383, tb at json.cpp:417-418, so strip.timebase is written last and survives.

But restartRuntime() → resetIfRequired() zeroes step, call, aux0, aux1 and clears the segment data buffer (FX_fcn.cpp:212-225), and tb restores none of it. tb aligns strip.now; effects that advance via those accumulators instead are not phase-locked by it, and on a first sync of a mixed on/off fleet only the dark devices get reset — an asymmetry no shared tb can correct. FX.cpp has 194 strip.now references against 234 SEGENV.step/.call ones, so it is not a corner case. Suggest scoping the claim to what tb actually guarantees, e.g. "…so all devices agree on strip.now. Effects driven by strip.now therefore animate in step; those driven by SEGENV.step/call accumulators are not aligned by tb, and a device that was dark has those accumulators zeroed by toggleOnOff()→restartRuntime() in this same request."

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this open — it is a real finding and not something a doc edit should paper over. tb aligns strip.now, but restartRuntime() zeroes step/call/aux0/aux1 and tb restores none of it, so effects driven by those accumulators are not phase-locked. That is a design question for Adam (does the tool need to reset runtime state too, or is the claim simply narrowed?), and it also predicts the still-open 'sync is idempotent on a re-run' bench item without needing eyes on LEDs. Flagged to him rather than silently rewording the comment.

Comment thread tests/test_wled_sync.py Resolved
aphelps-claude-bot and others added 4 commits August 20, 2026 02:10
…main

Re-review mutation-tested this branch with 44 mutations: the pure layer held up
(31 of 33 went red) but ALL 11 mutations of the glue left the suite green —
including deleting the --speed/--intensity range check outright. That check is the
other half of c5a8b63 ("...and reject out-of-range speed") and it shipped with no
coverage at all, while b9d7e0a's README advertises its exit-2 behaviour to users.

TestArgRanges closes that one. It drives main() rather than calling the validator,
so deleting the CALL SITE fails too, not just gutting the function. Verified by
re-running the same mutation: 3 failures where the old suite gave 0.

It also asserts the boundaries are ACCEPTED. 0 is a legal value and it is falsy,
so a validator written as `if not val` would reject it — the half a one-sided test
would miss.

Every invocation is pinned with --host and --dry-run. Without that the tool sweeps
the whole subnet: the first run of these tests contacted all three real WLED
devices on the LAN and printed "would apply sx=999" against them. Dry-run meant
nothing changed, but a unit test has no business reaching the network at all.

README corrected, since the commit that set out to "describe the actual test
suite" replaced one wrong description with another:
  * the stub tables are SYNTHETIC, not "captured" — real names at the indices that
    matter, padded with ["RSVD"] * 138 and friends. That tests the property just as
    well, but calling it captured misleads anyone who goes looking for the capture.
  * "verify-after-apply catches a deliberately wrong application" overstated it: no
    stub serves /json/state, so verify_applied is exercised directly and the
    apply-then-verify path over HTTP is not. Now says so.
  * the range-check behaviour it advertises is now actually tested.

Makefile: fourth union resolution of the same two lines this session (test-hmtl,
test-readme, test-apjoin, test-sync). Both recipes and both prerequisite lists
kept; all four targets dry-run.

37 tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01F4oTr1YW3z7ozksMUT1z5j
Same correction as the README one, in the file it describes. "Real name tables,
trimmed" sends anyone chasing a discrepancy off to look for a capture that does
not exist; they are real names at the indices under test with repeated padding
between, which establishes the cross-version index property exactly as well.

Lengths stated so the next reader does not have to count: EFF_16 is 220, EFF_014
is 186.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01F4oTr1YW3z7ozksMUT1z5j
Two more of the re-review's confirmed-uncovered paths, each verified by re-running
the mutation that exposed it.

usermod palette end-to-end: resolve_palette's 255-j arithmetic was well unit-tested,
but nothing drove it through sync_one, so replacing dev.get("umpalnames") with None
left every test green. The new test stands up a stub advertising umpalnames and
asserts the wire body carries pal=255-j rather than a list index. Mutation
re-applied: now fails.

verify-after-apply wiring: verify_applied was covered directly, but the code that
CONSUMES its verdict was not — `problems = []` left the suite green. Now fails.

Worth recording precisely, because my first version of that test described a
mechanism it does not use: sync_one checks the POST *response* (wled_sync.py:361),
not a later GET of /json/state. I had added a /json/state fixture and written a
docstring claiming the stub "answers with a state that does not hold what was asked
for". The fixture was never read — the stub answers every POST with `{}`, and that
is what fails verification. The test was passing for a reason its own comment got
wrong, so the fixture is gone and the docstring now says what actually drives it.

39 tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01F4oTr1YW3z7ozksMUT1z5j
The last two confirmed-uncovered paths from the re-review. Both mutations
re-applied and both now fail, where the old suite gave 0 failures for each:

  timebase = make_timebase()          (drop the --no-phase conditional)  -> fails
  if False:                           (suppress the colour-moot warning) -> fails

--no-phase is asserted on the WIRE body, not the local variable: what matters is
that no tb reaches the device. It also asserts the other direction — that tb IS
sent without the flag — because a test checking only for absence would pass
against a build that never sends a timebase at all.

The colour-moot test likewise asserts a colour-DRIVEN palette does NOT warn.
A warning that fires on everything is one people learn to ignore, so the
suppression half is the half worth pinning.

41 tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01F4oTr1YW3z7ozksMUT1z5j
@aphelps-claude-bot
aphelps-claude-bot merged commit c64f35e into main Aug 22, 2026
1 check passed
@aphelps-claude-bot
aphelps-claude-bot deleted the wled-fleet-sync branch August 22, 2026 07:50
aphelps pushed a commit that referenced this pull request Aug 22, 2026
wled_sync landed on main (#31) while this branch was open, and both added
scripts/README.md and a test target. Resolved by keeping both rather than
picking a side:

- Makefile: `test` runs test-sync AND test-apjoin, both target bodies kept.
  This is the merge hot spot the Makefile task already describes.
- scripts/README.md: one intro covering both tools and the scan skill they
  bracket, each tool's section intact, and a Tests section split per tool so
  neither set of caveats is lost.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants