feat(walls): marker retraction, re-earn and marker fault classes (#60)

Retract a player marker when the GM removes the wall, clears
player_marker, makes the wall stop deriving window, or moves its
geometry (a/b, thickness, position). Retraction emits del only and
never the new anchor; a re-earned marker gets a fresh id. The
marker_seen deletes ride the same derived-memory NORMAL transaction as
the explored chunks, after the wall row commits and before the ack.

Replace the leak checker's aggregate MARKER class with MARKER_EARLY,
MARKER_EXTRA and MARKER_OFF, add their leakfault hooks and exact-class
fault tests, and extend the leak scenario with an unseen marked window
and a marked solid wall as the negative controls. WS black-box tests
cover all four causes, fresh re-earns, no untouched re-send, no
set/del for one id in a frame, no explored write from a retraction,
and delete/cascade durability across a restart.
This commit is contained in:
2026-11-19 23:43:44 +01:00
parent edd4437f7e
commit c3c0a39188
9 changed files with 425 additions and 60 deletions
+5 -1
View File
@@ -5,7 +5,8 @@
//
// Classes: HIDDEN_TOKEN, GMONLY_TOKEN, WALLDATA, WITHHELD, NO_REMOVE, OWN_VIEW, OTHER_PLAYER,
// EXPLORED, from slice 7 (#22) OWNER_PROP, GM_PROP, STATUS_SOURCE, and from slice 8 (#23)
// ACTUAL_NAME, CHAR_LIST, CONTROLLER_CHANGE, CHAR_OWNER_PROP, and from Walls r1 (#58) ONEWAY.
// ACTUAL_NAME, CHAR_LIST, CONTROLLER_CHANGE, CHAR_OWNER_PROP, and from Walls r1 (#58) ONEWAY and
// (#60) MARKER_EARLY, MARKER_EXTRA, MARKER_OFF.
// (The tile class lands with slice 9.)
import test from 'node:test'
import assert from 'node:assert/strict'
@@ -30,6 +31,9 @@ const FAULTS = {
walls: ['WALLDATA'],
wallHeight: ['WALLDATA'],
oneWay: ['ONEWAY'],
markerEarly: ['MARKER_EARLY'],
markerExtra: ['MARKER_EXTRA'],
markerOff: ['MARKER_OFF'],
withhold: ['WITHHELD'],
otherOwner: ['OTHER_PLAYER'],
otherVision: ['OTHER_PLAYER'],
+9
View File
@@ -24,6 +24,9 @@
// frame of the group is checked for the bucket and the `source` it must not carry
// - Walls r1 (#58): a one-way wall the subject sees across (`sight_dir` names the token's side
// blind), the ONEWAY fault's positive source and the blind-side oracle's control
// - Walls r1 (#60): a marked window far outside every scripted position and a marked solid wall
// in the room, the negative controls for MARKER_EARLY and MARKER_EXTRA; the marker retraction
// rules themselves are proven by tools/markers.test.mjs (the final scenario rewrite is #61)
import fs from 'node:fs'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
@@ -119,6 +122,12 @@ export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen =
{ a: [500, 400], b: [500, 700], door: true, open: false },
{ a: [500, 700], b: [500, 1000] },
{ a: [1400, 400], b: [1400, 900] },
// Walls r1 (#60) fault controls, added last so `wallIds[1]` stays the door. The window is far
// outside every scripted position: only a build that drops the extent gate (MARKER_EARLY)
// sends it. The solid wall with the switch on stands in the room the subject enters: only a
// build that drops the derived-window gate (MARKER_EXTRA) sends a marker for it.
{ preset: 'window', a: [3500, 2000], b: [3500, 2200] },
{ a: [620, 760], b: [720, 760], player_marker: true },
]
const wallIds = []
+74 -19
View File
@@ -27,9 +27,11 @@
## CHAR_OWNER_PROP a character's owner bucket reached a player who does not own it (8)
## GEOMETRY the recomputed polygon disagrees with the clear-segment oracle (sanity)
## ONEWAY the subject's fan ignores `sight_dir` (the two-way fan; TESTING 10.3, #58)
## MARKER a marker frame disagrees with the independent visible-extent oracle, or its shape
## is wrong (the exact MARKER_EARLY/EXTRA/OFF classes are #60's fault builds; #59
## proves the allowed type and the oracle with a positive control)
## MARKER_EARLY a marker arrived before the subject had seen that wall's extent (the extent
## gate was dropped: it reveals a position early; TESTING 10.3, #60)
## MARKER_EXTRA a marker exists for a wall that should never produce one (the derived-`window`
## gate was dropped, or the wall is not a marker candidate at all; #60)
## MARKER_OFF a marker the visible-extent oracle expects was never sent (#60)
## PROTOCOL a frame the catalogue does not allow, a bad `n` sequence, a missing hello block
##
## One-way sight (DESIGN 5.8, TESTING 10.3): the checker reads `sight_dir` from the GM's frames and
@@ -39,7 +41,7 @@
## evaluate that two-way perspective so the fault is reported as exactly ONEWAY.
##
## usage: leakcheck <transcript.jsonl> <SUBJECT> exit 0 = clean
import std/[algorithm, json, math, options, os, sets, strutils, tables]
import std/[algorithm, json, math, options, os, sequtils, sets, strutils, tables]
import geometry
const
@@ -90,9 +92,18 @@ type
## keeps the geometry and the id from the GM's frames and does its own visible-extent test.
id: int
a, b: Vec
thickness: float
position: string
playerMarker: bool
isWindow: bool
ExpectedMarker = object
## The oracle's accumulated memory for one wall: the anchor the subject should hold and the
## marker signature it was earned for. A cause change (5.8: gone, switch off, not a window,
## geometry moved) drops the entry, mirroring the server's retraction (#60).
anchor: (int, int)
sig: string
Group = object
label: string
gmMsgs: seq[JsonNode]
@@ -150,13 +161,22 @@ proc readGroups(path, subject: string): seq[Group] =
# Truth from the GM socket (walls and every token)
proc markerWallOf(id: int, w: JsonNode): MarkerWall =
## The marker-relevant projection of a GM wall frame (5.8): the derived `window` gate and the switch.
## The marker-relevant projection of a GM wall frame (5.8): the derived `window` gate, the switch
## and the geometry whose change retracts (#60).
MarkerWall(id: id, a: vec(w["a"]), b: vec(w["b"]),
thickness: w["thickness"].getFloat,
position: w["position"].getStr,
playerMarker: w["player_marker"].getBool,
isWindow: not w["blocks_sight"].getBool and w["blocks_movement"].getBool)
proc isMarkerCandidate(m: MarkerWall): bool = m.playerMarker and m.isWindow
proc markerSig(m: MarkerWall): string =
## The oracle's own copy of the retraction signature: endpoints, thickness, placement, switch and
## the derived window gate. Height and label have no marker consequence (5.8, #60).
$m.a.x & "," & $m.a.y & "," & $m.b.x & "," & $m.b.y & "," & $m.thickness & "," &
m.position & "," & $m.playerMarker & "," & $m.isWindow
proc setMarkerWall(truth: var Truth, mw: MarkerWall) =
## Upsert by wall id, so a `wall` update replaces the marker projection in place.
for i in 0 ..< truth.markerWalls.len:
@@ -447,7 +467,7 @@ proc main() =
var viewCharacters: HashSet[string] # character ids the subject was sent
var prevController: Table[string, int] # controller of each token at the previous group
var markers: Table[string, (int, int)] # marker id -> anchor, what the subject was sent
var expectedMarkers: Table[int, (int, int)] # wall id -> anchor, accumulated memory (#59)
var expectedMarkers: Table[int, ExpectedMarker] # wall id -> accumulated memory (#59/#60)
var markerPositive = false # the scenario exercised the oracle at least once
for g in groups:
@@ -748,7 +768,7 @@ proc main() =
# `full:true` is the resync set and must follow `explored` full (the client draws it over the
# fog just rebuilt); a diff adds ids in `set` and (from #60) retracts in `del`.
if not markerShapeOk(m):
fail "MARKER", "malformed marker frame (group " & g.label & ")"
fail "PROTOCOL", "malformed marker frame (group " & g.label & ")"
elif m["full"].getBool and not sawExploredFull:
fail "PROTOCOL", "marker full before explored full (group " & g.label & ")"
else:
@@ -756,33 +776,68 @@ proc main() =
for e in m["set"]:
let id = e["id"].getStr
if markers.hasKey(id):
fail "MARKER", "duplicate marker id " & id & " (group " & g.label & ")"
fail "PROTOCOL", "duplicate marker id " & id & " (group " & g.label & ")"
markers[id] = (e["pos"][0].getInt, e["pos"][1].getInt)
if m.hasKey("del"):
for d in m["del"]:
let id = d.getStr
if not markers.hasKey(id):
fail "MARKER", "del for a marker the subject never had: " & id
fail "PROTOCOL", "del for a marker the subject never had: " & id
markers.del id
else: discard
# --- player markers (5.8, TESTING 10.3 #59) -------------------------------------------------
# --- player markers (5.8, TESTING 10.3 #59/#60) ---------------------------------------------
# The oracle's own memory: a marked window enters `expectedMarkers` once any part of its drawn
# extent is inside the subject's polygons, and stays (walking away, a door, lost sight never
# retract it). It never calls vision.nim: `polysChecks` is this file's recomputed fan.
# extent is inside the subject's polygons, and stays while the cause is unchanged. The four
# retraction causes (wall gone, switch off, no longer a window, geometry moved) drop it, which
# is the server's rule read independently from the GM's truth. It never calls vision.nim:
# `polysChecks` is this file's recomputed fan.
for id in expectedMarkers.keys.toSeq:
var match = none(MarkerWall)
for mw in truth.markerWalls:
if mw.id == id: match = some(mw)
if match.isNone or markerSig(match.get) != expectedMarkers[id].sig:
expectedMarkers.del id
for mw in truth.markerWalls:
if expectedMarkers.hasKey(mw.id): continue
if extentSeen(polysChecks, mw.a, mw.b): expectedMarkers[mw.id] = anchorOf(mw)
if extentSeen(polysChecks, mw.a, mw.b):
expectedMarkers[mw.id] = ExpectedMarker(anchor: anchorOf(mw), sig: markerSig(mw))
var wantPos: seq[(int, int)]
for _, pos in expectedMarkers: wantPos.add pos
for _, em in expectedMarkers: wantPos.add em.anchor
var gotPos: seq[(int, int)]
for _, pos in markers: gotPos.add pos
wantPos.sort()
gotPos.sort()
if gotPos != wantPos:
fail "MARKER", "marker set " & $gotPos & " != visible-extent oracle " & $wantPos &
" (group " & g.label & ")"
elif wantPos.len > 0:
# Multiset difference: `missing` markers the memory expects, `extra` ones it does not. An
# extra at a marker candidate's anchor was sent before its extent was seen (EARLY); an extra
# with no candidate wall at all must never exist (EXTRA).
var missingMarkers, extraMarkers: seq[(int, int)]
var wi = 0
var gi = 0
while wi < wantPos.len or gi < gotPos.len:
if wi >= wantPos.len:
extraMarkers.add gotPos[gi]; inc gi
elif gi >= gotPos.len:
missingMarkers.add wantPos[wi]; inc wi
elif wantPos[wi] == gotPos[gi]:
inc wi; inc gi
elif wantPos[wi] < gotPos[gi]:
missingMarkers.add wantPos[wi]; inc wi
else:
extraMarkers.add gotPos[gi]; inc gi
if missingMarkers.len > 0:
fail "MARKER_OFF", "marker " & $missingMarkers[0] & " was never sent (" &
$missingMarkers.len & " missing; group " & g.label & ")"
var candidateAnchors: seq[(int, int)]
for mw in truth.markerWalls: candidateAnchors.add anchorOf(mw)
for pos in extraMarkers:
if pos in candidateAnchors:
fail "MARKER_EARLY", "marker " & $pos & " sent before its wall was seen (group " &
g.label & ")"
else:
fail "MARKER_EXTRA", "marker " & $pos & " has no marker candidate wall (group " &
g.label & ")"
if wantPos.len > 0:
markerPositive = true
# --- CONTROLLER_CHANGE (10.3) ----------------------------------------------------------------
@@ -883,7 +938,7 @@ proc main() =
if removes == 0: fail "NO_REMOVE", "the scenario never withdrew a token (harness coverage)"
if seenAny.len < 3: fail "WITHHELD", "the scenario never showed the subject 3 tokens"
if not markerPositive:
fail "MARKER", "the scenario never produced a marker the visible-extent oracle expects"
fail "PROTOCOL", "the scenario never produced a marker the visible-extent oracle expects"
for cls, n in classes: echo "FAILCLASS ", cls, " ", n
echo "leakcheck: subject ", subject, " (player ", me, "), ", groupsSeen, " groups, ",
+215 -1
View File
@@ -8,7 +8,8 @@
// here: this group proves the emission gate, the anchor, storage/resync and privacy.
import test from 'node:test'
import assert from 'node:assert/strict'
import { withGmServer, openAs } from './withserver.mjs'
import fs from 'node:fs'
import { withGmServer, openAs, makeStateDir, gmKeyOf, startServer, stopServer } from './withserver.mjs'
import { createPlayer, namePlayer, sleep } from './lib.mjs'
const ID_RE = /^[A-Za-z0-9_-]{12}$/
@@ -180,3 +181,216 @@ test('marker lifetime and resync: survives walk-away and doors, full after explo
gm.ws.close(); alice.conn.ws.close(); again.ws.close(); bob.conn.ws.close(); carol.conn.ws.close()
})
})
// -------------------------------------------------------------------------------------------------
// Walls r1 (#60): retraction, re-earning and the derived-memory ordering.
const framesAfter = (ws, from) => ws.messages.filter((m, i) => i >= from)
async function waitAfter(ws, from, pred, what, timeoutMs = 5000) {
const deadline = Date.now() + timeoutMs
for (;;) {
const hit = ws.messages.find((m, i) => i >= from && m && pred(m))
if (hit) return hit
if (Date.now() > deadline) {
throw new Error(`no ${what} after message ${from}; saw: ` +
JSON.stringify(ws.messages.slice(from).map(m => m && m.t)))
}
await sleep(10)
}
}
function assertDelOnly(frames, id, what) {
const markers = frames.filter(m => m && m.t === 'marker')
assert.equal(markers.length, 1, `${what}: exactly one marker frame`)
const frame = markers[0]
assert.equal(frame.full, false, `${what}: a retraction is a diff`)
assert.deepEqual(frame.set, [], `${what}: a retraction carries no set`)
assert.deepEqual(frame.del, [id], `${what}: the marker is retracted by id`)
}
function assertNoSameIdBothWays(ws) {
for (const frame of markerFrames(ws)) {
const set = new Set(frame.set.map(e => e.id))
for (const id of frame.del ?? []) {
assert.equal(set.has(id), false, `set and del for ${id} in one frame`)
}
}
}
test('retraction: every cause sends del only, a re-earned marker gets a fresh id (#60)', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
// Two marked windows the subject sees at connect: one is edited throughout, the other is
// untouched and must never be re-sent.
const win = await addWall(gm, { preset: 'window', a: [200, 500], b: [200, 700] })
await addWall(gm, { preset: 'window', a: [400, 300], b: [400, 400] })
const alice = await namedPlayer(gm, s.origin, 'Retract Alice')
const tokenId = await addSightToken(gm, alice, [300, 300])
const seen = await alice.conn.ws.waitFor(m => m.t === 'marker' && m.set.length === 2)
assertMarkerShape(seen)
const byPos = p => seen.set.find(e => e.pos[0] === p[0] && e.pos[1] === p[1])
const keepId = byPos([400, 350]).id
let current = byPos([200, 600]).id
const editedAt = () => m => m.t === 'marker' &&
(m.set.some(e => e.pos[0] === 200) || (m.del ?? []).includes(current))
const away = async () => {
assert.equal((await gm.ws.request({ t: 'token.move', id: tokenId,
pos: [2000, 2000] })).ok, true)
await sleep(100)
}
const back = async () => {
assert.equal((await gm.ws.request({ t: 'token.move', id: tokenId,
pos: [300, 300] })).ok, true)
await sleep(100)
}
const retract = async action => {
const from = alice.conn.ws.messages.length
assert.equal((await action()).ok, true)
await sleep(100)
return framesAfter(alice.conn.ws, from)
}
const reEarn = async what => {
const from = alice.conn.ws.messages.length
await back()
const frame = await waitAfter(alice.conn.ws, from, editedAt(), what)
assert.equal(frame.set.length, 1, `${what}: one marker is re-earned`)
return { frame, from }
}
// Walking away is not a cause: memory stays, nothing is sent.
let from = alice.conn.ws.messages.length
await away()
assert.equal(markersAfter(alice.conn.ws, from).length, 0,
'walking away never retracts a marker')
// Cause 4a: endpoints move while the subject cannot see the new geometry -> del only.
let frames = await retract(() => gm.ws.request({ t: 'wall.update', scene: gm.scene, id: win.id,
a: [200, 520], b: [200, 720] }))
assertDelOnly(frames, current, 'endpoint move')
assert.equal(frames.some(m => m.t === 'explored'), false,
'a retraction writes no explored cell')
let earned = await reEarn('endpoint move')
assert.deepEqual(earned.frame.set[0].pos, [200, 620], 'the new anchor is the new midpoint')
assert.notEqual(earned.frame.set[0].id, current, 'a re-earned marker gets a fresh id')
current = earned.frame.set[0].id
assert.equal(JSON.stringify(framesAfter(alice.conn.ws, earned.from)).includes(keepId), false,
'the untouched marker is never re-sent')
// Cause 4b: thickness.
await away()
frames = await retract(() => gm.ws.request({ t: 'wall.update', scene: gm.scene, id: win.id,
thickness: 7 }))
assertDelOnly(frames, current, 'thickness change')
earned = await reEarn('thickness change')
assert.notEqual(earned.frame.set[0].id, current, 'thickness re-earn is a fresh id')
current = earned.frame.set[0].id
// Cause 4c: placement.
await away()
frames = await retract(() => gm.ws.request({ t: 'wall.update', scene: gm.scene, id: win.id,
position: 'left' }))
assertDelOnly(frames, current, 'placement change')
earned = await reEarn('placement change')
assert.notEqual(earned.frame.set[0].id, current, 'placement re-earn is a fresh id')
current = earned.frame.set[0].id
// Cause 2: the player_marker switch is turned off. Nothing about sight changes, so the only
// frame is the retraction itself.
frames = await retract(() => gm.ws.request({ t: 'wall.update', scene: gm.scene, id: win.id,
player_marker: false }))
assertDelOnly(frames, current, 'marker switch off')
assert.equal(frames.some(m => m.t === 'explored' || m.t === 'vision'), false,
'a switch-off retraction changes no sight state')
// Turning it back on re-earns a fresh id (the subject still sees the window).
from = alice.conn.ws.messages.length
assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id: win.id,
player_marker: true })).ok, true)
const re4 = await waitAfter(alice.conn.ws, from, editedAt(), 'switch-on re-earn')
assert.equal(re4.set.length, 1)
assert.notEqual(re4.set[0].id, current, 'a switch-on re-earn is a fresh id')
assert.equal(JSON.stringify(framesAfter(alice.conn.ws, from)).includes(keepId), false,
'the untouched marker is never re-sent')
current = re4.set[0].id
// Cause 3: the wall stops deriving `window` (a solid closed door now).
frames = await retract(() => gm.ws.request({ t: 'wall.update', scene: gm.scene, id: win.id,
blocks_sight: true }))
assertDelOnly(frames, current, 'no longer a window')
assert.equal(frames.some(m => m.t === 'explored'), false,
'making a window opaque reveals no new explored cell')
// Back to a window: a fresh id again.
from = alice.conn.ws.messages.length
assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id: win.id,
blocks_sight: false })).ok, true)
const re5 = await waitAfter(alice.conn.ws, from, editedAt(), 'window re-earn')
assert.equal(re5.set.length, 1)
assert.notEqual(re5.set[0].id, current, 'a window re-earn is a fresh id')
current = re5.set[0].id
// Cause 1: the wall is removed.
frames = await retract(() => gm.ws.request({ t: 'wall.remove', scene: gm.scene, id: win.id }))
assertDelOnly(frames, current, 'wall removed')
// The full set on reconnect carries only the untouched marker.
const again = await openAs(s.origin, alice.key)
await again.ws.waitText('hello')
const full2 = await again.ws.waitFor(m => m.t === 'marker' && m.full === true)
assert.deepEqual(full2.set.map(e => e.id), [keepId],
'the retracted marker is gone and the untouched one survives')
assertNoSameIdBothWays(alice.conn.ws)
assertNoSameIdBothWays(again.ws)
assert.equal(markerFrames(gm.ws).length, 0, 'the GM receives no marker')
gm.ws.close(); alice.conn.ws.close(); again.ws.close()
})
})
test('marker retraction is durable: delete and cascade survive a restart (#60)', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
let aliceKey = null
let keptId = null
let s = await startServer({ stateDir })
try {
const gm = await gmConnect(s.origin, gmKey)
const off = await addWall(gm, { preset: 'window', a: [200, 500], b: [200, 700] })
const gone = await addWall(gm, { preset: 'window', a: [300, 500], b: [300, 700] })
await addWall(gm, { preset: 'window', a: [400, 300], b: [400, 400] })
const alice = await namedPlayer(gm, s.origin, 'Restart Alice')
aliceKey = alice.key
await addSightToken(gm, alice, [300, 320])
const seen = await alice.conn.ws.waitFor(m => m.t === 'marker' && m.set.length === 3)
const idAt = p => seen.set.find(e => e.pos[0] === p[0] && e.pos[1] === p[1]).id
const offId = idAt([200, 600])
const goneId = idAt([300, 600])
keptId = idAt([400, 350])
let from = alice.conn.ws.messages.length
assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id: off.id,
player_marker: false })).ok, true)
await sleep(100)
assert.deepEqual(markersAfter(alice.conn.ws, from)[0].del, [offId])
from = alice.conn.ws.messages.length
assert.equal((await gm.ws.request({ t: 'wall.remove', scene: gm.scene,
id: gone.id })).ok, true)
await sleep(100)
assert.deepEqual(markersAfter(alice.conn.ws, from)[0].del, [goneId])
gm.ws.close(); alice.conn.ws.close()
} finally {
await stopServer(s)
}
s = await startServer({ stateDir })
try {
const again = await openAs(s.origin, aliceKey)
await again.ws.waitText('hello')
const full = await again.ws.waitFor(m => m.t === 'marker' && m.full === true)
assert.deepEqual(full.set.map(e => e.id), [keptId],
'the deleted marker rows stay deleted across the restart')
again.ws.close()
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})