diff --git a/prototype-server-vision/.gitignore b/prototype-server-vision/.gitignore index d055eb2..783ca67 100644 --- a/prototype-server-vision/.gitignore +++ b/prototype-server-vision/.gitignore @@ -8,3 +8,4 @@ server run/ results/*.jsonl results/faults.log +results/*-15s* diff --git a/prototype-server-vision/NOTES.md b/prototype-server-vision/NOTES.md index 0eb8681..d5d6df0 100644 --- a/prototype-server-vision/NOTES.md +++ b/prototype-server-vision/NOTES.md @@ -2,7 +2,7 @@ ## Geometry edge-case log - BROKE: `cellsTouched` returned nothing for a polygon wholly inside one cell (no edge crosses the cell, no cell corner inside poly). FIX: also hit if a polygon vertex lies in the cell. -- Test bug (not code): "shared endpoint" case asserted a point hugging a wall the token stands on line with was hidden; it is legitimately visible. Removed. +- Test bug (not code): "shared endpoint" case asserted a point hugging a wall the token stands on line with was hidden; it is legitimately visible. Removed. RESTORED with the correct expectation (token on the arm line: point 5 px below visible, 5 px above hidden); weak corner-case tests (box corner, collinear, T-junction, token at endpoint, free-standing wall, behind-viewer fan) got visible+hidden probes, no geometry bug found. - Design choices that avoided bugs (all pass first run): rays to each endpoint at -eps/0/+eps (1e-4 rad); ray/segment u-range inclusive with 1e-9 tolerance so no cracks at shared vertices / T-junctions; parallel (collinear) rays skipped since neighbouring +-eps rays cover them; token on an endpoint: that endpoint skipped for ray generation and hits at t<=1e-9 ignored. - Moves: inclusive intersection (touching = blocked) so no squeezing through shared vertices. Limit: token standing exactly on a wall can't move off it; server must keep tokens off walls. - Vision circle = inscribed 64-gon (max error r*(1-cos(pi/64)) ~ 0.12% of r). @@ -22,7 +22,7 @@ - BUG (client): door click `if (d)` would ignore door id 0. FIX: `!== null`. - Leak scenario bugs were scenario bugs (diagonal steps through walls), not server bugs; server answered `ok:false` as designed. - Leak checker B-string check initially flagged legit `remove{id:"B"}`; exempted token/remove. -- Perf finding: cellsTouched (~0.6 ms) is 15x the visibility polygon (~0.04 ms); per-move vision_ms is dominated by explored-cell computation. +- Perf finding: cellsTouched (~0.46 ms) is ~12x the visibility polygon (~0.04 ms) (results/bench.log); per-move vision_ms is dominated by explored-cell computation. ## Post-phase-3 manual-test bug - BUG (server, geometry.nim): `visibilityPolygon` sorted circle-segment angles in [0,2pi) together with wall-endpoint atan2 angles in (-pi,pi] -> fan vertices out of angular order -> bow-tie polygon, even-odd `inside`/`cellsTouched` dropped regions (tokens in plain LOS not shown, explored/tiles missing). Position dependent. FIX: wrap circle angles with atan2(sin,cos). diff --git a/prototype-server-vision/README.md b/prototype-server-vision/README.md index 101670d..9227411 100644 --- a/prototype-server-vision/README.md +++ b/prototype-server-vision/README.md @@ -18,12 +18,14 @@ Browser rendering was NOT verified (no browser in the build environment): only H ## Tests | cmd | what | |---|---| -| `devbox run test` | regen map + `nimble test` (geometry: visibility, moves, cells, seed sanity) | +| `devbox run test` | regen map + `nimble test` (geometry), smoke, leaktest, faulttest, restart, concurrency (DUR=15) | | `devbox run client` | includes client reducer test (`npm run check`, incl. reconnect reset) | | `devbox run smoke` | fresh DB, server+nginx, auth/cookie/tile/steal/garbage checks | -| `devbox run leaktest` | runs twice (SUBJECT=A, SUBJECT=B), fresh DB each; subject walks ~240 steps through rooms, corridor, open/closed doors while GM + B act; Nim checker (`tools/leakcheck.nim`) replays `run/leak-transcript.jsonl` | -| `devbox run concurrency` | 60 s (`DUR=` secs) A, B, GM(6 monsters + doors) at 20-50 ms per token | -| `devbox run bench` | vision microbench | +| `devbox run leaktest` | runs twice (SUBJECT=A, SUBJECT=B), fresh DB each; subject walks ~240 steps through rooms, corridor, open/closed doors while GM + B act; Nim checker (`tools/leakcheck.nim`) replays the transcript. Output per subject: `results/leak-A.log`, `results/leak-B.log` (committed), transcripts `results/leak-{A,B}.jsonl` (1.1-1.3 MB, gitignored) | +| `devbox run faulttest` | deliberate leaks: builds the server with `-d:leakfault` (hook absent from the normal build, asserted by grepping the clean binary for `LEAK_FAULT`), injects 8 faults one at a time (`LEAK_FAULT=`): hidden token sent (`hidden`), wall data to player (`walls`), unexplored tile 200 (`tile`), visible token withheld (`withhold`), B's vision / explored / ownership sent to A (`other-vision`, `other-explored`, `other-owner`), missing `remove` (`noremove`). Passes only if the checker fails each with exactly the expected failure-class set (classes: HIDDEN_TOKEN WALLDATA TILE WITHHELD OTHER_PLAYER NO_REMOVE, plus collateral OWN_VIEW / EXPLORED) and the clean build still passes. Details in `results/faults.log` (gitignored) | +| `devbox run restart` | isolated server, moves A/B/monsters, toggles doors, A explores a new area; stops with SIGTERM then (second round of changes) SIGKILL, restarts on the same DB; asserts invite secrets, token positions, doors, vision, explored grids per role and the full hello+state a reconnecting client receives are identical (gseq excluded: in-memory). Note: the server has no SIGTERM handler, so SIGTERM is as abrupt as SIGKILL; durability rests on SQLite WAL commit before ack | +| `devbox run concurrency` | 60 s (`DUR=` secs) A, B, GM(6 monsters + doors) at 20-50 ms per token; logs `results/concurrency-s.log` + `...-server.log` (server STATS) | +| `devbox run bench` | vision microbench, log `results/bench.log` | Tests are isolated: `tools/withserver.sh` uses `run/test/` (own DB, invites, nginx conf/logs) and ports 18088 (nginx) / 19000 (server), overridable via `TEST_PORT`/`TEST_BACKEND_PORT`; the live session on 8088/9000 and `run/` are never touched. Server stats print on stop into `run/test/server.log`. @@ -32,38 +34,40 @@ Ground truth = GM socket (tokens + doors per gseq). A's expected vision/explored - (a) A receives only hello/vision/explored/token/remove/moveAck; no wall-like keys (walls, door, open, a, b, segments...) anywhere. - (b) every token A is sent is inside the independently computed polygon (0.5 px boundary tolerance); every token inside it IS in A's view (completeness); view positions == truth; A's `vision` polygon equals the recomputed one (1e-6); A's explored set == recomputed set. - (c) `remove` arrives when a token leaves; scenario must show M1, M2, M5, B and >= 3 removes. -- (d) 256 tiles requested at 40+ points (10240 requests, incl. unexplored): 200 iff an explored cell touches the tile at that gseq, else 403. +- (d) 256 tiles requested per sweep (A: 39 sweeps = 9984 requests, B: 29 = 7424; incl. unexplored): 200 iff an explored cell touches the tile at that gseq, else 403. - (e) A never gets B-bound info: no B string outside token/remove, no `by:B` on others' tokens, hello tokens == ["A"], no error msgs. -Negative control done once by hand: injecting an out-of-vision token / a 200 for an unexplored tile into the transcript is flagged. +Negative control: automated, `devbox run faulttest` (above). -Result: PASS (220 gseq groups, 465 A msgs, 4 other tokens seen, 6 removes, tiles 1792 x 200 / 8448 x 403, 2163 explored cells, 0 failures). +Result (`results/leak-A.log`): PASS (218 gseq groups, 467 A msgs, 4 other tokens seen, 4 removes, tiles 1709 x 200 / 8275 x 403, 2142 explored cells, 0 failures). +Result (`results/leak-B.log`): PASS (218 gseq groups, 217 B msgs, 3 other tokens seen, 3 removes, tiles 686 x 200 / 6738 x 403, 1114 explored cells, 0 failures). -### Concurrency result (60 s, PASS) -Load was ~225 intents/s (A 28, B 28, 6 monsters 169) + door toggles every 1-3 s. 13876 mutations, no crash, 0 errors, gseq never went backwards at any client (non-decreasing; messages of one mutation share a gseq), every intent acked (sent == acks for all 3 clients), and after quiesce each client's tokens/doors/vision/explored == a fresh connection's snapshot. +### Concurrency result (60 s, PASS; `results/concurrency-60s.log`) +Load was ~223 intents/s (A 28, B 28, 6 monsters 167; `results/concurrency-60s.log`) + door toggles every 1-3 s. 13781 mutations (10300 monster + 3421 player moves + 60 doors; `results/concurrency-60s-server.log`, = final gseq in the log), no crash, 0 errors, gseq never went backwards at any client (non-decreasing; messages of one mutation share a gseq), every intent acked (sent == acks for all 3 clients; nacks = blocked random-walk moves: GM 64, A 17, B 0), and after quiesce each client's tokens/doors/vision/explored == a fresh connection's snapshot. ## Measurements (laptop, release build, localhost) -| metric | avg | p95 | worst | -|---|---|---|---| -| vision recompute per player move (server, incl. cellsTouched + diff) | 0.75 ms | - | 2.6 ms | -| vision recompute per monster move | 0.000 ms (no vision) | - | 0.005 ms | -| door toggle (2 roles) | 0.10 ms | - | 0.15 ms | -| bench: 1 visibility polygon | 0.036 ms | - | 0.13 ms | -| bench: 6 polygons | 0.20 ms | - | 0.29 ms | -| bench: 1 poly + cellsTouched | 0.67 ms | - | 1.8 ms | -| bench: 6 polys + cellsTouched | 4.7 ms | - | 7.3 ms | -| latency intent -> ack (sender, via nginx) | 0.92 ms | 1.98 ms | 13.9 ms | -| latency intent -> arrival at other clients | 1.26 ms | 2.37 ms | 11.2 ms | +Sources: C = `results/concurrency-60s.log`, S = `results/concurrency-60s-server.log` (server STATS), B = `results/bench.log`. +| metric | avg | p95 | worst | source | +|---|---|---|---|---| +| vision recompute per player move (server, incl. cellsTouched + diff) | 1.16 ms | - | 14.0 ms | S `vision_ms move-player` | +| vision recompute per monster move | 0.000 ms (no vision) | - | 0.025 ms | S `vision_ms move-monster` | +| door toggle (2 roles) | 0.19 ms | - | 0.49 ms | S `vision_ms door` | +| bench: 1 visibility polygon | 0.038 ms | - | 0.19 ms | B | +| bench: 6 polygons | 0.21 ms | - | 0.29 ms | B | +| bench: 1 poly + cellsTouched | 0.46 ms | - | 1.2 ms | B | +| bench: 6 polys + cellsTouched | 3.0 ms | - | 5.1 ms | B | +| latency intent -> ack (sender, via nginx) | 6.33 ms | 11.58 ms | 583 ms | C | +| latency intent -> arrival at other clients | 7.22 ms | 12.89 ms | 583 ms | C | -Bytes per delivery (only recipients that got something): +Bytes per delivery (only recipients that got something; S `bytes/delivery`): | mutation | recipient | avg B | |---|---|---| | monster move | GM | 243 | -| monster move | player who sees it | 147 | -| player move | the mover (ack + token + new `vision` + `explored` diff) | 3470-3710 (worst 5.0 KB) | -| player move | GM | 144 | -| door toggle | GM | 44 | +| monster move | player who sees it | 145 (A) - 148 (B) | +| player move | the mover (ack + token + new `vision` + `explored` diff) | 3181 (B) - 3679 (A) (worst 4.9 KB) | +| player move | GM | 145 | +| door toggle | GM | 45 | -"6 moving tokens" with vision: monsters have none in this design, so the 6-token case is the bench (a 6-token party in one role = 6 polys per recompute: 0.2 ms polys, 4.7 ms with cell marking). Concurrency exercised 6 simultaneously moving monsters (no vision cost) + 2 players. +"6 moving tokens" with vision: monsters have none in this design, so the 6-token case is the bench (a 6-token party in one role = 6 polys per recompute: 0.21 ms polys, 3.0 ms with cell marking; B). Concurrency exercised 6 simultaneously moving monsters (no vision cost) + 2 players. ## Findings **Worked** @@ -76,14 +80,14 @@ Bytes per delivery (only recipients that got something): **Edge cases that broke (see NOTES.md)**: `cellsTouched` missed polygons wholly inside one cell (fix: vertex-in-cell test); client did not reset on reconnect (fix: reset on `hello`); door id 0 falsy check; leak scenario steps crossing walls diagonally (scenario bug, server correctly refused). **mummy suitability** -- Send is thread-safe by construction: `WebSocket.send` appends the encoded frame to one server-wide deque under `sendQueueLock` and triggers the IO thread (mummy.nim ~L262-311); the IO thread drains it. Per-socket events are serialized by mummy. Because we also send while holding our own lock, per-socket order == gseq order, so no separate broadcaster was needed. 60 s of mixed 3-client load, ~14k mutations, ~40k messages: no crash, no reorder, no loss, consistent final views. -- Caveats: `WebSocket` has no `==`/hash, we key a table by its raw bytes (shortcut, works while it is one pointer-sized ref). Everything is serialized by one lock, so throughput is single-core bound (fine here: ~1 ms/move). Sending under the lock is cheap (queue push) but a slow client cannot block it; there is no backpressure/limit on a slow client's queue (memory grows). +- Send is thread-safe by construction: `WebSocket.send` appends the encoded frame to one server-wide deque under `sendQueueLock` and triggers the IO thread (mummy.nim ~L262-311); the IO thread drains it. Per-socket events are serialized by mummy. Because we also send while holding our own lock, per-socket order == gseq order, so no separate broadcaster was needed. 60 s of mixed 3-client load, 13781 mutations, ~36k messages (C): no crash, no reorder, no loss, consistent final views. +- Caveats: `WebSocket` has no `==`/hash, we key a table by its raw bytes (shortcut, works while it is one pointer-sized ref). Everything is serialized by one lock, so throughput is single-core bound (fine here: ~1.2 ms/player move, S). Sending under the lock is cheap (queue push) but a slow client cannot block it; there is no backpressure/limit on a slow client's queue (memory grows). - Pinned to an exact commit (no tags upstream). **Worries for a real VTT** -- Vision is O(rays x walls) per token (culled only by bbox); needs a spatial grid for big maps. cellsTouched (O(bbox cells x poly edges)) is ~15x costlier than the polygon itself and dominates. +- Vision is O(rays x walls) per token (culled only by bbox); needs a spatial grid for big maps. cellsTouched (O(bbox cells x poly edges)) is ~12x costlier than the polygon itself (0.46 vs 0.038 ms, B) and dominates. - Explored grid: 128x128 cells here; explored set sent whole on connect, kept in memory + one SQLite row per cell. Larger maps need run-length/bitmap + per-tile summaries. -- Full `vision` polygon resent on each player move (~3.3 KB of the ~3.5 KB); needs deltas or lower-res polygons. +- Full `vision` polygon resent on each player move (most of the ~3.2-3.7 KB per mover delivery); needs deltas or lower-res polygons. - Cookie = the secret (bearer, no rotation/expiry); invite links in logs/URLs are credentials. HTTPS needed beyond localhost. - Tiles do not update when a door changes (static art; only fog changes); a revealed tile stays visible forever and leaks the whole tile (256 px), not just the explored cells; tile granularity vs exploredCell is a leak/size tradeoff. - Polygon boundary epsilon: ray nudges (1e-4 rad) and inclusive tolerances; tokens right on the boundary are ambiguous (tests use a 0.5 px tolerance). A token standing exactly on a wall cannot move off it; server must keep tokens off walls. diff --git a/prototype-server-vision/devbox.json b/prototype-server-vision/devbox.json index 06c68cb..1856dbf 100644 --- a/prototype-server-vision/devbox.json +++ b/prototype-server-vision/devbox.json @@ -45,7 +45,7 @@ "tools/leaktest.sh" ], "concurrency": [ - "tools/withserver.sh node tools/concurrency.mjs" + "mkdir -p results; D=${DUR:-60}; tools/withserver.sh node tools/concurrency.mjs > results/concurrency-${D}s.log 2>&1; rc=$?; cat results/concurrency-${D}s.log; grep STATS run/test/server.log | awk '{k=$0; sub(/ n=.*/, \"\", k); a[k]=$0} END{for (k in a) print a[k]}' | sort > results/concurrency-${D}s-server.log; exit $rc" ], "faulttest": [ "tools/faulttest.sh" @@ -57,7 +57,7 @@ "tools/withserver.sh node tools/smoke.mjs" ], "bench": [ - "nim c -d:release --hints:off -r -o:run/bench tools/bench.nim" + "mkdir -p results; nim c -d:release --hints:off -r -o:run/bench tools/bench.nim | tee results/bench.log" ] } }, diff --git a/prototype-server-vision/results/bench.log b/prototype-server-vision/results/bench.log new file mode 100644 index 0000000..769d291 --- /dev/null +++ b/prototype-server-vision/results/bench.log @@ -0,0 +1,5 @@ +1 poly (jittered start positions): n=2000 avg=0.038ms worst=0.188ms +6 polys (one 6-token party): n=500 avg=0.207ms worst=0.287ms +1 poly + cellsTouched: n=2000 avg=0.456ms worst=1.222ms +6 polys + cellsTouched: n=300 avg=3.049ms worst=5.144ms +(sink 2063860) diff --git a/prototype-server-vision/results/concurrency-60s-server.log b/prototype-server-vision/results/concurrency-60s-server.log new file mode 100644 index 0000000..ee9d10b --- /dev/null +++ b/prototype-server-vision/results/concurrency-60s-server.log @@ -0,0 +1,10 @@ +STATS bytes/delivery door gm: n=60 avg=44.8 worst=46. +STATS bytes/delivery move-monster A: n=747 avg=145.0 worst=153. +STATS bytes/delivery move-monster B: n=814 avg=147.5 worst=154. +STATS bytes/delivery move-monster gm: n=10300 avg=243.0 worst=252. +STATS bytes/delivery move-player A: n=1711 avg=3678.6 worst=4927. +STATS bytes/delivery move-player B: n=1710 avg=3180.6 worst=4851. +STATS bytes/delivery move-player gm: n=3417 avg=144.7 worst=149. +STATS vision_ms door: n=60 avg=0.192 worst=0.492 +STATS vision_ms move-monster: n=10300 avg=0.000 worst=0.025 +STATS vision_ms move-player: n=3421 avg=1.159 worst=14.023 diff --git a/prototype-server-vision/results/concurrency-60s.log b/prototype-server-vision/results/concurrency-60s.log new file mode 100644 index 0000000..dcd0245 --- /dev/null +++ b/prototype-server-vision/results/concurrency-60s.log @@ -0,0 +1,6 @@ +gm: sent 10364 moves (167/s), acks 10364 (nack 64), recv 24144 msgs 2940 KiB, final gseq 13781, tokens in view 8 +A: sent 1728 moves (28/s), acks 1728 (nack 17), recv 6039 msgs 6259 KiB, final gseq 13777, tokens in view 2 +B: sent 1710 moves (28/s), acks 1710 (nack 0), recv 6079 msgs 5434 KiB, final gseq 13772, tokens in view 1 +latency intent->ack (sender): n=13802 avg=6.33ms p95=11.58ms worst=583.13ms +latency intent->arrival at other clients: n=4917 avg=7.22ms p95=12.89ms worst=583.22ms +concurrency: PASS diff --git a/prototype-server-vision/results/leak-A.log b/prototype-server-vision/results/leak-A.log index f69ffbe..6a4b7ae 100644 --- a/prototype-server-vision/results/leak-A.log +++ b/prototype-server-vision/results/leak-A.log @@ -1,2 +1,2 @@ driver done: 237 actions, 0 unexpected acks, final gseq 217 -leakcheck: 218 gseq groups, A msgs 467, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 0 +leakcheck: 218 gseq groups, subject msgs 467, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 0 diff --git a/prototype-server-vision/results/leak-B.log b/prototype-server-vision/results/leak-B.log index 0235c32..545190c 100644 --- a/prototype-server-vision/results/leak-B.log +++ b/prototype-server-vision/results/leak-B.log @@ -1,2 +1,2 @@ driver done: 237 actions, 0 unexpected acks, final gseq 217 -leakcheck: 218 gseq groups, A msgs 217, tokens seen 3 others, removes 3, tiles 7424 (200:686 403:6738 other:0), explored cells 1114, failures 0 +leakcheck: 218 gseq groups, subject msgs 217, tokens seen 3 others, removes 3, tiles 7424 (200:686 403:6738 other:0), explored cells 1114, failures 0