Files
FFF_vtt_frozen/tools/persistence.test.mjs
T

652 lines
34 KiB
JavaScript

// M3 slice 6 (#21): explored persistence. The 10.3 "persistence" group: the chunked store round
// trips (a fresh connection's full RLE is the grid the server accumulated), the grid is per player,
// it survives a SIGTERM restart and a SIGKILL, a wall that changes sight is persisted, the DB holds
// chunks rather than cells, a mutation's write cost stays inside the 4.3 budget, and a fixture DB
// from the previous schema version (4, the slice-5 server) migrates under the real binary.
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import { DatabaseSync } from 'node:sqlite'
import { createPlayer, namePlayer, sleep } from './lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
const CELL = 32
const cellOf = (x, y) => `${Math.floor(x / CELL)},${Math.floor(y / CELL)}`
const sorted = set => [...set].sort()
// `explored {full:true, rle}` -> the set of cells it names (DESIGN 6.1).
function rleCells(msg) {
assert.equal(msg.full, true, 'a snapshot is a full explored frame')
const cells = new Set()
for (const row of msg.rle) {
const cy = row[0]
for (let i = 1; i + 1 < row.length; i += 2) {
const x0 = row[i]
const len = row[i + 1]
for (let k = 0; k < len; k++) cells.add(`${x0 + k},${cy}`)
}
}
return cells
}
// The chunk format from the other side (server/explored.nim): 64x64 cells, row-major, LSB first.
function decodeChunks(rows, cols, rowsInScene) {
const cells = new Set()
for (const row of rows) {
const buf = row.bits
for (let ly = 0; ly < 64; ly++) {
for (let lx = 0; lx < 64; lx++) {
const bit = ly * 64 + lx
if ((buf[bit >> 3] & (1 << (bit & 7))) === 0) continue
const x = Number(row.cx) * 64 + lx
const y = Number(row.cy) * 64 + ly
if (x < cols && y < rowsInScene) cells.add(`${x},${y}`)
}
}
}
return cells
}
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, scene: walls.scene }
}
async function namedPlayer(origin, gm, name) {
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, name)
return player
}
// A vision token controlled by `owner`, so that player has sight (and an explored grid).
async function visionToken(gm, owner, pos) {
const ack = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos,
descriptive_name: 'a wanderer', actual_name: 'Wanderer',
controller: owner.id, flags: { vision: true } })
assert.equal(ack.ok, true, JSON.stringify(ack))
return ack.id
}
// Move a token along a path. Every leg is split into steps of at most 380 px: the 5.5 step cap is
// the token's vision radius (400 px by default), so a straight leg may be refused as over-cap.
async function walk(ws, id, start, points) {
let from = start
for (const to of points) {
const legs = Math.max(1, Math.ceil(Math.hypot(to[0] - from[0], to[1] - from[1]) / 380))
for (let k = 1; k <= legs; k++) {
const pos = [from[0] + (to[0] - from[0]) * k / legs, from[1] + (to[1] - from[1]) * k / legs]
const ack = await ws.request({ t: 'token.move', id, pos })
assert.equal(ack.ok, true, `move to ${pos}: ${JSON.stringify(ack)}`)
}
from = to
}
}
// The explored grid as a *fresh* connection sees it on resync (6.3): the product's own view of what
// the server holds. Closing keeps the 4-connections-per-player cap (4.3) out of the way.
async function exploredSnapshot(origin, player) {
const conn = await openAs(origin, player.key)
try {
await conn.ws.waitText('hello')
const frame = await conn.ws.waitText('explored')
return rleCells(frame)
} finally {
conn.ws.close()
}
}
function readChunks(dbPath) {
const db = new DatabaseSync(dbPath)
try {
db.exec('PRAGMA busy_timeout=5000')
return db.prepare('SELECT player_id, cx, cy, bits, length(bits) AS size, typeof(bits) AS kind ' +
'FROM explored_chunk ORDER BY player_id, cy, cx').all()
} finally {
db.close()
}
}
test('explored round trip: a fresh connection gets the whole grid the server accumulated', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const s = await startServer({ stateDir })
try {
const gm = await gmConnect(s.origin, gmKey)
const alice = await namedPlayer(s.origin, gm, 'Alice')
const tok = await visionToken(gm, alice, [200, 200])
const p = await openAs(s.origin, alice.key)
await p.ws.waitText('hello')
await p.ws.waitFor(m => m.t === 'token' && m.id === tok)
const e1 = rleCells(await p.ws.waitText('explored'))
assert.ok(e1.has(cellOf(200, 200)), 'the starting position is explored')
assert.ok(!e1.has(cellOf(3000, 200)), 'a far cell is not explored yet')
await walk(p.ws, tok, [200, 200], [[500, 200], [900, 200], [1300, 200]])
const e2 = await exploredSnapshot(s.origin, alice)
for (const c of e1) assert.ok(e2.has(c), `the earlier cell ${c} is still there`)
assert.ok(e2.has(cellOf(1300, 200)), 'the walked-to area is explored')
assert.ok(e2.size > e1.size, 'the grid only grows')
assert.equal(gm.ws.messages.filter(m => m.t === 'explored').length, 0,
'the GM never receives an explored frame (3.1)')
p.ws.close(); gm.ws.close()
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('explored is strictly per player, before and after a restart', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
let s = await startServer({ stateDir })
let alice, bob, before
try {
const gm = await gmConnect(s.origin, gmKey)
alice = await namedPlayer(s.origin, gm, 'Alice')
bob = await namedPlayer(s.origin, gm, 'Bob')
const aliceTok = await visionToken(gm, alice, [200, 200])
const bobTok = await visionToken(gm, bob, [3800, 3800])
const a = await openAs(s.origin, alice.key)
await a.ws.waitText('hello')
await a.ws.waitText('explored')
const b = await openAs(s.origin, bob.key)
await b.ws.waitText('hello')
await b.ws.waitText('explored')
await walk(a.ws, aliceTok, [200, 200], [[500, 200], [900, 200]])
await walk(b.ws, bobTok, [3800, 3800], [[3500, 3800], [3100, 3800]])
before = { alice: await exploredSnapshot(s.origin, alice),
bob: await exploredSnapshot(s.origin, bob) }
assert.ok(before.alice.has(cellOf(900, 200)))
assert.ok(!before.alice.has(cellOf(3100, 3800)), 'Alice never gets Bob\'s cells (Q9)')
assert.ok(before.bob.has(cellOf(3100, 3800)))
assert.ok(!before.bob.has(cellOf(900, 200)))
a.ws.close(); b.ws.close(); gm.ws.close()
} finally {
await stopServer(s)
}
s = await startServer({ stateDir })
try {
const after = { alice: await exploredSnapshot(s.origin, alice),
bob: await exploredSnapshot(s.origin, bob) }
assert.deepEqual(sorted(after.alice), sorted(before.alice))
assert.deepEqual(sorted(after.bob), sorted(before.bob))
assert.ok(!after.alice.has(cellOf(3100, 3800)), 'still strictly per player after the restart')
assert.match(s.log(), /explored_loaded players=2 chunks=[1-9]/, s.log())
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('restart: every player\'s explored area is identical before and after (SIGTERM)', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
let s = await startServer({ stateDir })
let alice, before
try {
const gm = await gmConnect(s.origin, gmKey)
alice = await namedPlayer(s.origin, gm, 'Alice')
const tok = await visionToken(gm, alice, [200, 200])
const p = await openAs(s.origin, alice.key)
await p.ws.waitText('hello')
await p.ws.waitText('explored')
await walk(p.ws, tok, [200, 200], [[500, 200], [500, 500], [900, 500], [1300, 900], [1700, 1300]])
before = await exploredSnapshot(s.origin, alice)
assert.ok(before.has(cellOf(200, 200)), 'the start area was explored')
assert.ok(before.has(cellOf(1700, 1300)), 'the end area was explored')
p.ws.close(); gm.ws.close()
} finally {
await stopServer(s)
}
s = await startServer({ stateDir })
try {
const after = await exploredSnapshot(s.origin, alice)
assert.deepEqual(sorted(after), sorted(before))
// The start is more than one vision radius from the last position, so these cells cannot come
// from recomputing sight: they are the loaded chunks.
assert.ok(after.has(cellOf(200, 200)))
assert.match(s.log(), /explored_loaded players=1 chunks=[1-9]/, s.log())
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('restart: the explored grid survives a SIGKILL', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
let s = await startServer({ stateDir })
let alice, before
try {
const gm = await gmConnect(s.origin, gmKey)
alice = await namedPlayer(s.origin, gm, 'Alice')
const tok = await visionToken(gm, alice, [400, 400])
const p = await openAs(s.origin, alice.key)
await p.ws.waitText('hello')
await p.ws.waitText('explored')
await walk(p.ws, tok, [400, 400], [[800, 400], [1200, 800], [1600, 1200]])
before = await exploredSnapshot(s.origin, alice)
// The ack of the last move is sent after COMMIT (4.2), so a hard kill loses nothing.
s.child.kill('SIGKILL')
const deadline = Date.now() + 5000
while (s.child.signalCode === null && s.child.exitCode === null && Date.now() < deadline) {
await sleep(20)
}
} finally {
await stopServer(s)
}
s = await startServer({ stateDir })
try {
const after = await exploredSnapshot(s.origin, alice)
assert.deepEqual(sorted(after), sorted(before))
assert.ok(after.has(cellOf(400, 400)))
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('a wall removal\'s newly explored cells are persisted, even after the wall comes back', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const s = await startServer({ stateDir })
try {
const gm = await gmConnect(s.origin, gmKey)
const alice = await namedPlayer(s.origin, gm, 'Alice')
// The wall goes in before Alice's token exists: explored only grows (5.1), so a token created
// on the far side first would legitimately have explored it already.
// A wall at x = 500 hides everything to the right of Alice (her circle reaches x = 600).
// Endpoints stay off the exact 64-gon rays: a ray through a wall endpoint is the documented
// boundary ambiguity of 5.4, not something this test is about.
const wall = await gm.ws.request({ t: 'wall.add', scene: gm.scene, a: [500, 50], b: [500, 4000],
kind: 'wall' })
assert.equal(wall.ok, true, JSON.stringify(wall))
const tok = await visionToken(gm, alice, [200, 200])
const p = await openAs(s.origin, alice.key)
await p.ws.waitText('hello')
await p.ws.waitText('token')
await p.ws.waitText('explored')
const hidden = await exploredSnapshot(s.origin, alice)
assert.ok(hidden.has(cellOf(200, 200)))
assert.ok(!hidden.has(cellOf(590, 200)), 'the wall keeps the right side unexplored')
assert.equal((await gm.ws.request({ t: 'wall.remove', scene: gm.scene, id: wall.id })).ok, true)
// the player's own delta: the cells removal revealed (6.1 `explored {full:false}`)
await p.ws.waitFor(m => m.t === 'explored' && m.full === false)
const revealed = await exploredSnapshot(s.origin, alice)
assert.ok(revealed.has(cellOf(590, 200)), 'removing the wall revealed and persisted the right side')
// Put the wall back: the right side is out of sight again, so only the store can still have it.
assert.equal((await gm.ws.request({ t: 'wall.add', scene: gm.scene, a: [500, 50], b: [500, 4000],
kind: 'wall' })).ok, true)
await sleep(150)
const afterReplace = await exploredSnapshot(s.origin, alice)
assert.deepEqual(sorted(afterReplace), sorted(revealed))
assert.ok(afterReplace.has(cellOf(590, 200)), 'explored never un-explores (5.1)')
// and a restart serves the same grid
await stopServer(s)
const s2 = await startServer({ stateDir })
try {
const after = await exploredSnapshot(s2.origin, alice)
assert.deepEqual(sorted(after), sorted(revealed))
assert.ok(after.has(cellOf(590, 200)))
} finally {
await stopServer(s2)
}
p.ws.close(); gm.ws.close()
} finally {
try { await stopServer(s) } catch {}
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('the store holds 512-byte chunks, and they decode to exactly the explored grid', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const s = await startServer({ stateDir })
try {
const gm = await gmConnect(s.origin, gmKey)
const alice = await namedPlayer(s.origin, gm, 'Alice')
const tok = await visionToken(gm, alice, [400, 400])
const p = await openAs(s.origin, alice.key)
await p.ws.waitText('hello')
await p.ws.waitText('explored')
await walk(p.ws, tok, [400, 400], [[800, 400], [1200, 400]])
const grid = await exploredSnapshot(s.origin, alice)
const rows = readChunks(s.dbPath)
assert.ok(rows.length > 0, 'something was stored')
// 4096 px / 32 px = 128x128 cells = 2x2 chunks: a chunk, not a cell per row (DESIGN 4.4).
assert.ok(rows.length <= 4, `at most 4 chunk rows for this map, got ${rows.length}`)
assert.ok(grid.size > rows.length * 2, 'many cells per row')
for (const row of rows) {
assert.equal(row.size, 512, 'a chunk is 64x64 cells = 512 B')
assert.equal(row.kind, 'blob')
}
// The independent decode agrees with the grid the product sends.
assert.deepEqual(sorted(decodeChunks(rows, 128, 128)), sorted(grid))
p.ws.close(); gm.ws.close()
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('write timing: a move\'s ack stays inside the 4.3 lock budget with explored writes on', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const s = await startServer({ stateDir })
try {
const gm = await gmConnect(s.origin, gmKey)
const alice = await namedPlayer(s.origin, gm, 'Alice')
// On the ring, so the first move is not a teleport across the map (5.5's step cap).
const tok = await visionToken(gm, alice, [2900, 2000])
const p = await openAs(s.origin, alice.key)
await p.ws.waitText('hello')
await p.ws.waitText('explored')
const latencies = []
// Under the 6.4 burst (100): 70 moves around a ring (each ~80 px, inside the 400 px cap), every
// one entering a new area and therefore writing its own chunks.
for (let i = 0; i < 70; i++) {
const ang = 2 * Math.PI * i / 70
const pos = [2000 + 900 * Math.cos(ang), 2000 + 900 * Math.sin(ang)]
const t0 = Date.now()
const ack = await p.ws.request({ t: 'token.move', id: tok, pos })
assert.equal(ack.ok, true, JSON.stringify(ack))
latencies.push(Date.now() - t0)
}
latencies.sort((x, y) => x - y)
const avg = latencies.reduce((a, b) => a + b, 0) / latencies.length
const p99 = latencies[Math.floor(latencies.length * 0.99)]
console.log(` move ack with explored writes: avg ${avg.toFixed(2)} ms, p99 ${p99} ms, ` +
`max ${latencies[latencies.length - 1]} ms over ${latencies.length} moves`)
// DESIGN 4.3: the revisit trigger is a measured p99 > 50 ms; one chunk upsert per move must not
// approach the accepted ~20 ms commit tail.
assert.ok(avg < 20, `avg ack ${avg} ms`)
assert.ok(p99 <= 50, `p99 ack ${p99} ms`)
assert.ok(readChunks(s.dbPath).length > 0)
p.ws.close(); gm.ws.close()
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
// A DB exactly as the slice-5 server (#20) left it: schema version 4, DDL copied from that build, one
// GM, one named player with a key and one vision token. The real binary must migrate it to version 5.
const V4_DDL = `
CREATE TABLE schema_migration (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL);
CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT NOT NULL);
CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT UNIQUE, role TEXT NOT NULL CHECK (role IN ('gm', 'player')), colour TEXT NOT NULL, created_at TEXT NOT NULL);
CREATE UNIQUE INDEX player_single_gm ON player(role) WHERE role = 'gm';
CREATE TABLE player_key (player_id INTEGER PRIMARY KEY REFERENCES player(id) ON DELETE CASCADE, secret TEXT NOT NULL, created_at TEXT NOT NULL);
CREATE TABLE session (id INTEGER PRIMARY KEY, player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, token_hash TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL, last_seen TEXT NOT NULL);
CREATE INDEX session_player ON session(player_id);
CREATE TABLE scene (id INTEGER PRIMARY KEY, name TEXT NOT NULL, w REAL NOT NULL, h REAL NOT NULL, tile_size INTEGER NOT NULL, cell INTEGER NOT NULL, grid_size REAL NOT NULL, vision_radius_default REAL NOT NULL, token_radius_default REAL NOT NULL, art_version INTEGER NOT NULL, active INTEGER NOT NULL DEFAULT 1, next_wall_id INTEGER NOT NULL DEFAULT 1, extra TEXT NOT NULL DEFAULT '{}');
CREATE TABLE wall (scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, id INTEGER NOT NULL, ax REAL NOT NULL, ay REAL NOT NULL, bx REAL NOT NULL, by REAL NOT NULL, kind TEXT NOT NULL CHECK (kind IN ('wall', 'door')), open INTEGER NOT NULL DEFAULT 0 CHECK (open IN (0, 1)), flags TEXT NOT NULL DEFAULT '{}', PRIMARY KEY (scene_id, id));
CREATE TABLE entity (id TEXT PRIMARY KEY, scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, kind TEXT NOT NULL, descriptive_name TEXT NOT NULL, actual_name TEXT NOT NULL, x REAL NOT NULL, y REAL NOT NULL, radius REAL, owner_player_id INTEGER REFERENCES player(id) ON DELETE SET NULL, gm_only INTEGER NOT NULL DEFAULT 0 CHECK (gm_only IN (0, 1)), vision_radius REAL, flags TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL);
INSERT INTO schema_migration VALUES (1, 'meta', '2026-11-15T00:00:00Z'), (2, 'auth', '2026-11-15T00:00:00Z'), (3, 'world', '2026-11-15T00:00:00Z'), (4, 'tokens', '2026-11-15T00:00:00Z');
INSERT INTO scene (id, name, w, h, tile_size, cell, grid_size, vision_radius_default, token_radius_default, art_version, active, next_wall_id, extra) VALUES (1, 'Scene', 4096, 4096, 32, 32, 0, 400, 20, 1, 1, 1, '{}');
INSERT INTO player (id, name, role, colour, created_at) VALUES (1, 'GM', 'gm', '#6b7280', '2026-11-15T00:00:00Z');
INSERT INTO player (id, name, role, colour, created_at) VALUES (2, 'Alice', 'player', '#2563eb', '2026-11-15T00:00:00Z');
INSERT INTO player_key (player_id, secret, created_at) VALUES (1, 'GM72-GM72-GM72-GM72-GM72', '2026-11-15T00:00:00Z');
INSERT INTO player_key (player_id, secret, created_at) VALUES (2, 'ALIC-ALIC-ALIC-ALIC-ALIC', '2026-11-15T00:00:00Z');
INSERT INTO entity (id, scene_id, kind, descriptive_name, actual_name, x, y, owner_player_id, gm_only, vision_radius, flags, created_at) VALUES ('tok000000001', 1, 'pc', 'a wanderer', 'Wanderer', 400, 400, 2, 0, NULL, '{"vision": true}', '2026-11-15T00:00:00Z');
PRAGMA user_version = 4;
`
test('migration: a schema-4 DB (fixture) migrates under the real binary to the latest schema', async () => { const stateDir = makeStateDir()
const dbPath = `${stateDir}/state.db`
const fixture = new DatabaseSync(dbPath)
try {
fixture.exec(V4_DDL)
assert.equal(Number(fixture.prepare('PRAGMA user_version').get().user_version), 4)
assert.equal(fixture.prepare("SELECT count(*) AS n FROM sqlite_master WHERE name = 'explored_chunk'")
.get().n, 0)
} finally {
fixture.close()
}
const s = await startServer({ stateDir })
try {
assert.match(s.log(), /db_ready .*schema_version=8 applied=4/, s.log())
// The old data is served unchanged through the product surface.
const alice = { id: 2, key: 'ALIC-ALIC-ALIC-ALIC-ALIC' }
const conn = await openAs(s.origin, alice.key)
try {
const hello = await conn.ws.waitText('hello')
assert.equal(hello.role, 'player')
assert.equal(hello.me.name, 'Alice')
const tok = await conn.ws.waitFor(m => m.t === 'token' && m.id === 'tok000000001')
assert.deepEqual(tok.pos, [400, 400])
assert.equal(tok.name, 'a wanderer')
// no explored chunks existed in a version-4 DB: the first resync is empty
const explored = await conn.ws.waitText('explored')
assert.equal(explored.full, true)
// no chunks were stored in version 4, so this grid was rebuilt from the walls on connect
assert.ok(rleCells(explored).has(cellOf(400, 400)))
} finally {
conn.ws.close()
}
const db = new DatabaseSync(dbPath)
try {
assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 8)
assert.deepEqual(db.prepare('SELECT version, name FROM schema_migration ORDER BY version').all()
.map(r => [Number(r.version), r.name]),
[[1, 'meta'], [2, 'auth'], [3, 'world'], [4, 'tokens'], [5, 'explored'],
[6, 'token details'], [7, 'characters'], [8, 'wall record']])
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM explored_chunk').get().n), 0)
assert.equal(db.prepare('SELECT name FROM player WHERE id = 2').get().name, 'Alice')
// step 8's data hook gave the schema-4 token its height
assert.deepEqual(JSON.parse(db.prepare("SELECT props_gm FROM entity WHERE id = 'tok000000001'").get().props_gm),
{ height: 1.8 })
} finally {
db.close()
}
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
// A DB exactly as the schema-7 build (#23) left it: every table of steps 1..7, two legacy wall
// kinds (one wall carrying a meaningless `open`, two doors with their stored state), a token with
// empty props, a linked token with a hand-set height/eye_height, and two characters, one with a
// hand-set height. Step 8 must rebuild `wall`, drop `kind`, add `marker_seen` and backfill only
// the missing heights.
const V7_DDL = `
CREATE TABLE schema_migration (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL);
CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT NOT NULL);
CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT UNIQUE, role TEXT NOT NULL CHECK (role IN ('gm', 'player')), colour TEXT NOT NULL, created_at TEXT NOT NULL);
CREATE UNIQUE INDEX player_single_gm ON player(role) WHERE role = 'gm';
CREATE TABLE player_key (player_id INTEGER PRIMARY KEY REFERENCES player(id) ON DELETE CASCADE, secret TEXT NOT NULL, created_at TEXT NOT NULL);
CREATE TABLE session (id INTEGER PRIMARY KEY, player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, token_hash TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL, last_seen TEXT NOT NULL);
CREATE INDEX session_player ON session(player_id);
CREATE TABLE scene (id INTEGER PRIMARY KEY, name TEXT NOT NULL, w REAL NOT NULL, h REAL NOT NULL, tile_size INTEGER NOT NULL, cell INTEGER NOT NULL, grid_size REAL NOT NULL, vision_radius_default REAL NOT NULL, token_radius_default REAL NOT NULL, art_version INTEGER NOT NULL, active INTEGER NOT NULL DEFAULT 1, next_wall_id INTEGER NOT NULL DEFAULT 1, extra TEXT NOT NULL DEFAULT '{}');
CREATE TABLE wall (scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, id INTEGER NOT NULL, ax REAL NOT NULL, ay REAL NOT NULL, bx REAL NOT NULL, by REAL NOT NULL, kind TEXT NOT NULL CHECK (kind IN ('wall', 'door')), open INTEGER NOT NULL DEFAULT 0 CHECK (open IN (0, 1)), flags TEXT NOT NULL DEFAULT '{}', PRIMARY KEY (scene_id, id));
CREATE TABLE entity (id TEXT PRIMARY KEY, scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, kind TEXT NOT NULL, descriptive_name TEXT NOT NULL, actual_name TEXT NOT NULL, x REAL NOT NULL, y REAL NOT NULL, radius REAL, owner_player_id INTEGER REFERENCES player(id) ON DELETE SET NULL, gm_only INTEGER NOT NULL DEFAULT 0 CHECK (gm_only IN (0, 1)), vision_radius REAL, flags TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL, props_public TEXT NOT NULL DEFAULT '{}', props_owner TEXT NOT NULL DEFAULT '{}', props_gm TEXT NOT NULL DEFAULT '{}', character_id TEXT REFERENCES character(id), reveal_all INTEGER NOT NULL DEFAULT 0 CHECK (reveal_all IN (0, 1)));
CREATE TABLE explored_chunk (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, cx INTEGER NOT NULL, cy INTEGER NOT NULL, bits BLOB NOT NULL CHECK (length(bits) = 512), PRIMARY KEY (player_id, scene_id, cx, cy));
CREATE TABLE entity_status (entity_id TEXT NOT NULL REFERENCES entity(id) ON DELETE CASCADE, status TEXT NOT NULL CHECK (status IN ('stuck', 'squeezed')), source TEXT NOT NULL CHECK (source IN ('walls', 'GM')), PRIMARY KEY (entity_id, status, source));
CREATE TABLE character (id TEXT PRIMARY KEY, owner_player_id INTEGER NOT NULL REFERENCES player(id), descriptive_name TEXT NOT NULL, actual_name TEXT NOT NULL, reveal_all INTEGER NOT NULL DEFAULT 0 CHECK (reveal_all IN (0, 1)), props_public TEXT NOT NULL DEFAULT '{}', props_owner TEXT NOT NULL DEFAULT '{}', props_gm TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL);
CREATE INDEX character_owner ON character(owner_player_id);
CREATE TABLE name_reveal (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, subject_id TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY (player_id, subject_id));
CREATE TABLE encountered (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, entity_id TEXT NOT NULL, character_id TEXT, descriptive_name TEXT NOT NULL, actual_name TEXT, created_at TEXT NOT NULL, PRIMARY KEY (player_id, entity_id));
CREATE INDEX encountered_character ON encountered(character_id);
INSERT INTO schema_migration VALUES (1, 'meta', '2026-11-15T00:00:00Z'), (2, 'auth', '2026-11-15T00:00:00Z'), (3, 'world', '2026-11-15T00:00:00Z'), (4, 'tokens', '2026-11-15T00:00:00Z'), (5, 'explored', '2026-11-15T00:00:00Z'), (6, 'token details', '2026-11-15T00:00:00Z'), (7, 'characters', '2026-11-15T00:00:00Z');
INSERT INTO scene (id, name, w, h, tile_size, cell, grid_size, vision_radius_default, token_radius_default, art_version, active, next_wall_id, extra) VALUES (1, 'Scene', 4096, 4096, 32, 32, 0, 400, 20, 1, 1, 5, '{}');
INSERT INTO player (id, name, role, colour, created_at) VALUES (1, 'GM', 'gm', '#6b7280', '2026-11-15T00:00:00Z');
INSERT INTO player (id, name, role, colour, created_at) VALUES (2, 'Alice', 'player', '#2563eb', '2026-11-15T00:00:00Z');
INSERT INTO player_key (player_id, secret, created_at) VALUES (2, 'ALIC-ALIC-ALIC-ALIC-ALIC', '2026-11-15T00:00:00Z');
INSERT INTO wall (scene_id, id, ax, ay, bx, by, kind, open, flags) VALUES
(1, 1, 0, 0, 4096, 0, 'wall', 0, '{"note":"north"}'),
(1, 2, 10, 10, 100, 10, 'wall', 1, '{}'),
(1, 3, 100, 100, 400, 100, 'door', 1, '{"a":1}'),
(1, 4, 500, 500, 900, 500, 'door', 0, '{}');
INSERT INTO character (id, owner_player_id, descriptive_name, actual_name, created_at, props_gm) VALUES
('char000000001', 1, 'Alice', 'Alice', '2026-11-15T00:00:00Z', '{}'),
('char000000002', 1, 'Bob', 'Bob', '2026-11-15T00:00:00Z', '{"height":1.5}');
INSERT INTO entity (id, scene_id, kind, descriptive_name, actual_name, x, y, owner_player_id, flags, created_at, props_gm, character_id) VALUES
('tok000000001', 1, 'pc', 'a wanderer', 'Wanderer', 400, 400, 2, '{"vision": true}', '2026-11-15T00:00:00Z', '{}', NULL),
('tok000000002', 1, 'pc', '', '', 800, 800, 2, '{"vision": true}', '2026-11-15T00:00:00Z', '{"height":2.5,"eye_height":2.0}', 'char000000001');
PRAGMA user_version = 7;
`
const V7_WALLS = [
{ id: 1, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both',
player_marker: 0, door: 0, open: 0, secret: 0, locked: 0, height: null, label: null,
flags: '{"note":"north"}' },
{ id: 2, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both',
player_marker: 0, door: 0, open: 0, secret: 0, locked: 0, height: null, label: null, flags: '{}' },
{ id: 3, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both',
player_marker: 0, door: 1, open: 1, secret: 0, locked: 0, height: null, label: null,
flags: '{"a":1}' },
{ id: 4, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both',
player_marker: 0, door: 1, open: 0, secret: 0, locked: 0, height: null, label: null, flags: '{}' },
]
function readWallRows(db) {
return db.prepare(`SELECT id, thickness, position, blocks_sight, blocks_movement, sight_dir,
player_marker, door, open, secret, locked, height, label, flags
FROM wall ORDER BY id`).all()
.map(r => ({ ...r, id: Number(r.id), thickness: Number(r.thickness) }))
}
function readProps(db, table) {
return Object.fromEntries(db.prepare(`SELECT id, props_gm FROM ${table} ORDER BY id`).all()
.map(r => [r.id, JSON.parse(r.props_gm)]))
}
test('migration: a schema-7 wall/token/character fixture maps to typed storage and backfills height', async () => {
const stateDir = makeStateDir()
const dbPath = `${stateDir}/state.db`
const fixture = new DatabaseSync(dbPath)
try {
fixture.exec(V7_DDL)
assert.equal(Number(fixture.prepare('PRAGMA user_version').get().user_version), 7)
} finally {
fixture.close()
}
let before
let s = await startServer({ stateDir })
try {
assert.match(s.log(), /db_ready .*schema_version=8 applied=1/, s.log())
const db = new DatabaseSync(dbPath)
try {
const cols = db.prepare("SELECT name FROM pragma_table_info('wall')").all().map(r => r.name)
assert.ok(!cols.includes('kind'), 'the legacy kind column is dropped')
for (const col of ['thickness', 'position', 'blocks_sight', 'blocks_movement', 'sight_dir',
'player_marker', 'door', 'open', 'secret', 'locked', 'height', 'label',
'flags']) {
assert.ok(cols.includes(col), `wall.${col} exists`)
}
assert.deepEqual(readWallRows(db), V7_WALLS)
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM marker_seen').get().n), 0)
assert.match(db.prepare("SELECT sql FROM sqlite_master WHERE name = 'marker_seen'").get().sql,
/FOREIGN KEY \(scene_id, wall_id\) REFERENCES wall\(scene_id, id\) ON DELETE CASCADE/)
// The height backfill: missing keys get 1.8, hand-set values survive, eye_height is never written.
assert.deepEqual(readProps(db, 'entity'), {
tok000000001: { height: 1.8 },
tok000000002: { height: 2.5, eye_height: 2.0 },
})
assert.deepEqual(readProps(db, 'character'), {
char000000001: { height: 1.8 },
char000000002: { height: 1.5 },
})
before = { walls: readWallRows(db), entity: readProps(db, 'entity'),
character: readProps(db, 'character') }
} finally {
db.close()
}
// The old scene is still served through the product surface.
const conn = await openAs(s.origin, 'ALIC-ALIC-ALIC-ALIC-ALIC')
try {
const hello = await conn.ws.waitText('hello')
assert.equal(hello.role, 'player')
assert.equal(hello.me.name, 'Alice')
const tok = await conn.ws.waitFor(m => m.t === 'token' && m.id === 'tok000000001')
assert.deepEqual(tok.pos, [400, 400])
} finally {
conn.ws.close()
}
} finally {
await stopServer(s)
}
// Second start: the migration runner writes nothing and the data is byte-identical.
s = await startServer({ stateDir })
try {
assert.match(s.log(), /db_ready .*schema_version=8 applied=0/, s.log())
const db = new DatabaseSync(dbPath)
try {
assert.deepEqual(readWallRows(db), before.walls)
assert.deepEqual(readProps(db, 'entity'), before.entity)
assert.deepEqual(readProps(db, 'character'), before.character)
} finally {
db.close()
}
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('migration: a failing step 8 leaves the schema-7 DB untouched', async () => {
const stateDir = makeStateDir()
const dbPath = `${stateDir}/state.db`
const fixture = new DatabaseSync(dbPath)
try {
fixture.exec(V7_DDL)
// The pre-existing table makes the last statement of step 8 fail after `wall` was rebuilt.
fixture.exec('CREATE TABLE marker_seen (x INTEGER)')
} finally {
fixture.close()
}
try {
await assert.rejects(startServer({ stateDir }), /db_migrate_failed|migration 8/)
const db = new DatabaseSync(dbPath)
try {
assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 7)
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM schema_migration').get().n), 7)
const cols = db.prepare("SELECT name FROM pragma_table_info('wall')").all().map(r => r.name)
assert.ok(cols.includes('kind'), 'the legacy table is back')
assert.ok(!cols.includes('thickness'), 'the typed columns were rolled back')
assert.equal(Number(db.prepare("SELECT count(*) AS n FROM sqlite_master WHERE name = 'wall_v1'")
.get().n), 0)
// The data hook never ran: no height was written.
assert.deepEqual(JSON.parse(db.prepare("SELECT props_gm FROM entity WHERE id = 'tok000000001'")
.get().props_gm), {})
} finally {
db.close()
}
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('startup: a database from a newer server (user_version=9) is refused, not downgraded', async () => {
const stateDir = makeStateDir()
const dbPath = `${stateDir}/state.db`
const fixture = new DatabaseSync(dbPath)
try {
fixture.exec(V7_DDL)
fixture.exec('PRAGMA user_version = 9')
} finally {
fixture.close()
}
try {
await assert.rejects(startServer({ stateDir }), /db_migrate_failed|newer than this server/)
const db = new DatabaseSync(dbPath)
try {
assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 9)
assert.ok(db.prepare("SELECT name FROM pragma_table_info('wall')").all()
.some(r => r.name === 'kind'), 'the newer DB was not touched')
} finally {
db.close()
}
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})