Files
FFF_vtt_frozen/tools/restart.test.mjs
T
SirStone 1f11779658 test: tie group evidence to passing tests and baseline restart on the as-built server (#36)
- tools/groups.mjs evidence entries now name the exact test, a minimum assertion
  count and the calls its body must keep; groups.test.mjs checks all three.
- tools/evidence.mjs parses the spec reporter log and fails the gate unless every
  registered evidence test ran and passed; test.sh runs it after the Node suite.
- restart.test.mjs snapshots the live as-built world on the first server, then
  compares it to the post-SIGTERM/SIGKILL state (players connect before the GM, so
  the GM's derived encountered grey is computed on both sides).
- Negative controls: a hollowed auth test fails the new evidence check; a planted
  first-load drop of a token's gm prop bucket fails the new restart baseline while
  the old restart-to-restart test passed.
- Refresh the gate evidence (control + 73 mutations incl. s1-s7, 142 node tests).
2026-11-20 21:55:50 +01:00

458 lines
24 KiB
JavaScript

// M3 slice 10 (#25): the "restart" acceptance group (DESIGN 10.1, 13 M3 group 7).
//
// A restart must bring back *identical state*, not just the single feature of one slice. This builds
// a world that exercises every CRUD path M3 has (walls and an open door, tokens with sizes, props in
// all three buckets and statuses, characters with props, a character reveal, a token reveal-all, a
// sighting in the encountered list, explored cells, players and their names), then compares what a
// fresh GM connection and a fresh player connection receive as their full 6.3 resync before and
// after the restart. SIGTERM and SIGKILL are both checked: every acked commit is durable (4.2).
//
// #27: three named players meet the same subjects, and the reveals are per player, so the restart
// group also pins that the persisted `encountered` snapshot is the name *that* player knows. Before
// the fix the reveal SQL had no player predicate: the non-revealed players saw the actual name only
// after the restart. Each player's encountered list is compared before/after AND against the name
// that player may know (from the GM truth), so a leak cannot hide behind two equally wrong snapshots.
import test from 'node:test'
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import { createPlayer, namePlayer, sleep } from './lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
async function gmConnect(origin, gmKey) {
const conn = await openAs(origin, gmKey)
await conn.ws.waitText('hello')
const walls = await conn.ws.waitText('walls')
return { ...conn, sceneId: walls.scene }
}
// Build the world on a running server. Every mutation is acked before the next one, so a kill after
// this returns cannot lose an acked commit.
async function buildWorld(origin, gmKey) {
const gm = await gmConnect(origin, gmKey)
const saved = {}
try {
// Players: a GM plus three named players with keys (their CRUD path is key.* + player.setname).
// Three, because the per-player reveal bug (#27) needs a second and a third encountered list to
// be wrong: one player is revealed to, the others must keep the descriptive name across a
// restart. Their tokens all stand west of the x=700 wall and see the same two subjects.
const alice = await createPlayer(gm.ws)
await namePlayer(origin, alice.key, 'Alice')
saved.alice = alice
const bob = await createPlayer(gm.ws)
await namePlayer(origin, bob.key, 'Bob')
saved.bob = bob
const carol = await createPlayer(gm.ws)
await namePlayer(origin, carol.key, 'Carol')
saved.carol = carol
// A fourth, still unnamed player: the GM roster carries it (`name:null`), players never see it.
await createPlayer(gm.ws)
// A wall and a door; the door is opened (door.set is its own write path).
const wall = await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [700, 0],
b: [700, 900] })
const door = await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [700, 1000],
b: [700, 1400], door: true })
assert.equal(wall.ok, true, JSON.stringify(wall))
assert.equal(door.ok, true, JSON.stringify(door))
assert.equal((await gm.ws.request({ t: 'door.set', scene: gm.sceneId, id: door.id,
open: true })).ok, true)
// Walls r1 (#59): a marked window every sighted player starts in view of, so the restart
// compares a non-empty per-player marker set and the `marker_seen` rows behind it.
const window = await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, preset: 'window',
a: [450, 300], b: [550, 300] })
assert.equal(window.ok, true, JSON.stringify(window))
// The player's own token: vision, explored cells and the encountered list come from it.
const pc = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
pos: [400, 400], descriptive_name: 'a wanderer',
actual_name: 'Wanderer', controller: alice.id,
flags: { vision: true }, radius: 35,
props: { public: { aura: 'cold' }, owner: { hp: 5 },
gm: { secret: 1 } } })
assert.equal(pc.ok, true, JSON.stringify(pc))
// Bob and Carol: sight of their own, at the same subjects. They never own a character, so only a
// reveal can tell them an actual name.
for (const [p, pos] of [[bob, [250, 500]], [carol, [300, 650]]]) {
const sight = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
pos, descriptive_name: 'sight', actual_name: 'Sight',
controller: p.id, flags: { vision: true },
radius: 35 })
assert.equal(sight.ok, true, JSON.stringify(sight))
if (p === bob) saved.ids = { ...(saved.ids ?? {}), bobTok: sight.id }
else saved.ids = { ...(saved.ids ?? {}), carolTok: sight.id }
}
// A monster right next to it: Alice meets it (one encountered entry, grey after it moves away).
const monster = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc',
pos: [500, 400], descriptive_name: 'a goblin',
actual_name: 'Grib' })
assert.equal(monster.ok, true, JSON.stringify(monster))
// A character with props, and a token that figures it (linked tokens carry no names).
const character = await gm.ws.request({ t: 'character.create',
descriptive_name: 'a cloaked figure',
actual_name: 'Lady Vex', owner: alice.id,
props: { public: { rank: 'noble' },
owner: { hp: 9 }, gm: { plot: 'ally' } } })
assert.equal(character.ok, true, JSON.stringify(character))
const linked = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
pos: [560, 400], character_id: character.id,
controller: alice.id })
assert.equal(linked.ok, true, JSON.stringify(linked))
// Props: a set and an unset on the plain token, a set on the character.
assert.equal((await gm.ws.request({ t: 'prop.set', target: 'token', id: pc.id,
bucket: 'public', key: 'light', value: 30 })).ok, true)
assert.equal((await gm.ws.request({ t: 'prop.unset', target: 'token', id: pc.id,
bucket: 'owner', key: 'hp' })).ok, true)
assert.equal((await gm.ws.request({ t: 'prop.set', target: 'character', id: character.id,
bucket: 'public', key: 'banner', value: 'red' })).ok, true)
// Status (GM source) and a resize: two more persisted tables/columns.
assert.equal((await gm.ws.request({ t: 'status.set', id: monster.id,
status: 'stuck' })).ok, true)
assert.equal((await gm.ws.request({ t: 'token.resize', id: monster.id, radius: 28 })).ok, true)
// Per-player reveals: the character's actual name to Alice only, the monster's to Bob only.
// Alice must then keep "a goblin" and Bob "a cloaked figure" - before the fix both flipped to
// the actual name after a restart (#27). reveal-all for a plain token stays all-players.
assert.equal((await gm.ws.request({ t: 'name.reveal', subject: 'character',
id: character.id, player: alice.id })).ok, true)
assert.equal((await gm.ws.request({ t: 'name.reveal', subject: 'token',
id: monster.id, player: bob.id })).ok, true)
assert.equal((await gm.ws.request({ t: 'name.reveal_all', subject: 'token',
id: pc.id })).ok, true)
saved.ids = { ...saved.ids, pc: pc.id, monster: monster.id, character: character.id,
linked: linked.id, wall: wall.id, door: door.id, window: window.id }
gm.ws.close()
} finally {
try { gm.ws.close() } catch {}
}
return saved
}
function count(client, t) {
return client.messages.filter(m => m && m.t === t).length
}
async function waitResync(client, expected) {
// The 6.3 sequence is ordered but arrives asynchronously; wait until every expected part is there.
const deadline = Date.now() + 5000
for (;;) {
const ok = count(client, 'hello') >= 1 && count(client, 'roster') >= 1 &&
count(client, 'token') >= expected.tokens &&
count(client, 'character') >= expected.characters &&
(expected.gm ? count(client, 'walls') >= 1
: count(client, 'encountered') >= 1 && count(client, 'vision') >= 1 &&
count(client, 'explored') >= 1 && count(client, 'marker') >= 1)
if (ok) return
if (Date.now() > deadline) {
throw new Error(`resync incomplete: ${JSON.stringify(client.messages.map(m => m.t))}`)
}
await sleep(5)
}
}
const strip = m => { const { n, ...rest } = m; return rest }
const by = key => (a, b) => String(a[key]).localeCompare(String(b[key]))
// One connection's whole resync, normalized: `n` is per-connection and therefore not state.
async function snapshot(origin, key, expected, isGm) {
const c = await openAs(origin, key)
try {
await waitResync(c.ws, { ...expected, gm: isGm })
const pick = t => c.ws.messages.filter(m => m && m.t === t).map(strip)
const snap = { hello: pick('hello')[0], roster: pick('roster').pop(), tokens: pick('token') }
snap.tokens.sort(by('id'))
snap.roster.players.sort(by('id'))
if (isGm) {
const walls = pick('walls').pop()
snap.walls = walls
snap.walls.walls.sort(by('id'))
snap.characters = pick('character').sort(by('id'))
assert.equal(c.ws.messages.some(m => m.t === 'marker'), false,
'the GM never receives a marker frame (5.8)')
snap.encountered = pick('encountered').map(e => {
e.set.sort(by('id'))
return e
}).sort(by('player'))
} else {
snap.characters = pick('character').sort(by('id'))
snap.encountered = pick('encountered').pop()
snap.encountered.set.sort(by('id'))
snap.vision = pick('vision').pop()
snap.vision.polys.sort(by('id'))
// explored RLE rows are already ordered by cy; keep the payload as the view, not a set.
snap.explored = pick('explored').pop()
// #59: the full marker set, after explored, with this player's own opaque ids.
snap.marker = pick('marker').pop()
snap.marker.set.sort(by('id'))
}
return snap
} finally {
c.ws.close()
await c.ws.closed
}
}
// The name each player may know for a subject, from the fixture's own truth: the character reveal
// went to Alice only, the monster's to Bob only, and the pc's reveal_all covers everyone.
function expectedEncounteredName(who, ids) {
if (who === 'alice') return { [ids.monster]: 'a goblin', [ids.linked]: 'Lady Vex',
[ids.pc]: 'Wanderer' }
return { [ids.monster]: who === 'bob' ? 'Grib' : 'a goblin',
[ids.linked]: 'a cloaked figure', [ids.pc]: 'Wanderer' }
}
// The full before/after comparison: one fresh connection per player and one fresh GM connection.
// #36: players connect first, so their live sight state is computed before the GM's per-player
// `encountered` lists (whose `grey` is a live sight test, not stored state) are read. Connecting
// them only after the GM would compare a refreshed restarted server against an unrefreshed one.
async function snapshotAll(origin, gmKey, players, expected) {
const all = {}
for (const [who, p] of Object.entries(players)) {
// Only the character's owner is sent a `character` record (6.1).
all[who] = await snapshot(origin, p.key,
{ ...expected, characters: who === 'alice' ? 1 : 0 }, false)
}
all.gm = await snapshot(origin, gmKey, expected, true)
return all
}
async function compareAcross(origin, gmKey, players, ids, expected) {
const before = await snapshotAll(origin, gmKey, players, expected)
const beforeGm = before.gm
// The CRUD inventory is not empty: a restart test over an empty world would prove nothing.
assert.ok(beforeGm.walls.walls.length >= 2, 'the wall and the door are there')
assert.equal(beforeGm.walls.walls.find(w => w.id === ids.door).open, true, 'the door is open')
assert.ok(beforeGm.tokens.length >= 5, 'plain, monster, player, linked and sight tokens are there')
assert.ok(beforeGm.characters.length >= 1, 'the character is there')
assert.equal(beforeGm.characters.find(c => c.id === ids.character).props.public.banner, 'red')
assert.equal(beforeGm.tokens.find(t => t.id === ids.monster).radius, 28,
'the resize survived')
assert.ok(beforeGm.tokens.find(t => t.id === ids.monster).statuses
.some(s => s.status === 'stuck' && s.source === 'GM'), 'the GM status survived')
// #27: each player's encountered list holds the name *that* player knows, live.
for (const [who, snap] of Object.entries(before)) {
if (who === 'gm') continue
for (const [id, name] of Object.entries(expectedEncounteredName(who, ids))) {
assert.equal(snap.encountered.set.find(e => e.id === id)?.name, name,
`${who}'s encountered entry for ${id} live`)
}
assert.ok(snap.vision.polys.length >= 1, `${who} has sight`)
assert.ok(snap.explored.rle.length >= 1, `${who} explored something`)
// #59: the marked window is in every sighted player's full set, at its drawn midpoint, under
// an opaque 12-character id of that player's own (never the wall id).
assert.equal(snap.marker.full, true, `${who}'s marker set is a full resync set`)
assert.ok(snap.marker.set.length >= 1, `${who} saw the marked window`)
for (const entry of snap.marker.set) {
assert.deepEqual(entry.pos, [500, 300], `${who}'s marker anchor is the drawn midpoint`)
assert.match(entry.id, /^[A-Za-z0-9_-]{12}$/, `${who}'s marker id is opaque`)
assert.notEqual(entry.id, String(ids.window), `${who}'s marker id is never the wall id`)
}
}
return before
}
// Kill the server that holds the as-built world. SIGKILL is deliberate for the hard variant: every
// ack is sent after COMMIT (4.2), so a hard kill cannot lose an acked mutation.
async function stopWithSignal(s, hard) {
if (hard) {
s.child.kill('SIGKILL')
const deadline = Date.now() + 5000
while (s.child.signalCode === null && s.child.exitCode === null && Date.now() < deadline) {
await sleep(20)
}
}
await stopServer(s)
}
// #36: `before` is the snapshot of the *as-built* world on the first server instance, taken after
// the CRUD and before any restart. The old version took it after a restart, so a field silently
// dropped on the first load was missing from both sides and the deepEqual held.
async function restartAndCompare(stateDir, before, gmKey, players, ids, expected) {
let s = await startServer({ stateDir })
try {
const after = await snapshotAll(s.origin, gmKey, players, expected)
assert.deepEqual(after.gm, before.gm, 'the GM resync after the restart is identical')
for (const who of Object.keys(players)) {
assert.deepEqual(after[who], before[who],
`${who}'s resync after the restart is identical`)
// ... and the absolute truth, so two equally wrong snapshots cannot pass (#27).
for (const [id, name] of Object.entries(expectedEncounteredName(who, ids))) {
assert.equal(after[who].encountered.set.find(e => e.id === id)?.name, name,
`${who}'s encountered entry for ${id} after the restart`)
}
}
} finally {
await stopServer(s)
}
}
// The persisted snapshot is where #27 lived: assert directly that the reveal changed exactly one
// player's row for the revealed subject, and nobody else's.
function dbEncounteredNames(stateDir, entityId) {
const r = spawnSync('sqlite3', [path.join(stateDir, 'state.db'),
`SELECT player_id || '=' || IFNULL(actual_name, '') FROM encountered ` +
`WHERE entity_id = '${entityId}' ORDER BY player_id`], { encoding: 'utf8' })
assert.equal(r.status, 0, r.stderr)
return Object.fromEntries(r.stdout.trim().split('\n').filter(Boolean)
.map(line => { const [id, name] = line.split('='); return [id, name] }))
}
// #59: the persisted marker memory, player id -> marker id, for one wall.
function dbMarkerRows(stateDir, wallId) {
const r = spawnSync('sqlite3', [path.join(stateDir, 'state.db'),
`SELECT player_id || '=' || marker_id FROM marker_seen WHERE wall_id = ${wallId} ` +
`ORDER BY player_id`], { encoding: 'utf8' })
assert.equal(r.status, 0, r.stderr)
return Object.fromEntries(r.stdout.trim().split('\n').filter(Boolean)
.map(line => { const [id, markerId] = line.split('='); return [id, markerId] }))
}
const EXPECTED = { tokens: 5, characters: 1 }
async function restartGroup(hard) {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const players = {}
let s = await startServer({ stateDir })
let saved
let markerRows
let before
try {
saved = await buildWorld(s.origin, gmKey)
players.alice = saved.alice
players.bob = saved.bob
players.carol = saved.carol
// #59: one persisted marker row per player/wall that has seen the window, all distinct per
// player, each an opaque id that is never the wall id. The rows are the restart fixture.
markerRows = dbMarkerRows(stateDir, saved.ids.window)
assert.ok(Object.keys(markerRows).length >= 2,
`the marked window wrote marker_seen rows for the sighted players: ${JSON.stringify(markerRows)}`)
for (const markerId of Object.values(markerRows)) {
assert.match(markerId, /^[A-Za-z0-9_-]{12}$/, 'the persisted marker id is opaque')
assert.notEqual(markerId, String(saved.ids.window), 'the marker id is never the wall id')
}
// #27, asserted against the rows while the server is still up: the monster's actual name was
// revealed to Bob only, so exactly one of the three rows carries it.
const monsterRows = dbEncounteredNames(stateDir, saved.ids.monster)
assert.equal(monsterRows[String(saved.bob.id)], 'Grib')
assert.equal(monsterRows[String(saved.alice.id)], '')
assert.equal(monsterRows[String(saved.carol.id)], '',
'the reveal to Bob did not write Alice\'s or Carol\'s row (#27)')
const linkedRows = dbEncounteredNames(stateDir, saved.ids.linked)
assert.equal(linkedRows[String(saved.alice.id)], 'Lady Vex')
assert.equal(linkedRows[String(saved.bob.id)], '')
assert.equal(linkedRows[String(saved.carol.id)], '',
'the reveal to Alice did not write Bob\'s or Carol\'s row (#27)')
// #36: the baseline is this live server's full resync, built by the CRUD above and never
// reloaded from disk. A field lost when the first server reloads the DB fails the comparison.
before = await compareAcross(s.origin, gmKey, players, saved.ids, EXPECTED)
} finally {
await stopWithSignal(s, hard)
}
try {
await restartAndCompare(stateDir, before, gmKey, players, saved.ids, EXPECTED)
assert.deepEqual(dbMarkerRows(stateDir, saved.ids.window), markerRows,
'the marker_seen rows (player and opaque id) survive the restart unchanged')
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
}
test('restart: full state, all CRUD, before and after SIGTERM', async () => {
await restartGroup(false)
})
test('restart: full state, all CRUD, before and after SIGKILL', async () => {
await restartGroup(true)
})
// #30: a rename must reach the live encountered list, not just the row a restart loads. The wire
// and the DB are asserted to agree before and after a restart, for a plain token and a character,
// and for a player who was never told the actual name.
test('restart: a mid-session rename reaches the live encountered list (#30)', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
let s = await startServer({ stateDir })
let ids = {}
let alice, bob
try {
const gm = await gmConnect(s.origin, gmKey)
alice = await createPlayer(gm.ws)
await namePlayer(s.origin, alice.key, 'Alice')
bob = await createPlayer(gm.ws)
await namePlayer(s.origin, bob.key, 'Bob')
for (const [p, pos] of [[alice, [350, 350]], [bob, [300, 650]]]) {
const t = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', pos,
descriptive_name: 'sight', actual_name: 'Sight',
controller: p.id, flags: { vision: true } })
assert.equal(t.ok, true, JSON.stringify(t))
}
const wolf = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc',
pos: [450, 450], descriptive_name: 'a wolf',
actual_name: 'Fang' })
const char = await gm.ws.request({ t: 'character.create',
descriptive_name: 'a cloaked figure',
actual_name: 'Lady Vex', owner: alice.id })
const linked = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc',
pos: [500, 400], character_id: char.id })
assert.ok(wolf.ok && char.ok && linked.ok)
ids = { wolf: wolf.id, char: char.id, linked: linked.id }
// Both players are connected while the rename happens, so the live frame is what is checked.
const a = await openAs(s.origin, alice.key)
await a.ws.waitText('hello')
const b = await openAs(s.origin, bob.key)
await b.ws.waitText('hello')
await a.ws.waitFor(m => m.t === 'encountered' &&
m.set.some(e => e.id === wolf.id && e.name === 'a wolf'))
await b.ws.waitFor(m => m.t === 'encountered' &&
m.set.some(e => e.id === wolf.id && e.name === 'a wolf'))
let from = a.ws.messages.length
const w = await gm.ws.request({ t: 'token.update', id: wolf.id,
descriptive_name: 'a huge wolf' })
assert.equal(w.ok, true, JSON.stringify(w))
const renamed = await a.ws.waitFor((m, i) => i >= from && m.t === 'encountered' &&
m.set.some(e => e.id === wolf.id))
assert.equal(renamed.set.find(e => e.id === wolf.id).name, 'a huge wolf',
'the live list follows a plain-token rename (#30)')
await b.ws.waitFor(m => m.t === 'encountered' &&
m.set.some(e => e.id === wolf.id && e.name === 'a huge wolf'))
const bFrom = b.ws.messages.length
const c = await gm.ws.request({ t: 'character.update', id: char.id,
descriptive_name: 'a tall stranger' })
assert.equal(c.ok, true, JSON.stringify(c))
// Alice owns the character, so she sees the actual name and the descriptive rename is invisible
// to her; Bob (never told) must see the new descriptive name on the wire, with no restart.
const moved = await b.ws.waitFor((m, i) => i >= bFrom && m.t === 'encountered' &&
m.set.some(e => e.id === linked.id))
assert.equal(moved.set.find(e => e.id === linked.id).name, 'a tall stranger',
'the live list follows a character rename for a player who was not told (#30)')
assert.equal(renamed.set.find(e => e.id === wolf.id).name, 'a huge wolf')
a.ws.close(); b.ws.close(); gm.ws.close()
} finally {
await stopServer(s)
}
try {
s = await startServer({ stateDir })
for (const [key, who] of [[alice.key, 'alice'], [bob.key, 'bob']]) {
const c = await openAs(s.origin, key)
try {
await c.ws.waitFor(m => m.t === 'encountered' && m.full === true)
const e = c.ws.messages.filter(m => m.t === 'encountered').pop()
assert.equal(e.set.find(x => x.id === ids.wolf)?.name, 'a huge wolf',
`${who}: the plain-token rename survives the restart`)
assert.equal(e.set.find(x => x.id === ids.linked)?.name,
who === 'alice' ? 'Lady Vex' : 'a tall stranger',
`${who}: the character rename survives the restart, per player`)
} finally {
c.ws.close()
}
}
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})