diff --git a/docs/external/nightdriver/666/REPORT.md b/docs/external/nightdriver/666/REPORT.md new file mode 100644 index 0000000..e052ae0 --- /dev/null +++ b/docs/external/nightdriver/666/REPORT.md @@ -0,0 +1,107 @@ +# NightDriverStrip issue 666: "Socket server: Unknown command in packet received: 31202" + +External proving-ground lane D1. Upstream project: PlummersSoftwareLLC/NightDriverStrip. +Nothing here has been sent upstream (tag `upstreamed` is not claimed anywhere below). + +**Outcome: B, already fixed upstream.** Reporter 1's error is a receiver framing bug (the receiver +did not consume the payload of a command it chose to ignore). It was fixed upstream in commit +`d73d18db` (2025-08-27) and is absent from pinned main `4d79c290`. Reporter 2's error is a +misconfigured client (a websocket aimed at the raw TCP port), not a bug. No code change is +proposed. The remaining value is the harness and the generic cases. + +Evidence tags: observed, reproduced, hypothesized, fixed, tested, upstreamed, accepted. + +## Observed + +Issue thread read in full (GitHub API; `gh issue view` fails here on a Projects-classic GraphQL error). Two reporters, treated separately. + +**Reporter 1, jmadotgg (2024-11-09): value 31202, running `samples/audioserver/audioserver.py` against the ledstrip demo.** +- [observed] The posted `LEDSTRIP` config has `ENABLE_AUDIO 0` (issue body). The sender is `audioserver.py`, which sends command 4 (PEAKDATA) with `num_bands` bands after each audio chunk and a 15 ms sleep (`samples/audioserver/audioserver.py:128-142` at `4d79c290`). The reporter's pasted copy has `num_bands = 12`; the repository copy has had `num_bands = 16` since commit `3146af92` (2023-02-24) and is unchanged between `15221f20` and `4d79c290`. So the reporter ran an edited or older copy. Why is unknown. +- [observed] 31202 = 0x79E2, so on a little-endian wire the two bytes are `E2 79`. The receiver reads `command16` as a little-endian u16 from buffer offset 0 (`WORDFromMemory`). +- [observed] In the reporter-era receiver (`src/socketserver.cpp` at `15221f20`, lines 132-169), the PEAKDATA branch with `ENABLE_AUDIO 0` compiles to nothing but `ResetReadBuffer()`. Only the 24-byte header was read from the socket; the declared 48-byte float payload stays in the stream. The next loop iteration reads 24 "header" bytes from that payload, so `command16` is the low 16 bits of `float[0]`. Anything other than 3 or 4 hits "Unknown command" (line 214), which closes the connection, matching "connection is closing and both sides keep retrying". +- [observed] The variant one commit earlier than the fix (`d73d18db~1`) gates on runtime `g_Analyzer.Enabled()` and has the same flaw (line 135). +- [observed] `d73d18db` adds the missing skip with the comment "Audio disabled: consume any declared payload to keep stream in sync, then ignore it". Pinned main has it at `src/socketserver.cpp:511-527`. +- [hypothesized] The exact value 31202 equals the low 16 bits of the reporter's first band value in their first frame. This is consistent with the mechanism but cannot be checked (many floats share those low bits and their audio is gone). The mechanism, not the number, is what is reproduced. +- [observed] Not the cause: the negative `micros` the reporter noticed (`time.perf_counter() - seconds`) is sent as a double and read as u64; it does not affect framing. +- [reproduced] On the main host build with `ENABLE_AUDIO 1`, the reporter's 12-band frames are rejected: the receiver logs "Invalid peak data packet: bands=12 length=48 total=72" and closes the connection. That is not an "Unknown command" and not a desync. At `4d79c290` `platformio.ini` sets `-DNUM_BANDS` to 16 in nine environments, 8, 48 and 64 in one each, and `globals.h` defaults to 16; no environment uses 12. So a 12-band sender cannot be accepted by any audio-enabled build of main. The repository copy of the script (16 bands) matches the common firmware value; harness case `peak16_with_pixels` shows 16-band frames are accepted with audio on. + +**Reporter 2, Cyborg-Squirrel (2025-07-05): value 17735, Kotlin client opening a WebSocket to port 49152.** +- [observed] 17735 = 0x4547; little-endian bytes `47 45` = ASCII "GE", the start of `GET /... HTTP/1.1`, the first bytes of a websocket upgrade request. +- [observed] Maintainer rbergen already said port 49152 is a raw TCP port that takes frame data only and that a websocket can only be opened against the web server on port 80, and only to read data from the device. +- [reproduced] Sending an HTTP GET to the real receiver code yields exactly "Unknown command in packet received: 17735" and a closed connection (case `http_get_on_raw_port`, all builds). +- Verdict: Outcome A (receiver correct, client misconfigured). The error text could say more (see Scope). + +## Reproduction + +What was built: the project's real `src/socketserver.cpp`, extracted unmodified with `git archive` at four SHAs, compiled on Linux (g++ 13, C++20) against stub platform headers (FreeRTOS task base, logging macros, PSRAM allocators, WiFi state, buffer manager, uzlib), driven over loopback TCP by a Rust harness. Stubs live in `harness/stubs/`; they are written for this harness and contain no project code. For the older snapshots, whose task loop lives in `src/network.cpp` (`SocketServerTaskEntry`, line 697 at `15221f20`), the host driver replicates that loop. Byte-reader helpers are stand-ins for the originals on those snapshots. + +Snapshots: +| label | SHA | what it is | +|---|---|---| +| s0 | `15221f20` | last socket-server change before the report | +| s1 | `d73d18db~1` | parent of the fix | +| s2 | `d73d18db` | the fix (2025-08-27) | +| main | `4d79c290` | pinned upstream main (2026-08-15) | + +Command (needs a NightDriverStrip clone; no project source is stored in this repo): + + ND_REPO=~/workspace/external/NightDriverStrip \ + docs/external/nightdriver/666/harness/run-matrix.sh > results.tsv + +Recorded run: `harness/results.tsv`. Summary of the property cases (PASS means the stream stayed aligned and every frame arrived byte-identical): + +| case | s0 | s1 | s2 | main | +|---|---|---|---|---| +| peak12_with_pixels (audioserver shape, float[0] low bits 0x79E2) | FAIL: Unknown command 31202 | FAIL: 31202 | PASS | PASS | +| peak16_with_pixels | FAIL: 31202 | FAIL: 31202 | PASS | PASS | +| whole frames, every split offset, coalescing, 1-byte writes | PASS | PASS | PASS | PASS | +| disconnect mid-header / mid-body then reconnect | PASS | PASS | PASS | PASS | +| unknown command then valid | PASS | PASS | PASS | PASS | +| max accepted, max+1 rejected, 0xFFFFFFFF rejected | PASS | PASS | PASS | PASS | +| slow sender inside / past the 3 s read timeout | PASS | PASS | PASS | PASS | +| HTTP GET on raw port gives 17735 | PASS | PASS | PASS | PASS | +| reconnect storm | PASS | PASS | PASS | PASS | + +Audio-on builds (`ENABLE_AUDIO=1`) of s2 and main: all property cases PASS. + +- [reproduced] Mechanism for reporter 1: the real receiver source at `15221f20` (a reporter-era snapshot; the reporter's exact firmware commit is unknown, so s0 and s1 are the two flawed endpoints we tested, not "their build"), fed `audioserver.py`-shaped frames, prints `Unknown command in packet received: 31202` when `float[0]` carries bits 0x????79E2. The test input was chosen to produce that value, so this reproduces the failure mode and its exact signature, not the reporter's audio. +- [tested] Red then green: the same peak cases fail on s0 and s1 and pass on s2 and main. This is the negative control for the harness. +- [reproduced] Reporter 2's 17735 from an HTTP request line. + +Limits, stated precisely: the s1 snapshot gates on runtime `g_Analyzer.Enabled()`; the host stub models it as the compile-time `ENABLE_AUDIO` value. That is a modelling assumption. [hypothesized, untested] A real build with audio compiled in but no microphone could return false at run time and desync the same way, which would also explain reporter 1 if they had flashed audio on. this is the real socket-server source, not a replica of its parsing, but it runs on Linux loopback TCP with `SO_RCVTIMEO`, not lwIP on an ESP32. Nothing here was run on a physical ESP32 and nothing is claimed about lwIP buffering, task scheduling, or PSRAM behaviour. A device test would need an ESP32 board flashed with the ledstrip demo from a pre-`d73d18db` checkout (and one from main), plus `audioserver.py` pointed at it with a serial monitor to read the log. + +## Root Cause + +[reproduced] for reporter 1, on the reporter-era source: a command that the firmware decides to ignore (PEAKDATA with audio disabled) was not drained from the TCP stream. The receiver parsed payload bytes as the next header. [observed] Fixed by `d73d18db`. + +Reporter 2: no receiver defect. [observed] misdirected client. + +## Fix + +[fixed] upstream by `d73d18db` (not by us): when audio is disabled, read `STANDARD_DATA_HEADER_SIZE + length32` bytes and discard them before resetting the buffer. [tested] on main by the harness above (both audio settings). Upstream main also validates the length with `CheckedStandardPacketSize` before reading (`src/socketserver.cpp:511-527`). + +No fork branch and no pull request: there is no remaining defect on main to fix. The 12 vs `NUM_BANDS` mismatch is in the reporter's pasted script, not in the repository sample (see Observed). + +## Regression + +[tested] Cases `peak12_with_pixels` and `peak16_with_pixels` fail on the pre-fix snapshots and pass on the fix and on main. Upstream has no automated test environment for the firmware: `platformio.ini` has no test environment, and the only tests in the tree are Python tooling tests (`tools/test_build_tools.py`, `tools/test_topology.py`). So no in-repo test is proposed; the harness stays on our side. + +## Scope (not changed) + +- No upstream pull request, issue comment or reaction. A suggested close-out comment is in `upstream-comment-draft.md` for the owner to post or discard. +- Nothing about the wire format, audioserver.py, or the socket server was modified. No fork branch or sample change is proposed: the repository sample already uses 16 bands, which matches the firmware default; the 12 in the report came from the reporter's copy. +- [hypothesized, not run] On a 32-bit target the older size computation `STANDARD_DATA_HEADER_SIZE + length32 * LED_DATA_SIZE` can wrap (for example `length32 = 0x55555556`), so a hostile or corrupt header could be accepted with a tiny length. The host harness is 64-bit and cannot show this. Main uses an overflow-checked helper, so it looks handled; unverified on a 32-bit build. +- [observed] Older firmware (s0) sleeps 100 ms after every frame (`delay(100)` at `15221f20` line 247), so it consumes about 10 frames per second; later snapshots sleep 1 ms. `audioserver.py` reads 512 samples at 44.1 kHz (about 11.6 ms) and sleeps 15 ms per loop, so it sends very roughly 35 to 40 frames per second [hypothesized by arithmetic, not measured]; against s0 the sender would outpace the receiver and TCP backpressure would absorb it. Not a framing issue. +- [observed, INFO cases] zero-LED pixel frame is passed to the consumer with length 24. A client that never reads the 72-byte responses is still served on the host (about 1.3k of 4k frames consumed in 1.5 s, limited by the 1 ms per-frame sleep, no stall seen). Sender prefix-then-drop faults (`sender_short_write`) surface as one corrupted-but-well-formed packet then an Unknown command or garbage value, on every build; a framed stream cannot detect that. +- Sender-side Outcome C (Python `send()` short write): [observed] on Linux, CPython 3.12.3, 1342 blocking `send()` calls of a 72-byte frame under receiver backpressure returned 72 every time (scratch script, not kept in the repo). Not supported as a cause of reporter 1; it is not excluded on other platforms. +- Optional upstream polish (not proposed): the "Unknown command" message could also print the first two raw bytes as hex, and the docs could say port 49152 is raw TCP only. Either would have shortened both reporters' debugging. + +## INTERPLANE Lesson + +- [observed] Decode a single rejected value before anything else: little-endian bytes, compare with ASCII and with every offset of a valid frame. Both reporters were solved by that arithmetic (0x4547 is "GE"; 0x79E2 is payload bytes). +- [observed] The dangerous bug class is not parsing, it is a disabled or ignored path that changes how many bytes get consumed. A transport conformance suite should run every command in enabled and disabled form and require the same stream alignment (cases T-ALIGN-1, T-ALIGN-2 in `transport-cases.md`). +- [tested] Segmentation, coalescing, mid-frame disconnect, timeout and oversize cases all passed on the real receiver even on the buggy snapshots; the one failure was caught only by interleaving an ignored command with valid ones. Interleaved-sequence cases belong in the Runner conformance set next to the split/coalesce cases. +- Error messages for rejected frames should include the raw first bytes. That alone identifies foreign traffic. +- Method: compiling a project's real source unmodified against a small stub platform layer gave reproduction evidence without hardware, and the pre-fix/post-fix commit pair gave the negative control for free. + +Generic case list: `transport-cases.md`. Harness: `harness/` (`host/` C++ driver and build script, `stubs/` platform stubs, `torture/` Rust test driver, `run-matrix.sh`, `results.tsv`). diff --git a/docs/external/nightdriver/666/harness/host/build.sh b/docs/external/nightdriver/666/harness/host/build.sh new file mode 100755 index 0000000..7bf2209 --- /dev/null +++ b/docs/external/nightdriver/666/harness/host/build.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# Usage: build.sh [extra g++ flags, e.g. -DENABLE_AUDIO=1] +# variant: modern | legacy +# source-dir: an UNMODIFIED NightDriverStrip tree at the SHA under test (needs include/ and src/socketserver.cpp) +# Platform headers are shadowed by stubs in an overlay copy of include/; socketserver.cpp is compiled from source-dir as-is. +set -e +H=$(cd "$(dirname "$0")/.." && pwd) +V=$1; SRC=$2; OUT=$3; shift 3 +OV=$(mktemp -d) +cp -r "$SRC/include" "$OV/include" +cp -r "$H/stubs/$V/." "$OV/include/" +g++ -std=gnu++20 -O1 -g -w "$@" -I"$OV/include" \ + "$SRC/src/socketserver.cpp" "$H/host/ndhost_$V.cpp" -o "$OUT" -lpthread +rm -rf "$OV" diff --git a/docs/external/nightdriver/666/harness/host/ndhost_legacy.cpp b/docs/external/nightdriver/666/harness/host/ndhost_legacy.cpp new file mode 100644 index 0000000..1b908a7 --- /dev/null +++ b/docs/external/nightdriver/666/harness/host/ndhost_legacy.cpp @@ -0,0 +1,69 @@ +// Host driver: runs the real SocketServer::Run() on Linux loopback. Written for this harness. +// Every line on stdout is machine-parsed by the Rust harness: +// LOG firmware debug output +// PKT cmd= len= fnv= a packet handed to ProcessIncomingData +#include "globals.h" +#include "socketserver.h" +#include "values.h" +#include "systemcontainer.h" +#include "soundanalyzer.h" +#include "nd_network.h" +#include +#include +#include +#include + +int g_debugLevel = 1; +HostValues g_Values; HostAnalyzer g_Analyzer; HostWiFi WiFi; +HostSystem g_hostSystem; +HostSystem* g_ptrSystem = &g_hostSystem; +std::mutex g_buffer_mutex; + +void host_log(int level, const char* tag, const char* fmt, ...) +{ + if (level > g_debugLevel) return; + char buf[512]; + va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); + size_t n = strlen(buf); while (n && (buf[n-1] == '\n')) buf[--n] = 0; + printf("LOG %s %s\n", tag, buf); +} + +namespace nd_network { +bool IsWiFiConnected() { return true; } +void SetSocketBlockingEnabled(int fd, bool blocking) +{ + int fl = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, blocking ? (fl & ~O_NONBLOCK) : (fl | O_NONBLOCK)); +} +int GetWiFiRSSI() { return -50; } +} + +extern "C" { +void uzlib_uncompress_init(struct uzlib_uncomp*, void*, unsigned) {} +int uzlib_zlib_parse_header(struct uzlib_uncomp*) { return -1; } // compressed path not exercised +int uzlib_uncompress_chksum(struct uzlib_uncomp*) { return -1; } +} + +bool ProcessIncomingData(std::unique_ptr& p, size_t len) +{ + uint32_t h = 2166136261u; + for (size_t i = 0; i < len; i++) { h ^= p[i]; h *= 16777619u; } + uint16_t cmd = p[0] | (p[1] << 8); + printf("PKT cmd=%u len=%zu fnv=%08x\n", cmd, len, h); + return true; +} + +struct HostServer : SocketServer +{ + using SocketServer::SocketServer; +}; + +int main(int argc, char** argv) +{ + if (argc < 2) { fprintf(stderr, "usage: ndhost [debug-level]\n"); return 2; } + if (argc > 2) g_debugLevel = atoi(argv[2]); + setvbuf(stdout, nullptr, _IOLBF, 0); + HostServer s(atoi(argv[1]), NUM_LEDS); + for (;;) { s.release(); if (s.begin()) { host_log(1, "I", "Socket server listening on port %s", argv[1]); s.ProcessIncomingConnectionsLoop(); host_log(1, "W", "Socket connection closed. Retrying..."); } delay(500); } // same shape as the firmware task entry + return 0; +} diff --git a/docs/external/nightdriver/666/harness/host/ndhost_modern.cpp b/docs/external/nightdriver/666/harness/host/ndhost_modern.cpp new file mode 100644 index 0000000..83ccbd8 --- /dev/null +++ b/docs/external/nightdriver/666/harness/host/ndhost_modern.cpp @@ -0,0 +1,69 @@ +// Host driver: runs the real SocketServer::Run() on Linux loopback. Written for this harness. +// Every line on stdout is machine-parsed by the Rust harness: +// LOG firmware debug output +// PKT cmd= len= fnv= a packet handed to ProcessIncomingData +#include "globals.h" +#include "socketserver.h" +#include "values.h" +#include "systemcontainer.h" +#include "nd_network.h" +#include +#include +#include +#include + +int g_debugLevel = 1; +HostValues g_Values; +HostSystem g_hostSystem; +HostSystem* g_ptrSystem = &g_hostSystem; +std::mutex g_buffer_mutex; + +void host_log(int level, const char* tag, const char* fmt, ...) +{ + if (level > g_debugLevel) return; + char buf[512]; + va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); + size_t n = strlen(buf); while (n && (buf[n-1] == '\n')) buf[--n] = 0; + printf("LOG %s %s\n", tag, buf); +} + +namespace nd_network { +bool IsWiFiConnected() { return true; } +void SetSocketBlockingEnabled(int fd, bool blocking) +{ + int fl = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, blocking ? (fl & ~O_NONBLOCK) : (fl | O_NONBLOCK)); +} +int GetWiFiRSSI() { return -50; } +} + +extern "C" { +void uzlib_uncompress_init(struct uzlib_uncomp*, void*, unsigned) {} +int uzlib_zlib_parse_header(struct uzlib_uncomp*) { return -1; } // compressed path not exercised +int uzlib_uncompress_chksum(struct uzlib_uncomp*) { return -1; } +} + +bool ProcessIncomingData(allocated_unique_ptr& p, size_t len) +{ + uint32_t h = 2166136261u; + for (size_t i = 0; i < len; i++) { h ^= p[i]; h *= 16777619u; } + uint16_t cmd = p[0] | (p[1] << 8); + printf("PKT cmd=%u len=%zu fnv=%08x\n", cmd, len, h); + return true; +} + +struct HostServer : SocketServer +{ + using SocketServer::SocketServer; + using SocketServer::Run; +}; + +int main(int argc, char** argv) +{ + if (argc < 2) { fprintf(stderr, "usage: ndhost [debug-level]\n"); return 2; } + if (argc > 2) g_debugLevel = atoi(argv[2]); + setvbuf(stdout, nullptr, _IOLBF, 0); + HostServer s(atoi(argv[1]), NUM_LEDS); + s.Run(); // the real accept/read/dispatch loop; runs until the harness kills this process + return 0; +} diff --git a/docs/external/nightdriver/666/harness/results.tsv b/docs/external/nightdriver/666/harness/results.tsv new file mode 100644 index 0000000..003d55f --- /dev/null +++ b/docs/external/nightdriver/666/harness/results.tsv @@ -0,0 +1,108 @@ +s0_audio0 whole_frames PASS 3 packets, all matched +s0_audio0 split_every_offset PASS 53 packets, all matched +s0_audio0 coalesced PASS 5 packets, all matched +s0_audio0 one_byte_writes PASS 2 packets, all matched +s0_audio0 peak12_with_pixels FAIL receiver lost frame alignment: Unknown command [31202]; packets [] +s0_audio0 peak16_with_pixels FAIL want 2 packets got 0; unknown-command [31202] +s0_audio0 http_get_on_raw_port PASS rejected with Unknown command 17735 (= 0x4547, bytes 'G','E'), connection closed +s0_audio0 disconnect_partial_then_valid PASS 1 packets, all matched +s0_audio0 malformed_then_valid PASS bad command rejected (30583), next connection clean +s0_audio0 max_and_oversize PASS max frame accepted, max+1 rejected and connection closed, next clean +s0_audio0 huge_length PASS length32=0xFFFFFFFF rejected on this 64-bit host +s0_audio0 zero_length INFO zero-LED pixel frame: packets=[24] response=true unknown=[] +s0_audio0 slow_sender_within_timeout PASS 1 packets, all matched +s0_audio0 slow_sender_past_timeout PASS stalled partial frame timed out and was discarded; next connection clean +s0_audio0 slow_receiver INFO sent 4000 frames without reading responses; receiver consumed 15; unknown=[] +s0_audio0 sender_short_write INFO k=12: packets=1 intact=0 unknown=[34688] | k=24: packets=1 intact=0 unknown=[13100] | k=40: packets=1 intact=0 unknown=[0] +s0_audio0 reconnect_storm PASS 5 packets, all matched +s0_audio0 SUMMARY fails=2 +s1_audio0 whole_frames PASS 3 packets, all matched +s1_audio0 split_every_offset PASS 53 packets, all matched +s1_audio0 coalesced PASS 5 packets, all matched +s1_audio0 one_byte_writes PASS 2 packets, all matched +s1_audio0 peak12_with_pixels FAIL receiver lost frame alignment: Unknown command [31202]; packets [] +s1_audio0 peak16_with_pixels FAIL want 2 packets got 0; unknown-command [31202] +s1_audio0 http_get_on_raw_port PASS rejected with Unknown command 17735 (= 0x4547, bytes 'G','E'), connection closed +s1_audio0 disconnect_partial_then_valid PASS 1 packets, all matched +s1_audio0 malformed_then_valid PASS bad command rejected (30583), next connection clean +s1_audio0 max_and_oversize PASS max frame accepted, max+1 rejected and connection closed, next clean +s1_audio0 huge_length PASS length32=0xFFFFFFFF rejected on this 64-bit host +s1_audio0 zero_length INFO zero-LED pixel frame: packets=[24] response=true unknown=[] +s1_audio0 slow_sender_within_timeout PASS 1 packets, all matched +s1_audio0 slow_sender_past_timeout PASS stalled partial frame timed out and was discarded; next connection clean +s1_audio0 slow_receiver INFO sent 4000 frames without reading responses; receiver consumed 1423; unknown=[] +s1_audio0 sender_short_write INFO k=12: packets=1 intact=0 unknown=[34688] | k=24: packets=1 intact=0 unknown=[13100] | k=40: packets=1 intact=0 unknown=[0] +s1_audio0 reconnect_storm PASS 5 packets, all matched +s1_audio0 SUMMARY fails=2 +s2_audio0 whole_frames PASS 3 packets, all matched +s2_audio0 split_every_offset PASS 53 packets, all matched +s2_audio0 coalesced PASS 5 packets, all matched +s2_audio0 one_byte_writes PASS 2 packets, all matched +s2_audio0 peak12_with_pixels PASS no desync; audio=0 packets seen: [(3, 54), (3, 54)] +s2_audio0 peak16_with_pixels PASS audio=0 sequence consumed in order, 2 packets +s2_audio0 http_get_on_raw_port PASS rejected with Unknown command 17735 (= 0x4547, bytes 'G','E'), connection closed +s2_audio0 disconnect_partial_then_valid PASS 1 packets, all matched +s2_audio0 malformed_then_valid PASS bad command rejected (30583), next connection clean +s2_audio0 max_and_oversize PASS max frame accepted, max+1 rejected and connection closed, next clean +s2_audio0 huge_length PASS length32=0xFFFFFFFF rejected on this 64-bit host +s2_audio0 zero_length INFO zero-LED pixel frame: packets=[24] response=true unknown=[] +s2_audio0 slow_sender_within_timeout PASS 1 packets, all matched +s2_audio0 slow_sender_past_timeout PASS stalled partial frame timed out and was discarded; next connection clean +s2_audio0 slow_receiver INFO sent 4000 frames without reading responses; receiver consumed 1419; unknown=[] +s2_audio0 sender_short_write INFO k=12: packets=1 intact=0 unknown=[34688] | k=24: packets=1 intact=0 unknown=[13100] | k=40: packets=1 intact=0 unknown=[0] +s2_audio0 reconnect_storm PASS 5 packets, all matched +s2_audio0 SUMMARY fails=0 +s2_audio1 whole_frames PASS 3 packets, all matched +s2_audio1 split_every_offset PASS 53 packets, all matched +s2_audio1 coalesced PASS 5 packets, all matched +s2_audio1 one_byte_writes PASS 2 packets, all matched +s2_audio1 peak12_with_pixels PASS no desync; audio=1 packets seen: [] +s2_audio1 peak16_with_pixels PASS audio=1 sequence consumed in order, 4 packets +s2_audio1 http_get_on_raw_port PASS rejected with Unknown command 17735 (= 0x4547, bytes 'G','E'), connection closed +s2_audio1 disconnect_partial_then_valid PASS 1 packets, all matched +s2_audio1 malformed_then_valid PASS bad command rejected (30583), next connection clean +s2_audio1 max_and_oversize PASS max frame accepted, max+1 rejected and connection closed, next clean +s2_audio1 huge_length PASS length32=0xFFFFFFFF rejected on this 64-bit host +s2_audio1 zero_length INFO zero-LED pixel frame: packets=[24] response=true unknown=[] +s2_audio1 slow_sender_within_timeout PASS 1 packets, all matched +s2_audio1 slow_sender_past_timeout PASS stalled partial frame timed out and was discarded; next connection clean +s2_audio1 slow_receiver INFO sent 4000 frames without reading responses; receiver consumed 1418; unknown=[] +s2_audio1 sender_short_write INFO k=12: packets=1 intact=0 unknown=[34688] | k=24: packets=1 intact=0 unknown=[13100] | k=40: packets=1 intact=0 unknown=[0] +s2_audio1 reconnect_storm PASS 5 packets, all matched +s2_audio1 SUMMARY fails=0 +main_audio0 whole_frames PASS 3 packets, all matched +main_audio0 split_every_offset PASS 53 packets, all matched +main_audio0 coalesced PASS 5 packets, all matched +main_audio0 one_byte_writes PASS 2 packets, all matched +main_audio0 peak12_with_pixels PASS no desync; audio=0 packets seen: [(3, 54), (3, 54)] +main_audio0 peak16_with_pixels PASS audio=0 sequence consumed in order, 2 packets +main_audio0 http_get_on_raw_port PASS rejected with Unknown command 17735 (= 0x4547, bytes 'G','E'), connection closed +main_audio0 disconnect_partial_then_valid PASS 1 packets, all matched +main_audio0 malformed_then_valid PASS bad command rejected (30583), next connection clean +main_audio0 max_and_oversize PASS max frame accepted, max+1 rejected and connection closed, next clean +main_audio0 huge_length PASS length32=0xFFFFFFFF rejected on this 64-bit host +main_audio0 zero_length INFO zero-LED pixel frame: packets=[24] response=true unknown=[] +main_audio0 slow_sender_within_timeout PASS 1 packets, all matched +main_audio0 slow_sender_past_timeout PASS stalled partial frame timed out and was discarded; next connection clean +main_audio0 slow_receiver INFO sent 4000 frames without reading responses; receiver consumed 1335; unknown=[] +main_audio0 sender_short_write INFO k=12: packets=1 intact=0 unknown=[34688] | k=24: packets=1 intact=0 unknown=[13100] | k=40: packets=1 intact=0 unknown=[0] +main_audio0 reconnect_storm PASS 5 packets, all matched +main_audio0 SUMMARY fails=0 +main_audio1 whole_frames PASS 3 packets, all matched +main_audio1 split_every_offset PASS 53 packets, all matched +main_audio1 coalesced PASS 5 packets, all matched +main_audio1 one_byte_writes PASS 2 packets, all matched +main_audio1 peak12_with_pixels PASS no desync; audio=1 packets seen: [] +main_audio1 peak16_with_pixels PASS audio=1 sequence consumed in order, 4 packets +main_audio1 http_get_on_raw_port PASS rejected with Unknown command 17735 (= 0x4547, bytes 'G','E'), connection closed +main_audio1 disconnect_partial_then_valid PASS 1 packets, all matched +main_audio1 malformed_then_valid PASS bad command rejected (30583), next connection clean +main_audio1 max_and_oversize PASS max frame accepted, max+1 rejected and connection closed, next clean +main_audio1 huge_length PASS length32=0xFFFFFFFF rejected on this 64-bit host +main_audio1 zero_length INFO zero-LED pixel frame: packets=[24] response=true unknown=[] +main_audio1 slow_sender_within_timeout PASS 1 packets, all matched +main_audio1 slow_sender_past_timeout PASS stalled partial frame timed out and was discarded; next connection clean +main_audio1 slow_receiver INFO sent 4000 frames without reading responses; receiver consumed 1337; unknown=[] +main_audio1 sender_short_write INFO k=12: packets=1 intact=0 unknown=[34688] | k=24: packets=1 intact=0 unknown=[13100] | k=40: packets=1 intact=0 unknown=[0] +main_audio1 reconnect_storm PASS 5 packets, all matched +main_audio1 SUMMARY fails=0 diff --git a/docs/external/nightdriver/666/harness/run-matrix.sh b/docs/external/nightdriver/666/harness/run-matrix.sh new file mode 100755 index 0000000..16906d0 --- /dev/null +++ b/docs/external/nightdriver/666/harness/run-matrix.sh @@ -0,0 +1,29 @@ +#!/bin/sh +# Reproduce the NightDriver 666 matrix. Needs: git, g++ (C++20), cargo, and a clone of +# https://github.com/PlummersSoftwareLLC/NightDriverStrip (set ND_REPO). No NightDriver source is stored in this repo: +# each snapshot is extracted unmodified with `git archive` at the SHA under test. +# +# ND_REPO=~/workspace/external/NightDriverStrip ./run-matrix.sh > results.tsv +set -e +H=$(cd "$(dirname "$0")" && pwd) +: "${ND_REPO:?set ND_REPO to a NightDriverStrip clone}" +W=$(mktemp -d) +(cd "$H/torture" && cargo build --release -q) +T="$H/torture/target/release/nd666-torture" + +# label variant sha audio (variant: which stub set matches that snapshot's platform API) +# s0 = 15221f20 last socket-server commit before the issue was filed (2024-11-09) +# s1 = parent of the fix commit, s2 = the fix commit d73d18db (2025-08-27), main = pinned upstream main +while read -r label variant sha audio; do + git -C "$ND_REPO" archive "$sha" include src/socketserver.cpp | (mkdir -p "$W/$label" && tar -x -C "$W/$label") + "$H/host/build.sh" "$variant" "$W/$label" "$W/$label.bin" -DENABLE_AUDIO="$audio" + "$T" "$W/$label.bin" --label "${label}_audio${audio}" --audio "$audio" +done < +#include +#include +#include +#include +#include +#include + +#ifndef ENABLE_AUDIO +#define ENABLE_AUDIO 0 +#endif +#define INCOMING_WIFI_ENABLED 1 +#define USE_PSRAM 0 +#ifndef NUM_LEDS +#define NUM_LEDS 144 +#endif +#define NUM_BANDS 16 +#define FLASH_VERSION 1 +#define WIFI_COMMAND_PIXELDATA64 3 +#define WIFI_COMMAND_PEAKDATA 4 + +struct CRGB { uint8_t r, g, b; }; + +template using allocated_unique_ptr = std::unique_ptr; +template std::unique_ptr make_unique_psram(size_t n) { return std::unique_ptr(new typename std::remove_extent::type[n]()); } +template std::unique_ptr make_unique_internal(size_t n) { return make_unique_psram(n); } + +extern int g_debugLevel; // 0 quiet, 1 errors, 2 verbose +void host_log(int level, const char* tag, const char* fmt, ...) __attribute__((format(printf, 3, 4))); +#define debugV(...) host_log(2, "V", __VA_ARGS__) +#define debugI(...) host_log(1, "I", __VA_ARGS__) +#define debugW(...) host_log(1, "W", __VA_ARGS__) +#define debugE(...) host_log(1, "E", __VA_ARGS__) +inline void delay(unsigned ms) { usleep(ms * 1000u); } +struct HostWiFi { int RSSI() const { return -50; } }; +extern HostWiFi WiFi; +#include +#include +// Little-endian host (and the ESP32) read helpers; stand-ins for the ones in the real globals.h. +inline uint16_t WORDFromMemory(const uint8_t* p) { uint16_t v; std::memcpy(&v, p, sizeof v); return v; } +inline uint32_t DWORDFromMemory(const uint8_t* p) { uint32_t v; std::memcpy(&v, p, sizeof v); return v; } +inline uint64_t ULONGFromMemory(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, sizeof v); return v; } +// Allocator stand-in: memory comes from new[] so unique_ptr::reset(ptr) can delete[] it. +template struct psram_allocator { T* allocate(size_t n) { return new T[n](); } }; diff --git a/docs/external/nightdriver/666/harness/stubs/legacy/ledbuffer.h b/docs/external/nightdriver/666/harness/stubs/legacy/ledbuffer.h new file mode 100644 index 0000000..fcf19c4 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/legacy/ledbuffer.h @@ -0,0 +1,2 @@ +#pragma once +#include "globals.h" diff --git a/docs/external/nightdriver/666/harness/stubs/legacy/nd_network.h b/docs/external/nightdriver/666/harness/stubs/legacy/nd_network.h new file mode 100644 index 0000000..94f5150 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/legacy/nd_network.h @@ -0,0 +1,3 @@ +#pragma once +#include "globals.h" +namespace nd_network { bool IsWiFiConnected(); void SetSocketBlockingEnabled(int fd, bool blocking); int GetWiFiRSSI(); } diff --git a/docs/external/nightdriver/666/harness/stubs/legacy/soundanalyzer.h b/docs/external/nightdriver/666/harness/stubs/legacy/soundanalyzer.h new file mode 100644 index 0000000..dc93645 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/legacy/soundanalyzer.h @@ -0,0 +1,4 @@ +#pragma once +#include "globals.h" +struct HostAnalyzer { bool Enabled() const { return ENABLE_AUDIO != 0; } }; +extern HostAnalyzer g_Analyzer; diff --git a/docs/external/nightdriver/666/harness/stubs/legacy/systemcontainer.h b/docs/external/nightdriver/666/harness/stubs/legacy/systemcontainer.h new file mode 100644 index 0000000..505ec4e --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/legacy/systemcontainer.h @@ -0,0 +1,8 @@ +#pragma once +#include "globals.h" +#include "values.h" +struct HostBufferManager { double AgeOfOldestBuffer() { return 0; } double AgeOfNewestBuffer() { return 0; } uint32_t BufferCount() { return 0; } uint32_t Depth() { return 0; } }; +struct HostSystem { HostBufferManager* BufferManagers() { static HostBufferManager b[1]; return b; } }; +extern HostSystem* g_ptrSystem; +extern std::mutex g_buffer_mutex; +#include "socketserver.h" diff --git a/docs/external/nightdriver/666/harness/stubs/legacy/uzlib/src/uzlib.h b/docs/external/nightdriver/666/harness/stubs/legacy/uzlib/src/uzlib.h new file mode 100644 index 0000000..c5007e3 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/legacy/uzlib/src/uzlib.h @@ -0,0 +1,8 @@ +// Host stub: decompression is not exercised by the framing cases; any compressed packet is rejected by the stub. +#pragma once +#include +#define TINF_DONE 1 +struct uzlib_uncomp { const unsigned char* source; const unsigned char* source_limit; int (*source_read_cb)(struct uzlib_uncomp*); unsigned char* dest_start; unsigned char* dest; unsigned char* dest_limit; }; +void uzlib_uncompress_init(struct uzlib_uncomp*, void*, unsigned); +int uzlib_zlib_parse_header(struct uzlib_uncomp*); +int uzlib_uncompress_chksum(struct uzlib_uncomp*); diff --git a/docs/external/nightdriver/666/harness/stubs/legacy/values.h b/docs/external/nightdriver/666/harness/stubs/legacy/values.h new file mode 100644 index 0000000..a0b3ff7 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/legacy/values.h @@ -0,0 +1,4 @@ +#pragma once +#include "globals.h" +struct HostValues { struct { double CurrentTime() const { return 0; } } AppTime; double Brite = 0; double FPS = 0; double Watts = 0; }; +extern HostValues g_Values; diff --git a/docs/external/nightdriver/666/harness/stubs/modern/globals.h b/docs/external/nightdriver/666/harness/stubs/modern/globals.h new file mode 100644 index 0000000..b68f514 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/modern/globals.h @@ -0,0 +1,37 @@ +// Host stub for the platform layer. Written for this harness; not NightDriverStrip code. +// Provides only what src/socketserver.cpp and include/socketserver.h need from "globals.h". +#pragma once +#include +#include +#include +#include +#include +#include +#include + +#ifndef ENABLE_AUDIO +#define ENABLE_AUDIO 0 +#endif +#define INCOMING_WIFI_ENABLED 1 +#define USE_PSRAM 0 +#ifndef NUM_LEDS +#define NUM_LEDS 144 +#endif +#define NUM_BANDS 16 +#define FLASH_VERSION 1 +#define WIFI_COMMAND_PIXELDATA64 3 +#define WIFI_COMMAND_PEAKDATA 4 + +struct CRGB { uint8_t r, g, b; }; + +template using allocated_unique_ptr = std::unique_ptr; +template std::unique_ptr make_unique_psram(size_t n) { return std::unique_ptr(new typename std::remove_extent::type[n]()); } +template std::unique_ptr make_unique_internal(size_t n) { return make_unique_psram(n); } + +extern int g_debugLevel; // 0 quiet, 1 errors, 2 verbose +void host_log(int level, const char* tag, const char* fmt, ...) __attribute__((format(printf, 3, 4))); +#define debugV(...) host_log(2, "V", __VA_ARGS__) +#define debugI(...) host_log(1, "I", __VA_ARGS__) +#define debugW(...) host_log(1, "W", __VA_ARGS__) +#define debugE(...) host_log(1, "E", __VA_ARGS__) +inline void delay(unsigned ms) { usleep(ms * 1000u); } diff --git a/docs/external/nightdriver/666/harness/stubs/modern/itaskservice.h b/docs/external/nightdriver/666/harness/stubs/modern/itaskservice.h new file mode 100644 index 0000000..2c846e0 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/modern/itaskservice.h @@ -0,0 +1,18 @@ +// Host stub: minimal ITaskService surface used by SocketServer. Not NightDriverStrip code. +#pragma once +#include "globals.h" +#include +struct IService { virtual ~IService() = default; virtual const char* Name() const = 0; }; +class ITaskService : public IService +{ + public: + bool Start() { return true; } + void Stop() { _shutdownRequested = true; } + protected: + struct TaskConfig { const char* taskName; size_t stackSize; int priority; int core; uint32_t shutdownTimeoutMs; }; + virtual TaskConfig GetTaskConfig() const = 0; + virtual void Run() = 0; + virtual void OnBeforeWaitForStop() {} + bool ShouldShutdown() const { return _shutdownRequested.load(); } + std::atomic _shutdownRequested{false}; +}; diff --git a/docs/external/nightdriver/666/harness/stubs/modern/ledbuffer.h b/docs/external/nightdriver/666/harness/stubs/modern/ledbuffer.h new file mode 100644 index 0000000..fcf19c4 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/modern/ledbuffer.h @@ -0,0 +1,2 @@ +#pragma once +#include "globals.h" diff --git a/docs/external/nightdriver/666/harness/stubs/modern/nd_network.h b/docs/external/nightdriver/666/harness/stubs/modern/nd_network.h new file mode 100644 index 0000000..94f5150 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/modern/nd_network.h @@ -0,0 +1,3 @@ +#pragma once +#include "globals.h" +namespace nd_network { bool IsWiFiConnected(); void SetSocketBlockingEnabled(int fd, bool blocking); int GetWiFiRSSI(); } diff --git a/docs/external/nightdriver/666/harness/stubs/modern/soundanalyzer.h b/docs/external/nightdriver/666/harness/stubs/modern/soundanalyzer.h new file mode 100644 index 0000000..fcf19c4 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/modern/soundanalyzer.h @@ -0,0 +1,2 @@ +#pragma once +#include "globals.h" diff --git a/docs/external/nightdriver/666/harness/stubs/modern/systemcontainer.h b/docs/external/nightdriver/666/harness/stubs/modern/systemcontainer.h new file mode 100644 index 0000000..46c5653 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/modern/systemcontainer.h @@ -0,0 +1,6 @@ +#pragma once +#include "globals.h" +struct HostBufferManager { double AgeOfOldestBuffer() { return 0; } double AgeOfNewestBuffer() { return 0; } uint32_t BufferCount() { return 0; } uint32_t Depth() { return 0; } }; +struct HostSystem { HostBufferManager* GetBufferManagers() { static HostBufferManager b[1]; return b; } }; +extern HostSystem* g_ptrSystem; +extern std::mutex g_buffer_mutex; diff --git a/docs/external/nightdriver/666/harness/stubs/modern/taskmgr.h b/docs/external/nightdriver/666/harness/stubs/modern/taskmgr.h new file mode 100644 index 0000000..1b9a511 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/modern/taskmgr.h @@ -0,0 +1,5 @@ +#pragma once +#include "globals.h" +#define SOCKET_STACK_SIZE 0 +#define SOCKET_PRIORITY 0 +#define SOCKET_CORE 0 diff --git a/docs/external/nightdriver/666/harness/stubs/modern/uzlib/src/uzlib.h b/docs/external/nightdriver/666/harness/stubs/modern/uzlib/src/uzlib.h new file mode 100644 index 0000000..c5007e3 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/modern/uzlib/src/uzlib.h @@ -0,0 +1,8 @@ +// Host stub: decompression is not exercised by the framing cases; any compressed packet is rejected by the stub. +#pragma once +#include +#define TINF_DONE 1 +struct uzlib_uncomp { const unsigned char* source; const unsigned char* source_limit; int (*source_read_cb)(struct uzlib_uncomp*); unsigned char* dest_start; unsigned char* dest; unsigned char* dest_limit; }; +void uzlib_uncompress_init(struct uzlib_uncomp*, void*, unsigned); +int uzlib_zlib_parse_header(struct uzlib_uncomp*); +int uzlib_uncompress_chksum(struct uzlib_uncomp*); diff --git a/docs/external/nightdriver/666/harness/stubs/modern/values.h b/docs/external/nightdriver/666/harness/stubs/modern/values.h new file mode 100644 index 0000000..a0b3ff7 --- /dev/null +++ b/docs/external/nightdriver/666/harness/stubs/modern/values.h @@ -0,0 +1,4 @@ +#pragma once +#include "globals.h" +struct HostValues { struct { double CurrentTime() const { return 0; } } AppTime; double Brite = 0; double FPS = 0; double Watts = 0; }; +extern HostValues g_Values; diff --git a/docs/external/nightdriver/666/harness/torture/Cargo.lock b/docs/external/nightdriver/666/harness/torture/Cargo.lock new file mode 100644 index 0000000..4c14661 --- /dev/null +++ b/docs/external/nightdriver/666/harness/torture/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "nd666-torture" +version = "0.1.0" diff --git a/docs/external/nightdriver/666/harness/torture/Cargo.toml b/docs/external/nightdriver/666/harness/torture/Cargo.toml new file mode 100644 index 0000000..43eeb73 --- /dev/null +++ b/docs/external/nightdriver/666/harness/torture/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "nd666-torture" +version = "0.1.0" +edition = "2021" +publish = false + +[workspace] + +[dependencies] diff --git a/docs/external/nightdriver/666/harness/torture/src/main.rs b/docs/external/nightdriver/666/harness/torture/src/main.rs new file mode 100644 index 0000000..314e3b7 --- /dev/null +++ b/docs/external/nightdriver/666/harness/torture/src/main.rs @@ -0,0 +1,353 @@ +//! Deterministic TCP torture harness for a NightDriverStrip-style framed receiver. +//! +//! Drives a host build of the project's real socket-server source (see ../host/build.sh) +//! over loopback and checks what the receiver hands to its packet consumer. +//! +//! usage: nd666-torture --label NAME --audio 0|1 [--only CASE] [--strict] +//! +//! Output: one tab separated line per case: CASE PASS|FAIL|INFO detail +//! PASS/FAIL cases encode a property the receiver must hold (stream stays in sync). +//! INFO cases record observed behaviour where the project has no stated contract. + +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::process::{Child, Command, Stdio}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +const NUM_LEDS: usize = 144; // must match the stub globals.h +const HDR: usize = 24; +const RESP: usize = 72; + +// ---------- frame builders (wire layout per the sender, samples/audioserver/audioserver.py) ---------- + +fn fnv(b: &[u8]) -> u32 { + let mut h: u32 = 2166136261; + for x in b { h ^= *x as u32; h = h.wrapping_mul(16777619); } + h +} + +fn header(cmd: u16, w2: u16, len32: u32) -> Vec { + let mut v = Vec::with_capacity(HDR); + v.extend_from_slice(&cmd.to_le_bytes()); + v.extend_from_slice(&w2.to_le_bytes()); + v.extend_from_slice(&len32.to_le_bytes()); + v.extend_from_slice(&1_731_164_000u64.to_le_bytes()); + v.extend_from_slice(&0.25f64.to_le_bytes()); + v +} + +/// Pixel frame (command 3) with n LEDs. +fn pixel(n: usize, seed: u8) -> Vec { + let mut v = header(3, 0, n as u32); + for i in 0..n * 3 { v.push((i as u8).wrapping_mul(7).wrapping_add(seed)); } + v +} + +/// Peak data frame (command 4) with `bands` float32 values; float[0] has the given bit pattern. +fn peak(bands: usize, f0_bits: u32) -> Vec { + let mut v = header(4, bands as u16, (bands * 4) as u32); + v.extend_from_slice(&f0_bits.to_le_bytes()); + for i in 1..bands { v.extend_from_slice(&(0.01f32 * i as f32).to_le_bytes()); } + v +} + +#[derive(Debug, Clone, PartialEq)] +struct Pkt { cmd: u16, len: usize, fnv: u32 } +fn expect(frame: &[u8]) -> Pkt { + Pkt { cmd: u16::from_le_bytes([frame[0], frame[1]]), len: frame.len(), fnv: fnv(frame) } +} + +// ---------- host process ---------- + +struct Host { child: Child, lines: Arc>>, port: u16, sessions: usize } + +impl Host { + fn spawn(bin: &str) -> Host { + let port = { let l = TcpListener::bind("127.0.0.1:0").unwrap(); l.local_addr().unwrap().port() }; + let mut child = Command::new(bin).arg(port.to_string()).arg("2") + .stdout(Stdio::piped()).stderr(Stdio::null()).spawn().expect("spawn host"); + let out = child.stdout.take().unwrap(); + let lines = Arc::new(Mutex::new(Vec::new())); + let l2 = lines.clone(); + std::thread::spawn(move || { + use std::io::{BufRead, BufReader}; + for line in BufReader::new(out).lines().flatten() { l2.lock().unwrap().push(line); } + }); + Host { child, lines, port, sessions: 0 } + } + fn count(&self, needle: &str) -> usize { self.lines.lock().unwrap().iter().filter(|l| l.contains(needle)).count() } + /// Wait for the server to (re)start listening, then connect. One call per connection. + fn connect(&mut self) -> TcpStream { + self.sessions += 1; + let t = Instant::now(); + while self.count("listening on port") < self.sessions { + assert!(t.elapsed() < Duration::from_secs(10), "server never listened"); + std::thread::sleep(Duration::from_millis(10)); + } + let s = TcpStream::connect(("127.0.0.1", self.port)).expect("connect"); + s.set_nodelay(true).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + s + } + fn pkts(&self) -> Vec { + self.lines.lock().unwrap().iter().filter_map(|l| { + let r = l.strip_prefix("PKT ")?; + let g = |k: &str| r.split_whitespace().find_map(|w| w.strip_prefix(k)).map(str::to_string); + Some(Pkt { cmd: g("cmd=")?.parse().ok()?, len: g("len=")?.parse().ok()?, fnv: u32::from_str_radix(&g("fnv=")?, 16).ok()? }) + }).collect() + } + fn unknown(&self) -> Vec { + self.lines.lock().unwrap().iter().filter_map(|l| { + l.split("Unknown command in packet received: ").nth(1)?.trim().parse().ok() + }).collect() + } + fn wait_pkts(&self, n: usize, ms: u64) { + let t = Instant::now(); + while self.pkts().len() < n && t.elapsed() < Duration::from_millis(ms) { std::thread::sleep(Duration::from_millis(10)); } + } + fn settle(&self) { std::thread::sleep(Duration::from_millis(250)); } +} +impl Drop for Host { fn drop(&mut self) { let _ = self.child.kill(); let _ = self.child.wait(); } } + +/// Read one response packet. Its first u32 is its own size (64 bytes before 2024-11-25, 72 after). +fn read_resp(s: &mut TcpStream) -> bool { + let mut n = [0u8; 4]; + if s.read_exact(&mut n).is_err() { return false; } + let size = u32::from_le_bytes(n) as usize; + if !(8..=RESP).contains(&size) { return false; } + let mut rest = vec![0u8; size - 4]; + s.read_exact(&mut rest).is_ok() +} +/// True if the peer closed (EOF or reset) within ms. +fn closed_by_peer(s: &mut TcpStream, ms: u64) -> bool { + s.set_read_timeout(Some(Duration::from_millis(ms))).unwrap(); + let mut b = [0u8; 1]; + match s.read(&mut b) { Ok(0) => true, Ok(_) => false, Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) } +} +/// Write that tolerates the receiver having already closed (that is itself an observation, not a harness error). +fn wr(s: &mut TcpStream, b: &[u8]) { let _ = s.write_all(b); } +fn pause(ms: u64) { std::thread::sleep(Duration::from_millis(ms)); } + +// ---------- cases ---------- + +enum V { Pass(String), Fail(String), Info(String) } +use V::*; + +struct Env { bin: String, audio: bool } + +fn check_exact(h: &Host, want: &[Pkt]) -> V { + h.wait_pkts(want.len(), 3000); + h.settle(); + let got = h.pkts(); + let unk = h.unknown(); + if got == want && unk.is_empty() { Pass(format!("{} packets, all matched", got.len())) } + else { Fail(format!("want {} packets, got {} (unknown-command values: {:?})", want.len(), got.len(), unk)) } +} + +fn c_whole_frames(e: &Env) -> V { + let mut h = Host::spawn(&e.bin); let mut s = h.connect(); + let f = [pixel(10, 1), pixel(10, 2), pixel(NUM_LEDS, 3)]; + for x in &f { wr(&mut s, x); if !read_resp(&mut s) { return Fail("no response packet".into()); } } + check_exact(&h, &f.iter().map(|x| expect(x)).collect::>()) +} + +fn c_split_every_offset(e: &Env) -> V { + // One frame split into two writes at every possible offset, 15 ms apart, all on one connection. + let mut h = Host::spawn(&e.bin); let mut s = h.connect(); + let f = pixel(10, 5); + for k in 1..f.len() { + wr(&mut s, &f[..k]); pause(15); wr(&mut s, &f[k..]); + if !read_resp(&mut s) { return Fail(format!("no response after split at {k}")); } + } + check_exact(&h, &vec![expect(&f); f.len() - 1]) +} + +fn c_coalesced(e: &Env) -> V { + let mut h = Host::spawn(&e.bin); let mut s = h.connect(); + let (a, b, c) = (pixel(10, 1), pixel(20, 2), pixel(5, 3)); + let mut all = a.clone(); all.extend(&b); all.extend(&c); + wr(&mut s, &all); // three frames in one segment + let mut d = pixel(7, 4); let mut tail = pixel(9, 5); + let mut two = d.clone(); two.extend(&tail[..13]); // frame + start of the next + wr(&mut s, &two); pause(30); wr(&mut s, &tail[13..]); + for _ in 0..5 { if !read_resp(&mut s) { return Fail("missing response".into()); } } + d.truncate(d.len()); tail.truncate(tail.len()); + check_exact(&h, &[expect(&a), expect(&b), expect(&c), expect(&d), expect(&tail)]) +} + +fn c_one_byte_writes(e: &Env) -> V { + let mut h = Host::spawn(&e.bin); let mut s = h.connect(); + let f = [pixel(4, 9), pixel(4, 10)]; + for x in &f { for b in x { wr(&mut s, &[*b]); pause(1); } if !read_resp(&mut s) { return Fail("no response".into()); } } + check_exact(&h, &f.iter().map(|x| expect(x)).collect::>()) +} + +/// The audioserver.py shape: peak frame (12 bands) interleaved with pixel frames. +/// Property: the receiver never loses frame alignment (no "Unknown command"), whatever it does with audio. +/// float[0] low 16 bits are 0x79E2 = 31202, the value in issue 666. +fn c_peak12_with_pixels(e: &Env) -> V { + let mut h = Host::spawn(&e.bin); let mut s = h.connect(); + let p = peak(12, 0x3F00_79E2); + let px = pixel(10, 1); + for _ in 0..2 { wr(&mut s, &p); pause(20); wr(&mut s, &px); pause(20); } + pause(400); + let unk = h.unknown(); + let pk = h.pkts(); + if unk.is_empty() { Pass(format!("no desync; audio={} packets seen: {:?}", e.audio as u8, pk.iter().map(|x| (x.cmd, x.len)).collect::>())) } + else { Fail(format!("receiver lost frame alignment: Unknown command {:?}; packets {:?}", unk, pk.iter().map(|x| (x.cmd, x.len)).collect::>())) } +} + +fn c_peak16_with_pixels(e: &Env) -> V { + let mut h = Host::spawn(&e.bin); let mut s = h.connect(); + let p = peak(16, 0x3F00_79E2); let px = pixel(10, 1); + wr(&mut s, &p); pause(20); wr(&mut s, &px); pause(20); + wr(&mut s, &p); pause(20); wr(&mut s, &px); + pause(500); + let want: Vec = if e.audio { vec![expect(&p), expect(&px), expect(&p), expect(&px)] } else { vec![expect(&px), expect(&px)] }; + let got = h.pkts(); let unk = h.unknown(); + if got == want && unk.is_empty() { Pass(format!("audio={} sequence consumed in order, {} packets", e.audio as u8, got.len())) } + else { Fail(format!("want {} packets got {}; unknown-command {:?}", want.len(), got.len(), unk)) } +} + +fn c_http_get(e: &Env) -> V { + // Issue 666 second reporter: a websocket client aimed at the raw port sends an HTTP upgrade request. + let mut h = Host::spawn(&e.bin); let mut s = h.connect(); + wr(&mut s, b"GET /ws HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\n\r\n"); + pause(500); + let unk = h.unknown(); + let closed = closed_by_peer(&mut s, 1000); + if unk == vec![17735] && closed { Pass("rejected with Unknown command 17735 (= 0x4547, bytes 'G','E'), connection closed".into()) } + else { Fail(format!("unknown={:?} closed={}", unk, closed)) } +} + +fn c_disconnect_partial_then_valid(e: &Env) -> V { + let mut h = Host::spawn(&e.bin); + let f = pixel(10, 1); + { let mut s = h.connect(); wr(&mut s, &f[..10]); pause(100); } // drop mid-header + { let mut s = h.connect(); wr(&mut s, &f[..40]); pause(100); } // drop mid-body + let mut s = h.connect(); wr(&mut s, &f); read_resp(&mut s); + check_exact(&h, &[expect(&f)]) +} + +fn c_malformed_then_valid(e: &Env) -> V { + let mut h = Host::spawn(&e.bin); + { let mut s = h.connect(); let mut bad = header(0x7777, 0, 0); bad.extend_from_slice(&[0; 8]); wr(&mut s, &bad); pause(300); } + let f = pixel(10, 2); + let mut s = h.connect(); wr(&mut s, &f); read_resp(&mut s); + h.wait_pkts(1, 3000); h.settle(); + if h.pkts() == vec![expect(&f)] && h.unknown() == vec![0x7777] { Pass("bad command rejected (30583), next connection clean".into()) } + else { Fail(format!("pkts={:?} unknown={:?}", h.pkts().len(), h.unknown())) } +} + +fn c_max_and_oversize(e: &Env) -> V { + let mut h = Host::spawn(&e.bin); + let max = pixel(NUM_LEDS, 1); + { let mut s = h.connect(); wr(&mut s, &max); read_resp(&mut s); } + let over = pixel(NUM_LEDS + 1, 2); + let closed; + { let mut s = h.connect(); wr(&mut s, &over); closed = closed_by_peer(&mut s, 1500); } + let ok = pixel(3, 3); + { let mut s = h.connect(); wr(&mut s, &ok); read_resp(&mut s); } + h.wait_pkts(2, 3000); h.settle(); + if h.pkts() == vec![expect(&max), expect(&ok)] && closed { Pass("max frame accepted, max+1 rejected and connection closed, next clean".into()) } + else { Fail(format!("pkts={} closed={}", h.pkts().len(), closed)) } +} + +fn c_huge_length(e: &Env) -> V { + let mut h = Host::spawn(&e.bin); + let mut bad = header(3, 0, 0xFFFF_FFFF); bad.extend_from_slice(&[0; 16]); + let closed; + { let mut s = h.connect(); wr(&mut s, &bad); closed = closed_by_peer(&mut s, 1500); } + pause(200); + if h.pkts().is_empty() && closed { Pass("length32=0xFFFFFFFF rejected on this 64-bit host".into()) } else { Fail(format!("pkts={} closed={}", h.pkts().len(), closed)) } +} + +fn c_zero_length(e: &Env) -> V { + let mut h = Host::spawn(&e.bin); let mut s = h.connect(); + wr(&mut s, &pixel(0, 0)); pause(300); + let resp = { s.set_read_timeout(Some(Duration::from_millis(300))).unwrap(); read_resp(&mut s) }; + Info(format!("zero-LED pixel frame: packets={:?} response={} unknown={:?}", h.pkts().iter().map(|p| p.len).collect::>(), resp, h.unknown())) +} + +fn c_slow_sender_within_timeout(e: &Env) -> V { + let mut h = Host::spawn(&e.bin); let mut s = h.connect(); + let f = pixel(10, 4); + wr(&mut s, &f[..5]); pause(1000); wr(&mut s, &f[5..30]); pause(1000); wr(&mut s, &f[30..]); + read_resp(&mut s); + check_exact(&h, &[expect(&f)]) +} + +fn c_slow_sender_past_timeout(e: &Env) -> V { + // The receiver sets a 3 s read timeout so a stalled sender cannot hang it. Property: it drops the + // connection and the next connection works. + let mut h = Host::spawn(&e.bin); + let f = pixel(10, 6); + { let mut s = h.connect(); wr(&mut s, &f[..10]); pause(3600); wr(&mut s, &f[10..]); pause(200); } + let g = pixel(10, 7); + { let mut s = h.connect(); wr(&mut s, &g); read_resp(&mut s); } + h.wait_pkts(1, 3000); h.settle(); + let got = h.pkts(); + if got == vec![expect(&g)] { Pass("stalled partial frame timed out and was discarded; next connection clean".into()) } + else { Fail(format!("packets={:?} unknown={:?}", got.iter().map(|p| (p.cmd, p.len)).collect::>(), h.unknown())) } +} + +fn c_slow_receiver(e: &Env) -> V { + // Client never reads the 72-byte response packets. Observe how many frames still get consumed. + let mut h = Host::spawn(&e.bin); let mut s = h.connect(); + let f = pixel(2, 1); + s.set_write_timeout(Some(Duration::from_millis(500))).unwrap(); + let mut sent = 0usize; + for _ in 0..4000 { if s.write_all(&f).is_err() { break; } sent += 1; } + pause(1500); + Info(format!("sent {} frames without reading responses; receiver consumed {}; unknown={:?}", sent, h.pkts().len(), h.unknown())) +} + +fn c_sender_short_write(e: &Env) -> V { + // Emulates a sender whose send() wrote only the first k bytes and never resent the tail + // (the failure sendall() prevents). Records how the receiver reports it. k=40 cuts mid-body. + let mut out = Vec::new(); + for k in [12usize, 24, 40] { + let mut h = Host::spawn(&e.bin); let mut s = h.connect(); + let a = pixel(10, 1); let b = pixel(10, 2); let c = pixel(10, 3); + wr(&mut s, &a[..k]); pause(20); + wr(&mut s, &b); pause(20); wr(&mut s, &c); pause(400); + let intact = h.pkts().iter().filter(|p| **p == expect(&a) || **p == expect(&b) || **p == expect(&c)).count(); + out.push(format!("k={}: packets={} intact={} unknown={:?}", k, h.pkts().len(), intact, h.unknown())); + } + Info(out.join(" | ")) +} + +fn c_reconnect_storm(e: &Env) -> V { + let mut h = Host::spawn(&e.bin); + let mut want = Vec::new(); + for i in 0..5u8 { let f = pixel(6, i); let mut s = h.connect(); wr(&mut s, &f); read_resp(&mut s); want.push(expect(&f)); } + check_exact(&h, &want) +} + +fn main() { + let a: Vec = std::env::args().collect(); + if a.len() < 2 { eprintln!("usage: nd666-torture --label NAME --audio 0|1 [--only CASE] [--strict]"); std::process::exit(2); } + let opt = |k: &str| a.iter().position(|x| x == k).and_then(|i| a.get(i + 1)).cloned(); + let label = opt("--label").unwrap_or_else(|| a[1].clone()); + let e = Env { bin: a[1].clone(), audio: opt("--audio").as_deref() == Some("1") }; + let only = opt("--only"); + let strict = a.iter().any(|x| x == "--strict"); + let cases: Vec<(&str, fn(&Env) -> V)> = vec![ + ("whole_frames", c_whole_frames), ("split_every_offset", c_split_every_offset), ("coalesced", c_coalesced), + ("one_byte_writes", c_one_byte_writes), ("peak12_with_pixels", c_peak12_with_pixels), ("peak16_with_pixels", c_peak16_with_pixels), + ("http_get_on_raw_port", c_http_get), ("disconnect_partial_then_valid", c_disconnect_partial_then_valid), + ("malformed_then_valid", c_malformed_then_valid), ("max_and_oversize", c_max_and_oversize), ("huge_length", c_huge_length), + ("zero_length", c_zero_length), ("slow_sender_within_timeout", c_slow_sender_within_timeout), + ("slow_sender_past_timeout", c_slow_sender_past_timeout), ("slow_receiver", c_slow_receiver), + ("sender_short_write", c_sender_short_write), ("reconnect_storm", c_reconnect_storm), + ]; + let mut fails = 0; + for (name, f) in cases { + if only.as_deref().map_or(false, |o| o != name) { continue; } + let (tag, d) = match f(&e) { Pass(d) => ("PASS", d), Fail(d) => { fails += 1; ("FAIL", d) } Info(d) => ("INFO", d) }; + println!("{label}\t{name}\t{tag}\t{d}"); + } + println!("{label}\tSUMMARY\tfails={fails}"); + if strict && fails > 0 { std::process::exit(1); } +} diff --git a/docs/external/nightdriver/666/transport-cases.md b/docs/external/nightdriver/666/transport-cases.md new file mode 100644 index 0000000..fb364b5 --- /dev/null +++ b/docs/external/nightdriver/666/transport-cases.md @@ -0,0 +1,58 @@ +# Generic transport-conformance cases (extracted from the NightDriver 666 investigation) + +Semantic descriptions only. No code from the investigated project is reproduced here. Each case +applies to any receiver that parses length-prefixed frames from a TCP byte stream, which includes +INTERPLANE transports in the 0.4 Runner work. + +Notation: a frame is `header (fixed size) + body (length given in header)`. "Consumer" is whatever +the receiver hands complete frames to. + +## Stream-alignment property (the one that mattered) + +**T-ALIGN-1. Every accepted command consumes its whole declared frame.** +For each command the receiver accepts, including commands it intends to ignore or has disabled, +the receiver must read and discard the full declared body before parsing the next header. +Failure signature: the next "header" is taken from the middle of a previous body, so the first +field is a meaningless value (here a 16 bit command id equal to the low bits of a float). +Test: send `[ignored-command frame][valid frame][ignored-command frame][valid frame]`; require the +valid frames to reach the consumer and no unknown-command rejection. + +**T-ALIGN-2. A disabled feature must not change framing.** +Run T-ALIGN-1 once with the feature enabled and once disabled. The consumer-visible result may +differ, but the "no rejection, next frame aligned" outcome must be identical. + +## Segmentation + +**T-SEG-1. Header split at every byte offset.** One frame, two writes, split at each offset in the header, pause between writes. +**T-SEG-2. Body split at every byte offset.** Same, across the body. +**T-SEG-3. Coalescing.** Several frames in one write; a frame plus the first part of the next; remainder in a later write. +**T-SEG-4. Single-byte writes.** A full frame sent one byte at a time. +Expectation for all: exactly the sent frames reach the consumer, in order, byte-identical. + +## Connection lifecycle + +**T-LIFE-1. Disconnect mid-header, then reconnect with a valid frame.** No state from the aborted connection may leak: only the valid frame is delivered. +**T-LIFE-2. Disconnect mid-body, then reconnect.** Same. +**T-LIFE-3. Reconnect storm.** Repeated connect, one frame, close. Every frame delivered once. +**T-LIFE-4. Stalled sender.** Header or body paused longer than the receiver's read timeout. The receiver drops the connection and discards the partial frame; the next connection is clean. Paused shorter than the timeout: the frame is delivered. +**T-LIFE-5. Non-reading client.** Client never reads responses. Record whether the receiver keeps consuming. (Observation, not a pass/fail contract.) + +## Bounds and malformed input + +**T-BOUND-1. Maximum declared size accepted, maximum plus one rejected** with the connection closed and the next connection clean. +**T-BOUND-2. Declared length at the integer limit** (all bits set, and a value whose size computation wraps on a 32 bit target) is rejected without allocating or reading that many bytes. +**T-BOUND-3. Zero-length body.** Record behaviour (consumer called or not, response or not). Observation. +**T-BOUND-4. Unknown command.** Rejected, connection closed, next connection clean, and the rejection reports the first bytes it saw so a human can identify foreign traffic. +**T-BOUND-5. Foreign protocol on the port.** An HTTP request line sent to a raw framed port is rejected as an unknown command and the connection closed. The reported value decodes to the first two ASCII bytes. Error messages for this case should say "unknown command" with the raw bytes, so the operator can recognise a misconfigured client. + +## Sender-side faults + +**T-SEND-1. Sender wrote a prefix and dropped the tail** (the failure `sendall` prevents and plain `send` permits on short writes). A framed stream cannot detect this. Record what the receiver reports; it is expected to be either a corrupted but well-formed frame followed by an unknown-command rejection, or a pure unknown-command rejection. Mitigation belongs to the sender (loop until all bytes are written) or to the protocol (per-frame checksum or sync marker), not to the receiver's parser. +**T-SEND-2. Sender short-write probe.** Blocking send of a small frame under receiver backpressure: verify whether the platform returns a short count. (Observed on Linux with CPython 3.12: never, including under backpressure.) + +## Reading a rejection value + +When a receiver reports a single unexpected integer, decode it before debugging anything else: +little-endian bytes of the integer, compare to ASCII (foreign protocol) and to the bytes at each +offset of a valid frame (desync). A value that equals bytes from the middle of a valid frame points +at framing; a value that is printable ASCII points at a foreign client. diff --git a/docs/external/nightdriver/666/upstream-comment-draft.md b/docs/external/nightdriver/666/upstream-comment-draft.md new file mode 100644 index 0000000..fd9418a --- /dev/null +++ b/docs/external/nightdriver/666/upstream-comment-draft.md @@ -0,0 +1,11 @@ +# DRAFT, NOT SENT. For the owner to post or discard. Do not mention anything outside NightDriverStrip. + +Possible comment for issue 666 (the first reporter's problem): + +> A note on the number: 31202 is 0x79E2, so the bytes `E2 79` were read where a command id belongs. That is consistent with the receiver having lost frame alignment partway through a PEAKDATA frame: in builds with audio disabled, before commit d73d18db, the PEAKDATA branch of `socketserver.cpp` read only the 24 byte header and left the audio payload in the stream, so the next "header" was payload bytes. d73d18db now reads and discards the declared payload. (Whether those two bytes were the low bits of the first band value can't be confirmed from the report.) +> +> I built the real `socketserver.cpp` on a Linux host (stubbed platform layer, loopback TCP) and fed it audioserver.py-shaped frames: before d73d18db it reports "Unknown command in packet received: 31202" for a frame whose first float ends in those bytes; at d73d18db and on current main every frame is consumed, with audio enabled or disabled. This was not run on a physical ESP32 and does not cover lwIP behaviour. +> +> Two things to check on your side even with a newer build: +> 1. With `ENABLE_AUDIO 0` (as in the posted `LEDSTRIP` config) the firmware accepts and discards the peak data, so the sample cannot drive anything. With `ENABLE_AUDIO 1` the band count in the script has to equal the firmware's `NUM_BANDS`. The script you pasted has `num_bands = 12`; the copy in the repository has 16, which matches the default. A 12-band sender is rejected as "Invalid peak data packet". +> 2. I have not looked at how remote peak data behaves when no microphone is attached.