prototype-server-vision: phase 3 (integration fixes, leaktest, concurrency, bench, README)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-01 23:03:24 +01:00
co-authored by Claude Sonnet 5.5
parent 013c29e4da
commit 26d7079084
17 changed files with 466 additions and 80 deletions
+7
View File
@@ -16,3 +16,10 @@
- Non-owned move => `error` (not moveAck: server pos of an unseen token would leak).
- `by` = "gm"|"A"|"B" (conn role name).
- Smoke: `PORT=8088 devbox run -- node tools/smoke.mjs` (server+nginx up, run/invites.txt written by server).
## Phase 3
- BUG (client): reconnect did not reset state (stale tokens/explored/sprites); server already resends hello+state on every connect. FIX: reducer resets on `hello`, main.ts clears sprites/masks/doors/pending (tiles kept). Reducer test added.
- 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.
+91
View File
@@ -0,0 +1,91 @@
# Server-authoritative vision prototype (throwaway)
Question: can the server alone decide what each player sees (tokens, fog, map tiles) so a modified client learns nothing hidden? Stack: Nim + mummy (WS/HTTP), SQLite, nginx (static + `X-Accel-Redirect` tiles), Vite + TS + Pixi v8 client.
## Run (everything through devbox)
```
devbox run gen # data/scene.json + data/tiles/*.png (deterministic, hand-authored layout)
devbox run client # npm install, reducer test, tsc + vite build -> client/dist
PORT=8088 devbox run server # :9000 backend, prints invite links, writes run/invites.txt
PORT=8088 devbox run nginx # public port; separate terminal
```
`PORT` (default 8080) is only the public nginx port and the origin printed in invite links. On the dev box 8080 is taken by unrelated docker, hence 8088 in all examples.
Open the 3 invite links (gm, A, B) each in a **separate browser or profile**. The link sets cookie `sid=<secret>` (HttpOnly, SameSite=Strict) and redirects to `/`; the WS and tile requests authenticate by that cookie. One cookie jar = one identity, so two links in the same profile overwrite each other. Same cookie in two tabs = same player (shared vision, both connections synced).
Browser rendering was NOT verified (no browser in the build environment): only HTTP/WS behaviour is scripted-tested (served `/`, JS bundle 200, join -> cookie, WS through nginx, tiles).
## Tests
| cmd | what |
|---|---|
| `devbox run test` | regen map + `nimble test` (geometry: visibility, moves, cells, seed sanity) |
| `devbox run client` | includes client reducer test (`npm run check`, incl. reconnect reset) |
| `PORT=8088 devbox run smoke` | fresh DB, server+nginx, auth/cookie/tile/steal/garbage checks |
| `PORT=8088 devbox run leaktest` | fresh DB; A walks ~240 steps through rooms, corridor, open/closed doors while GM + B act; Nim checker (`tools/leakcheck.nim`) replays `run/leak-transcript.jsonl` |
| `PORT=8088 devbox run concurrency` | 60 s (`DUR=` secs) A, B, GM(6 monsters + doors) at 20-50 ms per token |
| `devbox run bench` | vision microbench |
`smoke/leaktest/concurrency` start/stop their own server+nginx via `tools/withserver.sh` (wipes `run/state.db`). Server stats print on stop into `run/server.log`.
### Leak test asserts
Ground truth = GM socket (tokens + doors per gseq). A's expected vision/explored is recomputed with `geometry.nim`, never from A's own messages. Per gseq:
- (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.
- (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.
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).
### 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.
## 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 |
Bytes per delivery (only recipients that got something):
| 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 |
"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.
## Findings
**Worked**
- Server-only filtering is simple under one global lock: validate -> mutate -> recompute -> persist -> per-connection diff -> send. Players never receive walls/doors/other tokens; leak test finds nothing.
- Per-connection `known` map gives correct enter/leave (`token`/`remove`) and a fresh connection gets full state; clients reset on `hello`.
- Tile gating via nginx `internal` + `X-Accel-Redirect` after Nim checks explored cells; `/_tiles/` unreachable directly.
- Moves: inclusive segment test blocks squeezing through shared vertices; non-owned/malformed moves get `error` (not an ack, an ack would echo the position of an unseen token).
**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).
- 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.
- 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.
- 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.
- Fog masks are Graphics that grow unbounded (explored rects re-tessellated); needs baking to a RenderTexture. Pixi `Text` per token is heavy vs `BitmapText` at scale.
- Browser rendering (fog masks, drag, reconnect visuals) is unverified: only the reducer and HTTP/WS paths were tested.
- Timing trusts a single machine/loopback; latencies exclude real network and client render.
+4 -2
View File
@@ -80,6 +80,8 @@ function onMsg(m: any) {
const fresh = apply(s, m);
switch (m.t) {
case 'hello':
for (const c of sprites.values()) c.destroy({ children: true });
sprites.clear(); pending.clear(); visionM.clear(); exploredM.clear(); doorsG.clear(); // tiles kept: explored only grows
fit();
if (s.role === 'gm') { dim.visible = black.visible = false; const n = Math.ceil(s.w / s.tileSize), k = Math.ceil(s.h / s.tileSize); for (let y = 0; y < k; y++) for (let x = 0; x < n; x++) loadTile(x + '_' + y); }
else { for (const g of [dim, black]) g.clear().rect(0, 0, s.w, s.h).fill(0x000000); dim.alpha = 0.6; }
@@ -104,7 +106,7 @@ function onMsg(m: any) {
function connect() {
ws = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws`);
ws.onopen = () => { conn = 'open'; status(); };
ws.onclose = () => { conn = 'closed (retry 2s)'; status(); setTimeout(connect, 2000); }; // shortcut: no state reset on reconnect, assumes server resends full state/hello; verify
ws.onclose = () => { conn = 'closed (retry 2s)'; status(); setTimeout(connect, 2000); }; // state reset on hello; server resends everything
ws.onmessage = (e) => { onMsg(JSON.parse(e.data)); status(); };
}
@@ -140,7 +142,7 @@ cv.addEventListener('pointerdown', (e) => {
const t = s.tokens.get(id)!;
if (canDrag(t) && Math.hypot(p[0] - c.x, p[1] - c.y) <= R) { drag = { id, dx: c.x - p[0], dy: c.y - p[1], last: 0 }; dragging.set(id, true); return; }
}
if (s.role === 'gm') { const d = pickDoor(p); if (d) { send({ t: 'door', id: d, open: !s.walls.get(d)!.open }); return; } }
if (s.role === 'gm') { const d = pickDoor(p); if (d !== null) { send({ t: 'door', id: d, open: !s.walls.get(d)!.open }); return; } }
pan = { x: e.clientX - world.x, y: e.clientY - world.y };
});
cv.addEventListener('pointermove', (e) => {
@@ -34,3 +34,14 @@ test('tilesOfCells', () => {
assert.deepEqual([...tilesOfCells([[8, 0]], g)], ['1_0']);
assert.deepEqual([...tilesOfCells([[0, 0]], { ...g, cell: 1024 })].length, 4); // cell spans 2x2 tiles
});
test('hello resets state (reconnect)', () => {
const s = newState();
apply(s, { t: 'hello', gseq: 1, role: 'player', tokens: ['a'], world: { w: 4096, h: 4096 }, tileSize: 512, exploredCell: 64 });
apply(s, { t: 'token', gseq: 2, id: 'a', name: 'A', kind: 'pc', pos: [5, 6], mine: true });
apply(s, { t: 'explored', gseq: 3, cells: [[0, 0]] });
apply(s, { t: 'hello', gseq: 9, role: 'player', tokens: ['a'], world: { w: 4096, h: 4096 }, tileSize: 512, exploredCell: 64 });
assert.equal(s.tokens.size, 0);
assert.equal(s.explored.size, 0);
assert.equal(s.gseq, 9);
});
+2 -1
View File
@@ -25,7 +25,8 @@ export const newState = (): State => ({
export function apply(s: State, m: Msg): V2[] | undefined {
s.gseq = m.gseq;
switch (m.t) {
case 'hello':
case 'hello': // server resends full state after hello: start clean (reconnect)
Object.assign(s, newState(), { gseq: m.gseq });
s.role = m.role; s.owned = m.tokens; s.w = m.world.w; s.h = m.world.h;
s.tileSize = m.tileSize; s.cell = m.exploredCell;
break;
@@ -1,17 +0,0 @@
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
@@ -1,23 +0,0 @@
# The nginx.conf in this folder is automatically generated from nginx.template
# To modify your NGINX config, edit the nginx.template file
events {}
http{
server {
listen 8081;
listen [::]:8081;
server_name localhost;
root ../../../devbox.d/web;
error_log error.log error;
access_log access.log;
client_body_temp_path temp/client_body;
proxy_temp_path temp/proxy;
fastcgi_temp_path temp/fastcgi;
uwsgi_temp_path temp/uwsgi;
scgi_temp_path temp/scgi;
index index.html;
server_tokens off;
}
}
@@ -1,23 +0,0 @@
# The nginx.conf in this folder is automatically generated from nginx.template
# To modify your NGINX config, edit the nginx.template file
events {}
http{
server {
listen $NGINX_WEB_PORT;
listen [::]:$NGINX_WEB_PORT;
server_name $NGINX_WEB_SERVER_NAME;
root $NGINX_WEB_ROOT;
error_log error.log error;
access_log access.log;
client_body_temp_path temp/client_body;
proxy_temp_path temp/proxy;
fastcgi_temp_path temp/fastcgi;
uwsgi_temp_path temp/uwsgi;
scgi_temp_path temp/scgi;
index index.html;
server_tokens off;
}
}
@@ -1,10 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Hello World!</title>
</head>
<body>
Hello World!
</body>
</html>
+12
View File
@@ -35,6 +35,18 @@
"mkdir -p run/temp client/dist",
"sed \"s/NGX_PORT/${PORT:-8080}/\" nginx/nginx.conf > run/nginx.conf",
"nginx -p \"$PWD/\" -c run/nginx.conf -e run/error.log"
],
"leaktest": [
"tools/withserver.sh sh -c 'node tools/leak.mjs && nim c -d:release --hints:off -o:run/leakcheck tools/leakcheck.nim && run/leakcheck'"
],
"concurrency": [
"tools/withserver.sh node tools/concurrency.mjs"
],
"smoke": [
"tools/withserver.sh node tools/smoke.mjs"
],
"bench": [
"nim c -d:release --hints:off -r -o:run/bench tools/bench.nim"
]
}
},
+4 -4
View File
@@ -51,7 +51,7 @@ proc add(s: var Stat, v: float) = inc s.n; s.sum += v; s.worst = max(s.worst, v)
proc printStats() =
for k, s in vstat: echo &"STATS vision_ms {k}: n={s.n} avg={s.sum / s.n.float:.3f} worst={s.worst:.3f}"
for k, s in bstat: echo &"STATS bytes/mutation client={k}: n={s.n} avg={s.sum / s.n.float:.1f} worst={s.worst:.0f}"
for k, s in bstat: echo &"STATS bytes/delivery {k}: n={s.n} avg={s.sum / s.n.float:.1f} worst={s.worst:.0f}"
stdout.flushFile
# shortcut: WebSocket has no ==/hash and private fields; key by raw bytes, fine while the layout is plain POD
@@ -135,11 +135,11 @@ proc finish(ev: Ev, kind: string, visMs: float, mover: Conn = nil) =
vstat.mgetOrPut(kind, Stat()).add visMs
var line = &"MUT gseq={gseq} {kind} vision_ms={visMs:.3f}"
for c in conns.values:
bstat.mgetOrPut(c.role, Stat()).add c.bytes.float
if c.bytes > 0: bstat.mgetOrPut(kind & " " & c.role, Stat()).add c.bytes.float # only recipients that got something
line.add &" {c.role}:{c.bytes}B"
echo line
inc nMut
if nMut mod 100 == 0: printStats()
if nMut mod 5000 == 0: printStats()
stdout.flushFile
proc handleMove(c: Conn, m: JsonNode) =
@@ -166,7 +166,7 @@ proc handleMove(c: Conn, m: JsonNode) =
if roles.hasKey(id): persistCells(id)
db.exec(sql"COMMIT")
c.send("moveAck", %*{"reqId": reqId, "ok": true, "pos": pt(np)})
finish(Ev(door: -1, moved: id, by: c.role, reqId: reqId), "move", visMs, c)
finish(Ev(door: -1, moved: id, by: c.role, reqId: reqId), (if roles.hasKey(id): "move-player" else: "move-monster"), visMs, c)
proc handleDoor(c: Conn, m: JsonNode) =
if c.role != "gm": c.err("gm only"); return
+29
View File
@@ -0,0 +1,29 @@
## Vision microbench: nim c -d:release -r tools/bench.nim (devbox run bench)
import std/[json, monotimes, times, strformat]
import geometry
let j = parseFile("data/scene.json")
var walls: seq[Wall]
for w in j["walls"]:
walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat), door: w["door"].getBool, open: w["open"].getBool)
let r = j["visionRadius"].getFloat
var ps: seq[Vec]
for t in j["tokens"]: ps.add (t["pos"][0].getFloat, t["pos"][1].getFloat)
proc bench(name: string, n: int, f: proc(i: int)) =
var sum, worst = 0.0
for i in 0 ..< n:
let t0 = getMonoTime(); f(i)
let ms = (getMonoTime() - t0).inNanoseconds.float / 1e6
sum += ms; worst = max(worst, ms)
echo &"{name}: n={n} avg={sum / n.float:.3f}ms worst={worst:.3f}ms"
var sink = 0
bench("1 poly (jittered start positions)", 2000, proc(i: int) =
let p = ps[i mod 8]; sink += visibilityPolygon((p.x + float(i mod 50), p.y), walls, r).len)
bench("6 polys (one 6-token party)", 500, proc(i: int) =
for k in 0 ..< 6:
let p = ps[k + 2]; sink += visibilityPolygon((p.x + float(i mod 50), p.y), walls, r).len)
bench("1 poly + cellsTouched", 2000, proc(i: int) =
let p = ps[i mod 8]; sink += cellsTouched(visibilityPolygon((p.x + float(i mod 50), p.y), walls, r), 32).len)
bench("6 polys + cellsTouched", 300, proc(i: int) =
for k in 0 ..< 6:
let p = ps[k + 2]; sink += cellsTouched(visibilityPolygon((p.x + float(i mod 50), p.y), walls, r), 32).len)
echo "(sink ", sink, ")"
@@ -0,0 +1,82 @@
// A, B, GM hammer the server concurrently (moves every 20-50 ms per token, GM toggles doors), then compare views to fresh connections.
import { connect, sleep } from './lib.mjs'
const DUR = (process.env.DUR ?? 60) * 1000
const fails = []
const check = (c, m) => { if (!c) { fails.push(m); console.log('FAIL', m) } }
const sendT = new Map(), lat = { self: [], other: [] }
function mkState(name) {
const st = { name, toks: new Map(), doors: new Map(), explored: new Set(), poly: '[]', last: -1, backwards: 0, msgs: 0, bytes: 0, errors: 0, sent: 0, acks: 0, nack: 0, pending: new Set(), req: 0 }
st.on = (m, b) => {
st.msgs++; st.bytes += b
if (m.gseq < st.last) st.backwards++
st.last = m.gseq
switch (m.t) {
case 'hello': st.toks.clear(); st.explored.clear(); st.doors.clear(); st.poly = '[]'; break
case 'walls': for (const w of m.walls) if (w.door) st.doors.set(w.id, w.open); break
case 'door': st.doors.set(m.id, m.open); break
case 'vision': st.poly = JSON.stringify(m.polys); break
case 'explored': for (const c of m.cells) st.explored.add(c + ''); break
case 'token':
st.toks.set(m.id, m.pos + '')
if (m.reqId !== undefined) { const t0 = sendT.get(m.by + ':' + m.reqId); if (t0 && m.by !== st.name) lat.other.push(performance.now() - t0) }
break
case 'remove': st.toks.delete(m.id); break
case 'moveAck': st.acks++; st.pending.delete(m.reqId); if (!m.ok) st.nack++; st.onAck?.(m); break
case 'error': st.errors++; break
}
}
return st
}
const S = { gm: mkState('gm'), A: mkState('A'), B: mkState('B') }
const C = {}
for (const r of ['gm', 'A', 'B']) C[r] = await connect(r, S[r].on)
// random walkers: [client, token id, box]
const walkers = [['A', 'A', [300, 300, 980, 980], [400, 400]], ['B', 'B', [300, 2100, 980, 2780], [400, 2200]],
['gm', 'M1', [300, 300, 980, 980], [900, 900]], ['gm', 'M2', [1600, 300, 2250, 980], [1920, 640]], ['gm', 'M3', [2870, 300, 3530, 980], [3400, 500]],
['gm', 'M4', [300, 2100, 980, 2780], [900, 2700]], ['gm', 'M5', [1600, 2100, 2250, 2780], [1920, 2400]], ['gm', 'M6', [2870, 2100, 3530, 2780], [3200, 2400]]]
let running = true
const rnd = (a, b) => a + Math.random() * (b - a)
const loops = walkers.map(async ([who, id, [x0, y0, x1, y1], p]) => {
const st = S[who]
while (running) {
p = [Math.min(x1, Math.max(x0, p[0] + rnd(-40, 40))), Math.min(y1, Math.max(y0, p[1] + rnd(-40, 40)))]
const r = ++st.req; st.pending.add(r); st.sent++
sendT.set(who + ':' + r, performance.now())
st.onAck = m => { const t0 = sendT.get(who + ':' + m.reqId); if (t0) lat.self.push(performance.now() - t0); if (!m.ok) p = m.pos } // blocked: resync to server pos (shortcut: GM shares one onAck, only the last walker resyncs)
C[who].ws.send(JSON.stringify({ t: 'move', reqId: r, id, pos: p }))
await sleep(rnd(20, 50))
}
})
const doorLoop = (async () => { let o = true; while (running) { await sleep(rnd(1000, 3000)); o = !o; C.gm.ws.send(JSON.stringify({ t: 'door', id: 10, open: o })); C.gm.ws.send(JSON.stringify({ t: 'door', id: 27, open: !o })) } })()
const t0 = performance.now()
await sleep(DUR)
running = false
await Promise.all([...loops, doorLoop])
for (let i = 0; i < 100 && Object.values(S).some(s => s.pending.size); i++) await sleep(100)
await sleep(500)
// quiesced: compare against fresh connections
const F = {}
for (const r of ['gm', 'A', 'B']) { F[r] = mkState(r); await connect(r, F[r].on) }
const sig = m => JSON.stringify([...m].sort())
for (const r of ['gm', 'A', 'B']) {
const s = S[r], f = F[r]
check(s.pending.size === 0, `${r}: ${s.pending.size} moves never acked`)
check(s.sent === s.acks, `${r}: sent ${s.sent} acks ${s.acks}`)
check(s.backwards === 0, `${r}: gseq went backwards ${s.backwards}x`)
check(s.errors === 0, `${r}: ${s.errors} error msgs`)
check(sig(s.toks) === sig(f.toks), `${r}: token view != fresh snapshot`)
check(sig(s.doors) === sig(f.doors), `${r}: doors != fresh`)
check(s.poly === f.poly, `${r}: vision != fresh`)
check(sig(s.explored) === sig(f.explored), `${r}: explored != fresh (${s.explored.size} vs ${f.explored.size})`)
}
const q = (a, p) => a.length ? a.slice().sort((x, y) => x - y)[Math.min(a.length - 1, Math.floor(a.length * p))] : NaN
const st = a => `n=${a.length} avg=${(a.reduce((x, y) => x + y, 0) / a.length).toFixed(2)}ms p95=${q(a, 0.95).toFixed(2)}ms worst=${Math.max(...a).toFixed(2)}ms`
const secs = (performance.now() - t0) / 1000
for (const r of ['gm', 'A', 'B']) console.log(`${r}: sent ${S[r].sent} moves (${(S[r].sent / secs).toFixed(0)}/s), acks ${S[r].acks} (nack ${S[r].nack}), recv ${S[r].msgs} msgs ${(S[r].bytes / 1024).toFixed(0)} KiB, final gseq ${S[r].last}, tokens in view ${S[r].toks.size}`)
console.log('latency intent->ack (sender):', st(lat.self))
console.log('latency intent->arrival at other clients:', st(lat.other))
console.log(fails.length ? `FAILED ${fails.length}` : 'concurrency: PASS')
process.exit(fails.length ? 1 : 0)
+63
View File
@@ -0,0 +1,63 @@
// Leak test driver: scripted walk of A, GM + B as ground truth/noise. Writes run/leak-transcript.jsonl; tools/leakcheck.nim verifies it.
// Everything is sequential (one actor at a time) so every tile sweep sees a quiescent server at a known gseq.
import fs from 'node:fs'
import { O, connect, sleep } from './lib.mjs'
const out = fs.createWriteStream(new URL('../run/leak-transcript.jsonl', import.meta.url))
const log = o => out.write(JSON.stringify(o) + '\n')
let gmG = 0
const acks = new Map(), req = { A: 0, B: 0, GM: 0 }
const mk = who => connect(who === 'GM' ? 'gm' : who, m => {
log({ k: 'msg', who, m })
if (who === 'GM') gmG = m.gseq
if (m.t === 'moveAck') acks.get(who + m.reqId)?.(m)
})
const [gm, A, B] = [await mk('GM'), await mk('A'), await mk('B')]
const cl = { GM: gm, A, B }
const pos = { A: [400, 400], B: [400, 2200], M1: [900, 900], M2: [1920, 640], M5: [1920, 2400] }
const owner = id => (id === 'A' || id === 'B' ? id : 'GM')
const mv = (id, p) => new Promise(res => { const w = owner(id), r = ++req[w]; acks.set(w + r, res); cl[w].ws.send(JSON.stringify({ t: 'move', reqId: r, id, pos: p })) })
const tiles = Object.keys(Array.from({ length: 256 })).map(i => [i % 16, Math.floor(i / 16)])
async function sweep(label) {
await sleep(40)
const g = gmG
for (let i = 0; i < tiles.length; i += 32)
await Promise.all(tiles.slice(i, i + 32).map(async ([x, y]) => {
const r = await fetch(`${O}/tiles/${x}_${y}.png`, { headers: { Cookie: A.cookie } })
await r.arrayBuffer(); log({ k: 'tile', g, x, y, s: r.status, label })
}))
}
const acts = []
const cur = { ...pos }
const walk = (id, to, expectFail = false) => {
const [x, y] = cur[id], d = Math.hypot(to[0] - x, to[1] - y), n = Math.ceil(d / 40)
for (let i = 1; i <= n; i++) acts.push({ id, p: [x + (to[0] - x) * i / n, y + (to[1] - y) * i / n], fail: expectFail && i === n })
if (!expectFail) cur[id] = to
}
const door = (id, open) => acts.push({ door: [id, open] })
const sw = label => acts.push({ sweep: label })
sw('start')
walk('B', [700, 2300])
walk('A', [400, 800]); walk('A', [800, 800]); sw('M1 in view')
walk('A', [800, 640]); walk('A', [1000, 640]); walk('A', [1500, 640])
walk('A', [1560, 640], true); sw('closed door blocks')
walk('M2', [1700, 640]); sw('M2 behind closed door')
door(10, true); sw('door open'); walk('A', [1700, 640]); walk('M2', [1900, 700]); walk('A', [1900, 640]); sw('M2 close')
walk('M2', [2200, 300]); sw('M2 left'); walk('M1', [900, 640]); walk('M1', [1200, 640]); sw('M1 into corridor')
walk('A', [1920, 900]); walk('A', [1920, 1900]); sw('corridor')
door(27, false); sw('door 27 closed'); walk('A', [1920, 2030]); walk('A', [1920, 2060], true); sw('blocked'); door(27, true); sw('door 27 open')
walk('A', [1920, 2300]); sw('R5')
walk('B', [700, 2430]); walk('B', [1400, 2430]); walk('B', [1700, 2430]); sw('B visible?'); walk('B', [1000, 2430]); sw('B away')
walk('A', [1920, 2500]); sw('M5 in view'); walk('M5', [2200, 2700]); sw('M5 away'); walk('A', [1700, 2700]); sw('end')
let nA = 0, bad = 0
for (const a of acts) {
if (a.sweep) { await sweep(a.sweep); continue }
if (a.door) { cl.GM.ws.send(JSON.stringify({ t: 'door', id: a.door[0], open: a.door[1] })); await sleep(40); continue }
const m = await mv(a.id, a.p)
if (m.ok === !!a.fail) { bad++; console.log('unexpected ack', a, m) }
if (a.id === 'A' && ++nA % 5 === 0) await sweep('walk'); else await sleep(15)
}
await sleep(200)
for (const c of [gm, A, B]) c.ws.close()
out.end()
console.log(`driver done: ${acts.length} actions, ${bad} unexpected acks, final gseq ${gmG}`)
process.exit(bad ? 1 : 0)
+132
View File
@@ -0,0 +1,132 @@
## Leak checker: replays run/leak-transcript.jsonl. Ground truth = GM socket (tokens+doors per gseq);
## A's vision/explored are recomputed with geometry.nim, never taken from A's own messages.
import std/[json, tables, sets, strutils]
import geometry
type Side = enum Out, Amb, In
var fails = 0
proc fail(s: string) =
inc fails
if fails <= 20: echo "FAIL ", s
# boundary is ambiguous in inside(): In/Out only if the point and its 0.5px neighbours agree
proc side(poly: seq[Vec], p: Vec): Side =
var n = 0
for d in [(0.0, 0.0), (0.5, 0.0), (-0.5, 0.0), (0.0, 0.5), (0.0, -0.5)]:
if poly.inside((p.x + d[0], p.y + d[1])): inc n
if n == 0: Out elif n == 5: In else: Amb
proc vec(j: JsonNode): Vec = (j[0].getFloat, j[1].getFloat)
const banned = ["walls", "door", "open", "a", "b", "segments", "segs", "wall"]
const allowed = ["hello", "vision", "explored", "token", "remove", "moveAck"]
proc scan(j: JsonNode, t: string) =
if j.kind == JObject:
for k, v in j:
if k in banned: fail "A msg " & t & " has wall-like key " & k
scan(v, t)
elif j.kind == JArray:
for v in j: scan(v, t)
var gm, am: seq[JsonNode]
var tiles: seq[JsonNode]
for line in lines("run/leak-transcript.jsonl"):
let j = parseJson(line)
if j["k"].getStr == "tile": tiles.add j
elif j["who"].getStr == "GM": gm.add j["m"]
elif j["who"].getStr == "A": am.add j["m"]
# B transcript is deliberately unused: B is only noise
let radius = parseFile("data/scene.json")["visionRadius"].getFloat
var walls: seq[Wall]
var truth: Table[string, Vec]
var tileSize, cell, cw: int
var firstG: Table[int, int] # explored cell -> gseq it first became explored (independent)
var view: Table[string, Vec] # what A has been told
var aExp: HashSet[int]
var ai, removes, groups, expN: int
var seen: HashSet[string]
proc finalize(g: int) =
inc groups
let poly = visibilityPolygon(truth["A"], walls, radius)
for (ix, iy) in cellsTouched(poly, cell.float):
if ix >= 0 and iy >= 0 and ix < cw and iy < cw and (iy * cw + ix) notin firstG:
firstG[iy * cw + ix] = g; inc expN
while ai < am.len and am[ai]["gseq"].getInt <= g:
let m = am[ai]; inc ai
let t = m["t"].getStr
if t == "error": fail "A got error " & $m
if t notin allowed: fail "A got forbidden type " & t; continue
if t == "moveAck": continue
scan(m, t)
if m["gseq"].getInt != g: fail "A msg gseq " & $m["gseq"] & " not in GM log (group " & $g & ")"
if t notin ["token", "remove"] and "\"B\"" in $m: fail "B mentioned in " & $m
case t
of "hello": (if m["tokens"] != %["A"]: fail "hello tokens " & $m["tokens"])
of "token":
let id = m["id"].getStr
if id notin truth: fail "unknown token " & id; continue
if vec(m["pos"]) != truth[id]: fail "token " & id & " pos != truth at g=" & $g
if m["mine"].getBool != (id == "A"): fail "mine flag " & id
if id != "B" and m{"by"}.getStr == "B": fail "B leak via by on " & id
if id != "A" and side(poly, truth[id]) == Out: fail "LEAK token " & id & " outside A vision at g=" & $g
view[id] = vec(m["pos"]); seen.incl id
of "remove":
let id = m["id"].getStr
if id notin view: fail "remove of unknown " & id
if id in truth and side(poly, truth[id]) == In: fail "remove of token still visible " & id
view.del id; inc removes
of "vision":
let ps = m["polys"]
if ps.len != 1 or ps[0].len != poly.len: fail "vision shape at g=" & $g; continue
for i in 0 ..< poly.len:
let p = ps[0][i]
if abs(p[0].getFloat - poly[i].x) > 1e-6 or abs(p[1].getFloat - poly[i].y) > 1e-6: fail "vision vertex differs at g=" & $g; break
of "explored":
for c in m["cells"]:
let k = c[1].getInt * cw + c[0].getInt
if firstG.getOrDefault(k, int.high) > g: fail "LEAK explored cell not yet explored " & $c
aExp.incl k
else: discard
if aExp.len != expN: fail "explored count at g=" & $g & ": A " & $aExp.len & " expected " & $expN
for id, p in truth:
let s = side(poly, p)
if s == Amb and id != "A": continue
let want = id == "A" or s == In
if want != (id in view): fail "view mismatch " & id & " want=" & $want & " at g=" & $g
elif want and view[id] != p: fail "view pos stale " & id & " at g=" & $g
var curG = -1
for m in gm:
let g = m["gseq"].getInt
if curG >= 0 and g != curG: finalize(curG)
curG = g
case m["t"].getStr
of "hello": tileSize = m["tileSize"].getInt; cell = m["exploredCell"].getInt; cw = (m["world"]["w"].getInt + cell - 1) div cell
of "walls":
for w in m["walls"]: walls.add Wall(a: vec(w["a"]), b: vec(w["b"]), door: w["door"].getBool, open: w["open"].getBool)
of "door": walls[m["id"].getInt].open = m["open"].getBool
of "token": truth[m["id"].getStr] = vec(m["pos"])
else: discard
finalize(curG)
if ai < am.len: fail "A messages after last GM gseq: " & $am[ai]
var n200, n403, nOther: int
for t in tiles:
let g = t["g"].getInt
var exp = false
let per = tileSize div cell
for cy in t["y"].getInt * per ..< (t["y"].getInt + 1) * per:
for cx in t["x"].getInt * per ..< (t["x"].getInt + 1) * per:
if firstG.getOrDefault(cy * cw + cx, int.high) <= g: exp = true
let s = t["s"].getInt
if s == 200: inc n200 elif s == 403: inc n403 else: inc nOther
if s != (if exp: 200 else: 403): fail "tile " & $t["x"] & "_" & $t["y"] & " g=" & $g & " (" & t["label"].getStr & ") status " & $s & " expected " & (if exp: "200" else: "403")
# coverage: the scripted path must actually exercise enter/leave
for id in ["M1", "M2", "B", "M5"]:
if id notin seen: fail "scenario never showed A token " & id
if removes < 3: fail "only " & $removes & " removes"
echo "leakcheck: ", groups, " gseq groups, A msgs ", am.len, ", tokens seen ", seen.len - 1, " others, removes ", removes,
", tiles ", tiles.len, " (200:", n200, " 403:", n403, " other:", nOther, "), explored cells ", expN, ", failures ", fails
quit(if fails > 0: 1 else: 0)
+16
View File
@@ -0,0 +1,16 @@
// shared by leak.mjs / concurrency.mjs. Node 22 WebSocket (undici) accepts {headers}.
import fs from 'node:fs'
export const O = `http://localhost:${process.env.PORT ?? 8080}`
export const inv = Object.fromEntries(fs.readFileSync(new URL('../run/invites.txt', import.meta.url), 'utf8').trim().split('\n').map(l => l.split(' ')))
export const sleep = ms => new Promise(r => setTimeout(r, ms))
export const login = async role => (await fetch(inv[role], { redirect: 'manual' })).headers.get('set-cookie').split(';')[0]
// resolves once hello+initial state arrived (socket quiet for 300 ms)
export async function connect(role, onMsg) {
const cookie = await login(role)
const ws = new WebSocket(O.replace('http', 'ws') + '/ws', { headers: { Cookie: cookie } })
let last = Date.now()
ws.onmessage = e => { last = Date.now(); onMsg(JSON.parse(e.data), Buffer.byteLength(e.data)) }
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej })
while (Date.now() - last < 300) await sleep(50)
return { ws, cookie }
}
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# usage: tools/withserver.sh cmd... fresh DB, build, start server+nginx (PORT, default 8080), run cmd, stop both (SIGINT => server prints STATS)
cd "$(dirname "$0")/.." || exit 1
PORT=${PORT:-8080}; export PORT
mkdir -p run/temp client/dist
rm -f run/state.db* run/invites.txt
nimble build -d:release -y >/dev/null || exit 1
sed "s/NGX_PORT/$PORT/" nginx/nginx.conf > run/nginx.conf
./server > run/server.log 2>&1 & S=$!
nginx -p "$PWD/" -c run/nginx.conf -e run/error.log > run/nginx.out 2>&1 & N=$!
trap 'kill -INT $S; sleep 1; kill $N 2>/dev/null' EXIT
for i in $(seq 50); do [ -s run/invites.txt ] && curl -s -o /dev/null "localhost:$PORT/" && break; sleep 0.2; done
"$@"