diff --git a/docs/TESTING.md b/docs/TESTING.md index dae3cb6..61dc2cd 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -60,7 +60,7 @@ How to run: `devbox run test` = Nim in-process tests first, then the Node black- | # | Proving test | |---|---| | T1 | leak test + fault classes | -| T2 | fault `walls` [MEASURED caught]; door-equivalence test (T17, §10.3) [MEASURED caught: fault `secretgap`]; `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` (§10.3) — planned: Walls r1 #59/#60 | +| T2 | fault `walls` [MEASURED caught]; door-equivalence test (T17, §10.3) [MEASURED caught: fault `secretgap`]; `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` (§10.3) [MEASURED caught: `tools/fault.test.mjs`, Walls r1 #60] | | T3 | faults `other-*` [MEASURED caught] | | T4 | leak (d) against the independent oracle, smoke steal check, direct `/_tiles/` -> 404 (M3 test nginx) | | T5 | documented, not testable as a leak; M4 timing gates (§13) | @@ -350,9 +350,12 @@ from the prototype, what was missing, what the M3 build added, and the tools it exact-class assertion; the shipped binary must contain no `LEAK_FAULT`. Built: `HIDDEN_TOKEN`, `GMONLY_TOKEN`, `WALLDATA`, `WITHHELD`, `NO_REMOVE`, `OWN_VIEW`, `OTHER_PLAYER`, `EXPLORED`, `OWNER_PROP`, `GM_PROP`, `STATUS_SOURCE`, `ACTUAL_NAME`, `STALE_NAME`, `CHAR_LIST`, - `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`, `KEY_IN_LOG`, `ONEWAY` (#58). Walls r1 built: `secretgap` + `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`, `KEY_IN_LOG`, `ONEWAY` (#58), `MARKER_EARLY`, + `MARKER_EXTRA`, `MARKER_OFF` (#60). Walls r1 built: `secretgap` (#56), asserted as exactly `SECRETGAP` by `tools/doors.test.mjs` (the differential group, not the - transcript checker). Planned: Walls r1 — `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` (#59/#60). + transcript checker); `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` (#60), each asserted as exactly + its own class by `tools/fault.test.mjs` (the leak transcript checker, with the scenario's unseen + marked window and marked solid wall as the negative controls). `tools/leakcheck.nim` refuses the `gm` bucket, the `owner` bucket on a non-controller and any `source` on a player status entry. Two consequences: the `hidden` and @@ -446,13 +449,20 @@ from the prototype, what was missing, what the M3 build added, and the tools it calling `vision.nim`), checks that a marker exists for a player exactly when some point of the wall's visible extent has entered that player's polygon **and** the wall is `player_marker:true` and derives `window`, and that the frame carries only the opaque marker id and the anchor: anything - else is `WALLDATA`/`MARKER`. Positive control: a marked window the subject sees yields exactly one - marker at its drawn midpoint; a wall behind a sight blocker, `player_marker:false`, or a solid wall - with the switch on yields none. The oracle's expected set accumulates like explored memory, so - walking away, a door or lost sight never makes a sent marker wrong. Faults `MARKER_EARLY`, - `MARKER_EXTRA`, `MARKER_OFF` and retraction (removing the wall, clearing the switch, moving the - geometry retracts the marker, never sending the new position early and writing no explored cell or - tile) remain #60. + else is `WALLDATA`/`PROTOCOL`. Positive control: a marked window the subject sees yields exactly + one marker at its drawn midpoint; a wall behind a sight blocker, `player_marker:false`, or a solid + wall with the switch on yields none. The oracle's expected set accumulates like explored memory, + so walking away, a door or lost sight never makes a sent marker wrong; a wall removal, a cleared + switch, a lost `window` or a geometry move retract it (the oracle drops the entry when the GM's + wall frame shows the cause changed, mirroring the server). An extra marker at a candidate's anchor + before its extent was seen is `MARKER_EARLY`; an extra marker with no candidate wall is + `MARKER_EXTRA`; an expected marker never sent is `MARKER_OFF`. Faults `MARKER_EARLY`, + `MARKER_EXTRA`, `MARKER_OFF` (`markerEarly`/`markerExtra`/`markerOff`) are built and asserted as + exactly their own class by `tools/fault.test.mjs`, with the scenario's far unseen marked window + and marked solid wall as the negative controls. The WS group `tools/markers.test.mjs` proves the + four retraction causes (del only), a fresh id on re-earn, no re-send of an untouched marker, no + `set` and `del` for one id in a frame, no explored write from a pure retraction, and durability + of the deletes across a restart. - **Wall fields, storage and migration (#49).** Three gates. **Leak:** `BannedAlways` contains every wall field name (`thickness`, `position`, `height`, `blocks_sight`, `blocks_movement`, `sight_dir`, `player_marker`, `door`, `open`, `secret`, `locked`, `label`, `a`, `b`), so any of them in a player diff --git a/server/main.nim b/server/main.nim index 3e6c052..f83a53d 100644 --- a/server/main.nim +++ b/server/main.nim @@ -235,7 +235,8 @@ proc recordEncounters() = # M3 slice 6 / #21, #59). Both live in memory and reach the DB only here. One rule: a mutation writes # exactly the explored chunks its refresh dirtied and the markers it minted, never the whole state, # and the write rides in the mutation's transaction so an ack cannot precede what it reports. NORMAL -# durability (Q12): both are derived and monotone (a marker only grows in r1), not GM-authored. +# durability (Q12): both are derived (explored only grows; a marker is minted and retracted by the +# GM's causes), never GM-authored. proc dirtyExplored(pids: openArray[int]): seq[explored.Chunk] = ## The chunks the last refresh dirtied, for the named players. Caller holds the lock and has @@ -252,16 +253,21 @@ proc dirtyExplored(pids: openArray[int]): seq[explored.Chunk] = proc persistMarkers(pids: openArray[int]) = ## The marker half alone, for a connect where the explored grid must stay exactly as it was (a ## schema-4/7 database rebuilds its grid on connect and stores nothing until a mutation): a marker - ## minted at the resync is still durable before it is sent (5.8, 4.2 step 6). + ## minted at the resync is still durable before it is sent (5.8, 4.2 step 6). The deletes run + ## before the inserts: a moved wall's old marker must be gone before its fresh one is stored, and + ## both are the same derived-memory transaction. for pid in pids: if pid == GmControlled: continue + discard markers.writeDead(app.db, pid, + app.visions.mgetOrPut(pid, PlayerVision()).markerDead) discard markers.writeNew(app.db, app.scene.id, pid, app.visions.mgetOrPut(pid, PlayerVision()).markerFresh) proc persistDerived(pids: openArray[int]) = - ## Writes the dirtied explored chunks and the markers the same refresh minted (5.8: a marker insert - ## is in the same derived-memory transaction as the explored chunks, after the wall row commits). - ## No transaction of its own: the caller wraps it together with the mutation's row writes. + ## Writes the dirtied explored chunks and the markers the same refresh minted or retracted (5.8: + ## marker inserts and deletes are in the same derived-memory transaction as the explored chunks, + ## after the wall row commits). No transaction of its own: the caller wraps it together with the + ## mutation's row writes. let chunks = dirtyExplored(pids) if chunks.len > 0: discard explored.writeChunks(app.db, app.scene.id, chunks) persistMarkers(pids) diff --git a/server/markers.nim b/server/markers.nim index fec0a6a..a475e84 100644 --- a/server/markers.nim +++ b/server/markers.nim @@ -1,4 +1,4 @@ -## Player marker emission and persistence (DESIGN 5.8, 6.1, 6.3, 8; ADR-0015, #59). +## Player marker emission, retraction and persistence (DESIGN 5.8, 6.1, 6.3, 8; ADR-0015, #59/#60). ## ## A marker exists for a player exactly when a wall is both `player_marker:true` and derives ## `window`, and any point of the wall's visible extent has been inside one of that player's vision @@ -11,19 +11,33 @@ ## 12-character id (never the wall id), keeps the wall's drawn midpoint rounded once as its anchor, ## and is persisted in `marker_seen` as part of the same derived-memory transaction as the explored ## chunks (4.2 step 6). `vision.PlayerVision.markers` holds it in memory and `restore` loads it at -## startup, before the first connection (4.4). This round only adds: retraction (wall removed, switch -## off, no longer a window, geometry moved), re-earning a fresh id and the marker fault classes are -## #60; `sync` is the seam where that lifetime rule lands. +## startup, before the first connection (4.4). +## +## Lifetime (5.8, #60): walking away, a door and lost sight never retract a marker. The GM's causes +## do: removing the wall, clearing `player_marker`, making the wall stop deriving `window`, or +## moving its geometry (`a`/`b`, `thickness`, `position`). Every cause reduces to "the wall is gone +## or its marker signature changed", so `syncMarkers` retracts those markers and then mints anew for +## whatever qualifies now. A retraction is a `del` id only (never the new anchor), and a re-earned +## marker always gets a fresh id because the old one died. A moved wall therefore cannot reveal its +## new position early: the new geometry qualifies only through the normal extent gate on a refresh +## whose polygon contains it. ## ## No DB transaction control here: the caller owns it, exactly like explored.nim. import std/[math, options, strutils, tables] import db_connector/db_sqlite -import geometry, tokens, vision, world +import faults, geometry, tokens, vision, world proc anchorOf*(w: WallRec): (int, int) = ## The wall's drawn midpoint, rounded once to integer px and fixed for the wall (5.8, 6.1). (int(round((w.a.x + w.b.x) / 2.0)), int(round((w.a.y + w.b.y) / 2.0))) +proc wallSig(w: WallRec): string = + ## Everything whose change retracts a marker (5.8, #60): endpoints, thickness, placement, the + ## `player_marker` switch and the derived `window` gate. Height and label have no marker + ## consequence and are deliberately absent. + $w.a.x & "," & $w.a.y & "," & $w.b.x & "," & $w.b.y & "," & + $w.thickness & "," & $w.position & "," & $w.playerMarker & "," & derivedKind(w) + proc extentSeen*(pv: PlayerVision, a, b: Vec): bool = ## True when any point of the wall's visible extent (the segment in this round) is inside one of ## the player's polygons: an endpoint inside, or the segment crossing a polygon edge. Boundary @@ -38,11 +52,23 @@ proc extentSeen*(pv: PlayerVision, a, b: Vec): bool = proc qualifies*(pv: PlayerVision, w: WallRec): bool = ## The complete emission gate of 5.8: the switch on, the derived shape label a window, and part of ## the visible extent seen. A solid wall with `player_marker:true` fails the kind gate. - w.playerMarker and derivedKind(w) == "window" and pv.extentSeen(w.a, w.b) + var kindOk = derivedKind(w) == "window" + var seen = pv.extentSeen(w.a, w.b) + when defined(leakfault): + # Negative controls (TESTING 10.3, #60): MARKER_EARLY drops the visible-extent gate, so a + # marker is sent before the player has seen the window; MARKER_EXTRA drops the derived-window + # gate, so any wall with the switch on (a solid wall included) emits one. + if faultActive("markerEarly"): seen = true + if faultActive("markerExtra"): kindOk = true + w.playerMarker and kindOk and seen proc markerIdTaken(pv: PlayerVision, id: string): bool = for marker in pv.markers.values: if marker.id == id: return true + # A re-earned marker in the same refresh must not reuse an id that is being retracted: one frame + # may carry `set` and `del`, but never for the same id (5.8, 6.1). + for dead in pv.markerDead: + if dead == id: return true proc freshMarkerId(pv: PlayerVision): string = result = newTokenId() @@ -52,15 +78,29 @@ proc freshMarkerId(pv: PlayerVision): string = inc tries proc syncMarkers*(pv: var PlayerVision, sc: SceneRec): int = - ## Adds one marker per wall that now qualifies and is not in this player's memory yet; returns how - ## many were minted. Add-only by design in this round (#59): a marker that stops qualifying stays, - ## so walking away, a door closing and lost sight never retract it. The retraction/re-earn rule is - ## #60 and belongs here, next to this loop. + ## Reconciles one player's marker memory with the current scene (DESIGN 5.8, #60): retract every + ## marker whose wall is gone or whose cause changed, then mint one for every wall that now + ## qualifies and is not in memory. Returns how many were minted. + ## + ## Retraction is first, so a moved wall gives up its old id even when the new geometry is already + ## in sight; the mint below is still the ordinary extent gate, never a "the wall moved" shortcut. + ## `markerDead` feeds the same derived-memory transaction as `markerFresh` (4.2 step 6). + var retract: seq[int] + for wallId in pv.markers.keys: + let wall = sc.wallById(wallId) + if wall.isNone or pv.markers[wallId].sig != wallSig(wall.get): + retract.add wallId + for wallId in retract: + pv.markerDead.add pv.markers[wallId].id + pv.markers.del wallId + when defined(leakfault): + # MARKER_OFF: the player-facing computation never mints a marker (retraction still runs). + if faultActive("markerOff"): return 0 for w in sc.walls: if w.id in pv.markers: continue if not pv.qualifies(w): continue let (x, y) = anchorOf(w) - let marker = Marker(id: freshMarkerId(pv), x: x, y: y) + let marker = Marker(id: freshMarkerId(pv), x: x, y: y, sig: wallSig(w)) pv.markers[w.id] = marker pv.markerFresh.add (w.id, marker) inc result @@ -71,6 +111,8 @@ proc syncMarkers*(pv: var PlayerVision, sc: SceneRec): int = const InsertSql = """INSERT INTO marker_seen (player_id, scene_id, wall_id, marker_id) VALUES (?, ?, ?, ?)""" +const DeleteSql = """DELETE FROM marker_seen WHERE player_id = ? AND marker_id = ?""" + proc writeNew*(db: DbConn, sceneId, playerId: int, fresh: var seq[(int, Marker)]): int = ## Inserts the markers the last refresh minted for one player and clears the buffer. Called inside ## the mutation's transaction, after the wall row (for a wall write) committed and before the ack: @@ -85,11 +127,28 @@ proc writeNew*(db: DbConn, sceneId, playerId: int, fresh: var seq[(int, Marker)] finalize(ps) fresh.setLen(0) +proc writeDead*(db: DbConn, playerId: int, dead: var seq[string]): int = + ## Deletes the markers the last refresh retracted for one player and clears the buffer. Same + ## transaction and ordering rule as `writeNew` (5.8, 4.2 step 6): derived player memory rides the + ## mutation's `NORMAL` transaction, after the wall row commits and before the ack, so a + ## retraction's `del` can never precede the wall change it reports. A wall removal already took + ## its rows through the composite FK cascade, so that delete is a no-op here (and still correct). + if dead.len == 0: return 0 + let ps = db.prepare(DeleteSql) + try: + for id in dead: + db.exec(ps, playerId, id) + inc result + finally: + finalize(ps) + dead.setLen(0) + proc restore*(db: DbConn, sc: SceneRec, visions: var Table[int, PlayerVision]) = ## Startup (4.4): every `marker_seen` row back into its player's memory, before the first - ## connection, with the anchor recomputed from the loaded wall (the anchor is derived, not stored). - ## A row whose wall is missing cannot exist (the composite FK cascades); skipping one defensively - ## keeps a hand-edited DB from crashing startup. + ## connection, with the anchor recomputed from the loaded wall (the anchor is derived, not stored) + ## and the marker signature taken from the wall as loaded. A row whose wall is missing cannot + ## exist (the composite FK cascades); skipping one defensively keeps a hand-edited DB from + ## crashing startup. for row in db.getAllRows(sql""" SELECT player_id, wall_id, marker_id FROM marker_seen WHERE scene_id = ?""", sc.id): let pid = parseInt(row[0]) @@ -98,7 +157,7 @@ proc restore*(db: DbConn, sc: SceneRec, visions: var Table[int, PlayerVision]) = if wall.isNone: continue let (x, y) = anchorOf(wall.get) visions.mgetOrPut(pid, PlayerVision()).markers[wallId] = - Marker(id: row[2], x: x, y: y) + Marker(id: row[2], x: x, y: y, sig: wallSig(wall.get)) proc markerCount*(db: DbConn, sceneId: int): int = ## Scene-wide marker rows: an O(1) startup log number (11.3) and a test probe. diff --git a/server/views.nim b/server/views.nim index b4bb662..37ea32c 100644 --- a/server/views.nim +++ b/server/views.nim @@ -524,7 +524,7 @@ proc markerEntryJson(m: MarkerView): JsonNode = proc markerFrame*(entries: seq[MarkerView], full: bool, del: seq[string]): JsonNode = ## `marker {full, set:[{id, pos}], del:[id]}` (DESIGN 6.1). `full:true` replaces the whole set on ## connect/resync and carries no `del`; a diff carries additions in `set` and retractions in `del`, - ## never both for one id. Retraction emission is #60; this builder already has the shape. + ## never both for one id. var set: JsonNode = newJArray() for m in entries: set.add markerEntryJson(m) result = %*{"t": "marker", "full": full, "set": set} @@ -593,8 +593,8 @@ proc diffEncountered(known: var Known, key: string, entries: seq[EncounteredView proc diffMarkers(known: var Known, markers: seq[MarkerView], full: bool): JsonNode = ## One `marker` message or nil (DESIGN 5.8, 6.1): on connect/resync `full:true` with the whole set - ## (after `explored`, 6.3); afterwards only new ids in `set`. The `del` path exists in the frame - ## shape but the r1 map is add-only: retraction is #60, so it stays empty here. + ## (after `explored`, 6.3); afterwards additions in `set` and retractions in `del`, each sorted and + ## never the same id in both (a re-earned marker is a new id, 5.8, #60). var seen = initHashSet[string]() var set: seq[MarkerView] var del: seq[string] diff --git a/server/vision.nim b/server/vision.nim index 9782dcb..89e6af8 100644 --- a/server/vision.nim +++ b/server/vision.nim @@ -21,10 +21,12 @@ ## Change tracking: `ver` counts polygon changes (the client gets `vision` only when it changes, 6.4) ## and `fresh` holds the cells this mutation added (4.2 step 8: cleared after egress). ## -## Player markers (DESIGN 5.8, ADR-0015, #59) are per-player memory like explored: `markers` maps a -## wall id to that player's own opaque marker id and its fixed anchor (integer px). The map only grows -## in this round; retraction and re-earning are #60. `markerFresh` holds the markers minted by the -## current refresh so the mutation's transaction can persist them (server/markers.nim). +## Player markers (DESIGN 5.8, ADR-0015, #59/#60) are per-player memory like explored: `markers` +## maps a wall id to that player's own opaque marker id, its fixed anchor (integer px) and the +## wall-cause signature it was minted for. A marker is retracted when the wall goes, the switch is +## cleared, the wall stops deriving `window`, or its geometry (`a`/`b`, `thickness`, `position`) +## moves; a re-earn gets a fresh id. `markerFresh`/`markerDead` hold the markers minted/retracted by +## the current refresh so the mutation's transaction can persist them (server/markers.nim). import std/[algorithm, math, sets, tables] import tokens, worldmap, geometry, world, faults @@ -35,9 +37,12 @@ type Marker* = object ## One player's marker memory for one wall (DESIGN 5.8, 6.1). The id is opaque and per player; - ## the anchor is the wall's drawn midpoint, rounded once at mint time and never updated. + ## the anchor is the wall's drawn midpoint, rounded once at mint time and never updated. `sig` + ## is the retraction-relevant wall state (geometry, switch, derived kind) the marker was earned + ## for: a different signature at the next refresh means the cause changed and the marker dies. id*: string x*, y*: int + sig*: string PlayerVision* = object polys*: seq[Poly] @@ -46,6 +51,7 @@ type fresh*: seq[(int, int)] ## cells added by the current mutation (cx, cy), sorted markers*: Table[int, Marker] ## wall id -> this player's marker (5.8, #59) markerFresh*: seq[(int, Marker)] ## markers minted by the last refresh, awaiting the DB write + markerDead*: seq[string] ## marker ids retracted by the last refresh, awaiting the DB delete proc cols*(sc: SceneRec): int = ## Cells across the scene (DESIGN 8: ceil(w / cell)). @@ -95,7 +101,9 @@ proc refresh*(pv: var PlayerVision, sc: SceneRec, tokens: seq[TokenRec], playerI pv.fresh.sort() proc clearFresh*(pv: var PlayerVision) = - ## 4.2 step 8: after the egress fan-out every connection has the cells. + ## 4.2 step 8: after the egress fan-out every connection has the cells. `markerFresh` and + ## `markerDead` are cleared by their own write (markers.writeNew/writeDead), which ran before the + ## egress under the same lock. pv.fresh.setLen(0) proc exploredFull*(pv: PlayerVision, sc: SceneRec): seq[(int, int)] = diff --git a/tools/fault.test.mjs b/tools/fault.test.mjs index 9e57aee..7af2309 100644 --- a/tools/fault.test.mjs +++ b/tools/fault.test.mjs @@ -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'], diff --git a/tools/leak.mjs b/tools/leak.mjs index fa87e75..5eb1c3f 100644 --- a/tools/leak.mjs +++ b/tools/leak.mjs @@ -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 = [] diff --git a/tools/leakcheck.nim b/tools/leakcheck.nim index 780c306..322ad05 100644 --- a/tools/leakcheck.nim +++ b/tools/leakcheck.nim @@ -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 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, ", diff --git a/tools/markers.test.mjs b/tools/markers.test.mjs index 292d87a..8427035 100644 --- a/tools/markers.test.mjs +++ b/tools/markers.test.mjs @@ -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 }) + } +})