Files
FFF_vtt_frozen/tools/leak.mjs
T
SirStone 959412ff09 tools: leak driver, checker and the fault controls (#20)
tools/leak.mjs builds a 27-group scene over the real wire (movement, a closed door,
create/remove, gm_only, a controller hand-over, another player walking in and out, a
wall added and removed, a door push) and records every frame each socket saw, one
group per mutation. tools/leakcheck.nim replays it: the GM socket is ground truth,
the subject's polygons and explored cells are recomputed from geometry.nim, and the
explored set is also probed with a clear-segment sampler. Subjects A and B both pass
with zero failures; the transcripts and logs land in results/.

tools/fault.test.mjs runs the same scenario against a -d:leakfault build for each
fault and asserts the EXACT class set (HIDDEN_TOKEN, GMONLY_TOKEN, WALLDATA,
WITHHELD, OTHER_PLAYER, NO_REMOVE, EXPLORED), plus that the shipped binary carries no
LEAK_FAULT string.

withserver can build a variant with extra -d: flags and pass an env to it; lib.mjs
can name a player out of band, the fixture the player-side tests need until slice 8
brings player.setname (the unnamed gate itself is pinned in tools/tokens.test.mjs).
2026-11-15 09:35:24 +01:00

259 lines
11 KiB
JavaScript

// Leak test driver (DESIGN 10.1, 10.3; M3 slice 5 / #20). Builds a known scene over the real wire,
// then plays a scripted narrative with ONE mutation per group and writes every frame each socket
// received to a JSONL transcript. tools/leakcheck.nim replays it: the GM socket is ground truth,
// the subject's own messages are only ever checked, never trusted.
//
// Groups: a marker line, one action, then "quiescent" (no frame for QUIET ms on any socket). That
// is what lets the checker evaluate a group as one state: every mutation is its own group, so the
// truth after the group is the truth the group's frames describe.
//
// The scenario (4096 px world, 32 px cells, 400 px vision, token radius 20) is built to exercise
// every way a token can enter or leave a player's view:
// - visible at the first resync (M1, and the subject's own token)
// - hidden behind a closed door, revealed by opening it (M2)
// - removed from view by moving away, and re-entering
// - created and removed while in view
// - a `gm_only` token inside LOS that must never appear (M3)
// - a controller change: handed to the subject while out of sight, handed back
// - another player's token walking in and out (A sees B)
// - a wall added and removed while the subject watches (its polygon shrinks and grows)
// - a door closing on a token, which the server pushes aside (5.5)
// - a token that is never within range at all (M4)
import fs from 'node:fs'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { createPlayer, namePlayer, openWs, sleep, projectRoot } from './lib.mjs'
import { signIn } from './withserver.mjs'
const QUIET_MS = 60
const nimblePkgs = () => path.join(process.env.NIMBLE_DIR ?? path.join(projectRoot, '.devbox', 'nimble'), 'pkgs2')
// The checker is compiled once per process (it imports server/geometry.nim through --path in nim.cfg).
let checkerBin = null
export function buildChecker() {
if (checkerBin) return checkerBin
const out = path.join(projectRoot, 'run', 'test', 'leakcheck')
fs.mkdirSync(path.dirname(out), { recursive: true })
const r = spawnSync('nim', ['c', '--hints:off', '-d:release', `--nimblePath:${nimblePkgs()}`,
`-o:${out}`, path.join('tools', 'leakcheck.nim')],
{ cwd: projectRoot, encoding: 'utf8' })
if (r.status !== 0) throw new Error(`nim c tools/leakcheck.nim failed:\n${r.stdout}\n${r.stderr}`)
checkerBin = out
return out
}
export function runChecker(transcript, subject) {
const r = spawnSync(buildChecker(), [transcript, subject], { encoding: 'utf8' })
return { status: r.status, output: `${r.stdout ?? ''}${r.stderr ?? ''}` }
}
// One socket, its received frames, and where the transcript cursor is.
async function connect(origin, key, who, log) {
const { cookie } = await signIn(origin, key)
const ws = await openWs(origin, cookie)
return { who, ws, logged: 0, log }
}
export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen = false }) {
// The transcript is written in group order; the checker needs nothing else.
const lines = []
const log = obj => lines.push(JSON.stringify(obj))
const clients = []
const gm = await connect(origin, gmKey, 'GM', log)
clients.push(gm)
await gm.ws.waitText('hello')
const walls = await gm.ws.waitText('walls')
const scene = walls.scene
let g = 0
let quiesceMs = QUIET_MS
const flush = () => {
// Only now, at a group boundary, do the frames a client received get attributed to the group.
for (const c of clients) {
for (; c.logged < c.ws.messages.length; c.logged++) {
log({ k: 'msg', who: c.who, g, m: c.ws.messages[c.logged] })
}
}
}
async function quiesce() {
const deadline = Date.now() + 5000
let last = -1
let since = Date.now()
for (;;) {
const n = clients.reduce((a, c) => a + c.ws.messages.length, 0)
if (n !== last) { last = n; since = Date.now() }
if (Date.now() - since >= quiesceMs) return
if (Date.now() > deadline) throw new Error('server never went quiet')
await sleep(10)
}
}
async function group(label, fn) {
g++
log({ k: 'group', g, label })
await fn()
await quiesce()
flush()
}
// --- the scene -------------------------------------------------------------------------------
// x = 500 is a wall with a door in the middle (y 400..700): the subject starts west of it.
const wallsToAdd = [
{ a: [500, 0], b: [500, 400], kind: 'wall' },
{ a: [500, 400], b: [500, 700], kind: 'door', open: false },
{ a: [500, 700], b: [500, 1000], kind: 'wall' },
{ a: [1400, 400], b: [1400, 900], kind: 'wall' },
]
const wallIds = []
const addWall = async fields => {
const ack = await gm.ws.request({ t: 'wall.add', scene, ...fields })
if (ack.ok !== true) throw new Error(`wall.add refused: ${JSON.stringify(ack)}`)
wallIds.push(ack.id)
return ack.id
}
const createToken = async (id, fields) => {
const ack = await gm.ws.request({ t: 'token.create', scene, ...fields })
if (ack.ok !== true) throw new Error(`token.create refused: ${JSON.stringify(ack)}`)
ids[id] = ack.id
return ack.id
}
const ids = {}
const move = async (client, id, pos) => {
const ack = await client.ws.request({ t: 'token.move', id, pos })
return ack
}
// Two named players: the naming is the fixture of lib.mjs (player.setname is slice 8).
const playerA = await createPlayer(gm.ws)
const playerB = await createPlayer(gm.ws)
await namePlayer(stateDir, playerA.id, 'Subject A')
await namePlayer(stateDir, playerB.id, 'Player B')
await group('walls', async () => {
for (const w of wallsToAdd) await addWall(w)
})
await group('tokens', async () => {
await createToken('A', { kind: 'pc', pos: [300, 300], descriptive_name: 'A', actual_name: 'A',
controller: playerA.id, flags: { vision: true } })
await createToken('B', { kind: 'pc', pos: [300, 3000], descriptive_name: 'B', actual_name: 'B',
controller: playerB.id, flags: { vision: true } })
await createToken('M1', { kind: 'npc', pos: [400, 200], descriptive_name: 'a wolf',
actual_name: 'Fang' })
await createToken('M2', { kind: 'npc', pos: [560, 550], descriptive_name: 'a guard',
actual_name: 'Captain Vex' })
await createToken('M3', { kind: 'npc', pos: [350, 350], descriptive_name: 'a shadow',
actual_name: 'The Hidden', gm_only: true })
await createToken('M4', { kind: 'item', pos: [3500, 3500], descriptive_name: 'a chest',
actual_name: 'The Vault' })
})
const A = await connect(origin, playerA.key, 'A', log)
clients.push(A)
await A.ws.waitText('hello')
await group('connect subject', async () => { await sleep(0) })
const B = await connect(origin, playerB.key, 'B', log)
clients.push(B)
await B.ws.waitText('hello')
await group('connect other', async () => { await sleep(0) })
// A walks from (300,300) to just west of the door.
await group('A walks to the door', async () => {
expectAck(await move(A, ids.A, [350, 600]), true)
})
await group('A at the door', async () => {
expectAck(await move(A, ids.A, [350, 620]), true)
})
await group('M2 is hidden behind the closed door', async () => { await sleep(0) })
await group('GM opens the door', async () => {
const ack = await gm.ws.request({ t: 'door.set', scene, id: wallIds[1], open: true })
if (ack.ok !== true) throw new Error(`door.set refused: ${JSON.stringify(ack)}`)
})
await group('A steps through the door', async () => {
expectAck(await move(A, ids.A, [560, 600]), true)
})
await group('A steps into the room', async () => {
expectAck(await move(A, ids.A, [600, 640]), true)
})
await group('GM moves M1 into the room', async () => {
expectAck(await move(gm, ids.M1, [700, 700]), true)
})
await group('GM creates a token in view', async () => {
await createToken('N1', { kind: 'item', pos: [520, 700], descriptive_name: 'a lamp',
actual_name: 'Lantern' })
})
await group('GM removes it', async () => {
const ack = await gm.ws.request({ t: 'token.remove', id: ids.N1 })
if (ack.ok !== true) throw new Error(`token.remove refused: ${JSON.stringify(ack)}`)
})
await group('GM hides M1', async () => {
const ack = await gm.ws.request({ t: 'token.update', id: ids.M1, gm_only: true })
if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`)
})
await group('GM unhides M1', async () => {
const ack = await gm.ws.request({ t: 'token.update', id: ids.M1, gm_only: false })
if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`)
})
await group('GM hands M1 to the subject', async () => {
const ack = await gm.ws.request({ t: 'token.update', id: ids.M1, controller: playerA.id })
if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`)
})
await group('GM moves the subject-owned token far away', async () => {
expectAck(await move(gm, ids.M1, [3000, 3000]), true)
})
await group('GM hands M1 back to the GM', async () => {
const ack = await gm.ws.request({ t: 'token.update', id: ids.M1, controller: null })
if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`)
})
await group('GM walks the other player in', async () => {
expectAck(await move(gm, ids.B, [420, 640]), true)
})
await group('GM walks the other player out', async () => {
expectAck(await move(gm, ids.B, [420, 1500]), true)
})
await group('GM adds a wall in the subject sight', async () => {
await addWall({ a: [400, 900], b: [900, 900], kind: 'wall' })
})
await group('GM removes it again', async () => {
const ack = await gm.ws.request({ t: 'wall.remove', scene, id: wallIds[wallIds.length - 1] })
if (ack.ok !== true) throw new Error(`wall.remove refused: ${JSON.stringify(ack)}`)
})
await group('GM puts M2 on the door line', async () => {
expectAck(await move(gm, ids.M2, [500, 600]), true)
})
await group('GM closes the door: the server pushes M2 aside', async () => {
const ack = await gm.ws.request({ t: 'door.set', scene, id: wallIds[1], open: false })
if (ack.ok !== true) throw new Error(`door.set refused: ${JSON.stringify(ack)}`)
})
await group('A walks away from the door', async () => {
expectAck(await move(A, ids.A, [560, 950]), true)
})
await group('A walks further south', async () => {
expectAck(await move(A, ids.A, [560, 1300]), true)
})
await group('end', async () => { await sleep(0) })
// Let anything still queued arrive, then close politely.
await sleep(100)
flush()
if (!keepOpen) for (const c of clients) c.ws.close()
fs.mkdirSync(path.dirname(transcript), { recursive: true })
fs.writeFileSync(transcript, lines.join('\n') + '\n')
return { transcript, groups: g, walls: wallIds, tokens: ids }
}
function expectAck(ack, ok) {
const got = ack.ok === true
if (got !== ok) throw new Error(`unexpected ack: ${JSON.stringify(ack)}`)
return ack
}