fix: marker_seen deletes commit with the wall change

A wall cause change (endpoint move, thickness/position, player_marker off,
no longer window) committed the wall row in the FULL transaction while its
marker_seen deletes rode the later NORMAL derived-memory transaction. A crash
between them left the stale row, and restart restored the marker with the
anchor recomputed from the NEW geometry, revealing a position the player never
saw (DESIGN 5.8).

updateWall now deletes the affected rows in the same FULL transaction as the
replaced row, exactly as the composite FK cascade already does for wall.remove.
The live del frames are unchanged and marker inserts stay in the derived
transaction: wall+deletes commit, derived inserts, then ack.

The marker cause signature moves to world.markerSig so the write-time delete
and the online retraction cannot drift.

Proof: a leakfault-only markerCrash hook quits between the wall commit and
the derived write; tools/markers.test.mjs covers all four causes and restarts
on a clean build, asserting no marker for the changed wall (no new anchor) and
restoring the untouched window's marker as the positive control.

Ref #60
This commit is contained in:
2026-11-19 23:52:13 +01:00
parent c3c0a39188
commit a69563f701
8 changed files with 160 additions and 27 deletions
+7
View File
@@ -908,3 +908,10 @@ Each entry quotes the superseded statement (excerpt) and names the surviving rul
That is 5.8 [#42], which superseded both; this block fixed heights and units only, and what a That is 5.8 [#42], which superseded both; this block fixed heights and units only, and what a
low wall hides (#44) and thickness (#45) were settled afterwards in 5.9 and 5.10." Historical low wall hides (#44) and thickness (#45) were settled afterwards in 5.9 and 5.10." Historical
provenance only; the surviving rules are current §1, §5.7, §5.8, §5.9, §5.10. provenance only; the surviving rules are current §1, §5.7, §5.8, §5.9, §5.10.
17. **All marker deletes in the derived transaction (2026-11-19, #60).** Old §8: "marker
inserts/deletes are derived player memory and ride the mutation's `NORMAL` transaction (the
same one as the explored chunks)". Narrowed after the #60 crash review: a cause-change delete
rides the wall row's `FULL` transaction (inserts stay `NORMAL`), because a crash between the
two would restore the marker with the new geometry and reveal a position the player never saw.
Surviving rules: current §5.8, §8.
+11 -6
View File
@@ -664,10 +664,11 @@ explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, sc
`''` is not a legal label (`1..64`) and `0` is not a legal height (`> 0`), so a sentinel would `''` is not a legal label (`1..64`) and `0` is not a legal height (`> 0`), so a sentinel would
make the load path lie about the domain. make the load path lie about the domain.
- **Startup and write timing:** `marker_seen` rows are loaded per player with the explored chunks - **Startup and write timing:** `marker_seen` rows are loaded per player with the explored chunks
before the first connection (like `explored.restore`); marker inserts/deletes are derived player before the first connection (like `explored.restore`); marker inserts are derived player memory
memory and ride the mutation's `NORMAL` transaction (the same one as the explored chunks), never and ride the mutation's `NORMAL` transaction (the same one as the explored chunks), never the
the `FULL` authoring one. They run before the ack, after the wall row commits, so a retraction's `FULL` authoring one, while a cause-change delete rides the wall row's `FULL` transaction so it
`del` can never precede the wall change it reports. cannot outlive the wall change across a crash. They run before the ack, after the wall row
commits, so a retraction's `del` can never precede the wall change it reports.
- Startup: load everything into memory, recompute vision for all players (prototype does, in one - Startup: load everything into memory, recompute vision for all players (prototype does, in one
transaction) so `vision` is never stale vs walls. Startup loads the scene, its tokens and every transaction) so `vision` is never stale vs walls. Startup loads the scene, its tokens and every
stored `explored_chunk` and `marker_seen` row before the first connection (`explored.restore`), so stored `explored_chunk` and `marker_seen` row before the first connection (`explored.restore`), so
@@ -1044,7 +1045,9 @@ What a wall's behaviour is made of. Heights are 5.7; what a low wall does to sig
`player_marker` is turned off, the wall stops being a window (a switch or `sight_dir` change), `player_marker` is turned off, the wall stops being a window (a switch or `sight_dir` change),
or its geometry moves (`a`/`b`, `thickness`, `position`). A retraction reveals only that the GM or its geometry moves (`a`/`b`, `thickness`, `position`). A retraction reveals only that the GM
changed something there, never a new position: a moved wall re-earns its marker only when the changed something there, never a new position: a moved wall re-earns its marker only when the
player sees the new geometry. Retraction never un-explores a cell and never revokes a tile. player sees the new geometry. The retraction delete commits with the wall row, so a crash
between the wall change and the derived-memory write cannot restore the stale marker either.
Retraction never un-explores a cell and never revokes a tile.
- **Wire [FIXED (owner-delegated), #48; shape #49].** The message is the dotless server noun - **Wire [FIXED (owner-delegated), #48; shape #49].** The message is the dotless server noun
`marker`: `{full:bool, set:[{id, pos}], del:[id]}`, mirroring `encountered`'s full/set/del `marker`: `{full:bool, set:[{id, pos}], del:[id]}`, mirroring `encountered`'s full/set/del
spelling, with `pos` in integer px (the wall's drawn midpoint, rounded once) and `id` an opaque spelling, with `pos` in integer px (the wall's drawn midpoint, rounded once) and `id` an opaque
@@ -2013,7 +2016,9 @@ copy/export stable).
removed player takes their markers, a removed scene takes them through its walls, and a removed removed player takes their markers, a removed scene takes them through its walls, and a removed
wall retracts its marker for everyone (5.8's retraction rule; the composite FK is why a marker wall retracts its marker for everyone (5.8's retraction rule; the composite FK is why a marker
can never dangle). The other retraction causes (`player_marker` off, no longer a window, can never dangle). The other retraction causes (`player_marker` off, no longer a window,
geometry moved) are a deliberate delete in the update path, not an FK. geometry moved) are a deliberate delete in the update path, not an FK; that delete commits in
the same FULL transaction as the wall row, so a crash before the derived-memory write cannot
restore a marker with the changed wall's new geometry.
- **Migration [FIXED (owner decision), 2026-11-17, #49].** Step 8 (4.4) rebuilds `wall` and maps - **Migration [FIXED (owner decision), 2026-11-17, #49].** Step 8 (4.4) rebuilds `wall` and maps
every existing row to today's behaviour (`thickness 0`, `position center`, both block switches every existing row to today's behaviour (`thickness 0`, `position center`, both block switches
1, `sight_dir both`, `player_marker`/`secret`/`locked` 0, `height`/`label` NULL; `kind='door'` 1, `sight_dir both`, `player_marker`/`secret`/`locked` 0, `height`/`label` NULL; `kind='door'`
+3 -1
View File
@@ -462,7 +462,9 @@ from the prototype, what was missing, what the M3 build added, and the tools it
and marked solid wall as the negative controls. The WS group `tools/markers.test.mjs` proves the 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 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 `set` and `del` for one id in a frame, no explored write from a pure retraction, and durability
of the deletes across a restart. of the deletes across a restart. A `LEAK_FAULT=markerCrash` hook quits in a `-d:leakfault` build
between the wall commit and the derived write; after a restart the changed wall's marker is gone
for all four causes while the untouched window's marker is restored (the positive control).
- **Wall fields, storage and migration (#49).** Three gates. **Leak:** `BannedAlways` contains every - **Wall fields, storage and migration (#49).** Three gates. **Leak:** `BannedAlways` contains every
wall field name (`thickness`, `position`, `height`, `blocks_sight`, `blocks_movement`, `sight_dir`, 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 `player_marker`, `door`, `open`, `secret`, `locked`, `label`, `a`, `b`), so any of them in a player
+6
View File
@@ -12,3 +12,9 @@ proc faultActive*(name: string): bool =
getEnv("LEAK_FAULT") == name getEnv("LEAK_FAULT") == name
else: else:
false false
proc crashNow*() =
## `-d:leakfault` only: die at a chosen point with no shutdown, modelling a hard kill between two
## transactions (the `markerCrash` hook, TESTING 10.3, #60). A shipped build has no death path.
when defined(leakfault):
quit(70)
+12 -7
View File
@@ -232,7 +232,8 @@ proc recordEncounters() =
# --------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------
# Derived player memory persistence: explored cells and player markers (DESIGN 4.2 step 6, 4.4, 5.8; # Derived player memory persistence: explored cells and player markers (DESIGN 4.2 step 6, 4.4, 5.8;
# M3 slice 6 / #21, #59). Both live in memory and reach the DB only here. One rule: a mutation writes # M3 slice 6 / #21, #59). Both live in memory and reach the DB here, except a marker cause-change
# delete, which `world.updateWall` commits with the wall row (5.8, #60). One rule: a mutation writes
# exactly the explored chunks its refresh dirtied and the markers it minted, never the whole state, # 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 # and the write rides in the mutation's transaction so an ack cannot precede what it reports. NORMAL
# durability (Q12): both are derived (explored only grows; a marker is minted and retracted by the # durability (Q12): both are derived (explored only grows; a marker is minted and retracted by the
@@ -254,8 +255,8 @@ proc persistMarkers(pids: openArray[int]) =
## The marker half alone, for a connect where the explored grid must stay exactly as it was (a ## 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 ## 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). The deletes run ## 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 ## before the inserts: a moved wall's old rows are already gone (the wall transaction took them),
## both are the same derived-memory transaction. ## and a fresh one is stored after them, so one id can never be set and deleted in one refresh.
for pid in pids: for pid in pids:
if pid == GmControlled: continue if pid == GmControlled: continue
discard markers.writeDead(app.db, pid, discard markers.writeDead(app.db, pid,
@@ -264,10 +265,10 @@ proc persistMarkers(pids: openArray[int]) =
app.visions.mgetOrPut(pid, PlayerVision()).markerFresh) app.visions.mgetOrPut(pid, PlayerVision()).markerFresh)
proc persistDerived(pids: openArray[int]) = proc persistDerived(pids: openArray[int]) =
## Writes the dirtied explored chunks and the markers the same refresh minted or retracted (5.8: ## Writes the dirtied explored chunks and the markers the same refresh minted (5.8: marker inserts
## marker inserts and deletes are in the same derived-memory transaction as the explored chunks, ## ride the same derived-memory transaction as the explored chunks, after the wall row committed;
## after the wall row commits). No transaction of its own: the caller wraps it together with the ## a cause-change delete already committed with that row). No transaction of its own: the caller
## mutation's row writes. ## wraps it together with the mutation's row writes.
let chunks = dirtyExplored(pids) let chunks = dirtyExplored(pids)
if chunks.len > 0: discard explored.writeChunks(app.db, app.scene.id, chunks) if chunks.len > 0: discard explored.writeChunks(app.db, app.scene.id, chunks)
persistMarkers(pids) persistMarkers(pids)
@@ -2151,6 +2152,10 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
var mr = moveScene(app.scene, app.tokens) var mr = moveScene(app.scene, app.tokens)
outcome = updateWall(app.db, app.scene, candidate.get) outcome = updateWall(app.db, app.scene, candidate.get)
if outcome == waOk: if outcome == waOk:
when defined(leakfault):
# LEAK_FAULT=markerCrash (TESTING 10.3, #60): die between the wall commit and the
# derived-memory transaction, to prove the marker deletes commit with the wall row.
if faultActive("markerCrash"): crashNow()
let updated = wallById(app.scene, id) let updated = wallById(app.scene, id)
discard moverules.updateWall(mr, idx, ruleWall(updated.get)) discard moverules.updateWall(mr, idx, ruleWall(updated.get))
discard applyRuleOutcome(mr) discard applyRuleOutcome(mr)
+12 -13
View File
@@ -9,9 +9,10 @@
## ##
## The marker is per-player memory like explored: it is minted once, gets that player's own opaque ## The marker is per-player memory like explored: it is minted once, gets that player's own opaque
## 12-character id (never the wall id), keeps the wall's drawn midpoint rounded once as its anchor, ## 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 ## and is persisted in `marker_seen`: a cause-change retraction's delete commits with the wall row
## chunks (4.2 step 6). `vision.PlayerVision.markers` holds it in memory and `restore` loads it at ## itself (so a crash cannot restore it), while a mint rides the derived-memory transaction with the
## startup, before the first connection (4.4). ## 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).
## ##
## Lifetime (5.8, #60): walking away, a door and lost sight never retract a marker. The GM's causes ## 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 ## do: removing the wall, clearing `player_marker`, making the wall stop deriving `window`, or
@@ -32,11 +33,9 @@ proc anchorOf*(w: WallRec): (int, int) =
(int(round((w.a.x + w.b.x) / 2.0)), int(round((w.a.y + w.b.y) / 2.0))) (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 = proc wallSig(w: WallRec): string =
## Everything whose change retracts a marker (5.8, #60): endpoints, thickness, placement, the ## Alias for the shared signature in `world` (5.8, #60): the write path deletes the persisted
## `player_marker` switch and the derived `window` gate. Height and label have no marker ## rows by the same rule the online retraction uses.
## consequence and are deliberately absent. markerSig(w)
$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 = 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 ## True when any point of the wall's visible extent (the segment in this round) is inside one of
@@ -128,11 +127,11 @@ proc writeNew*(db: DbConn, sceneId, playerId: int, fresh: var seq[(int, Marker)]
fresh.setLen(0) fresh.setLen(0)
proc writeDead*(db: DbConn, playerId: int, dead: var seq[string]): int = 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 ## Deletes the markers the last refresh retracted for one player and clears the buffer. A wall
## transaction and ordering rule as `writeNew` (5.8, 4.2 step 6): derived player memory rides the ## cause change already took its rows in the wall row's own `FULL` transaction (`world.updateWall`)
## mutation's `NORMAL` transaction, after the wall row commits and before the ack, so a ## and a removal took its rows through the composite FK cascade, so this is normally a no-op; it
## retraction's `del` can never precede the wall change it reports. A wall removal already took ## stays as the idempotent backstop for the live `del` frames, in the same `NORMAL` transaction and
## its rows through the composite FK cascade, so that delete is a no-op here (and still correct). ## ordering rule as `writeNew` (5.8, 4.2 step 6).
if dead.len == 0: return 0 if dead.len == 0: return 0
let ps = db.prepare(DeleteSql) let ps = db.prepare(DeleteSql)
try: try:
+14
View File
@@ -158,6 +158,14 @@ proc derivedKind*(w: WallRec): string =
else: else:
"custom" "custom"
proc markerSig*(w: WallRec): string =
## The marker cause signature of DESIGN 5.8: exactly the wall fields whose change retracts a
## player marker — endpoints, thickness, placement, the `player_marker` switch and the derived
## `window` gate. Height and label have no marker consequence and are deliberately absent. Shared
## with `server/markers.nim` so the online retraction and the write-time delete cannot drift.
$w.a.x & "," & $w.a.y & "," & $w.b.x & "," & $w.b.y & "," &
$w.thickness & "," & $w.position & "," & $w.playerMarker & "," & derivedKind(w)
# --------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------
# The one expand-and-validate path for wall writes (DESIGN 5.8, 6.1 FIXED #49/#55) # The one expand-and-validate path for wall writes (DESIGN 5.8, 6.1 FIXED #49/#55)
@@ -485,12 +493,18 @@ proc addWall*(db: DbConn, sc: var SceneRec, rec: WallRec): Option[int] =
proc updateWall*(db: DbConn, sc: var SceneRec, rec: WallRec): WallApply = proc updateWall*(db: DbConn, sc: var SceneRec, rec: WallRec): WallApply =
## `wall.update` = full replacement of the patched row (`remove + add` for the 5.5 status rules, ## `wall.update` = full replacement of the patched row (`remove + add` for the 5.5 status rules,
## which slice 5 re-evaluates). Clearing the door switch closes and de-secrets the wall. ## which slice 5 re-evaluates). Clearing the door switch closes and de-secrets the wall.
## A marker cause change (5.8, #60) takes the affected `marker_seen` rows in this same FULL
## transaction: on a crash before the derived-memory write, a survivor would be restored on
## restart with the NEW geometry, revealing a position the player never saw.
let idx = wallIndex(sc, rec.id) let idx = wallIndex(sc, rec.id)
if idx.isNone: return waNotFound if idx.isNone: return waNotFound
let stored = normalize(rec) let stored = normalize(rec)
if not validWall(sc, stored): return waInvalid if not validWall(sc, stored): return waInvalid
let sigChanged = markerSig(stored) != markerSig(sc.walls[idx.get])
authoringTransaction(db): authoringTransaction(db):
replaceRow(db, sc.id, stored) replaceRow(db, sc.id, stored)
if sigChanged:
db.exec(sql"DELETE FROM marker_seen WHERE scene_id = ? AND wall_id = ?", sc.id, stored.id)
sc.walls[idx.get] = stored sc.walls[idx.get] = stored
waOk waOk
+95
View File
@@ -394,3 +394,98 @@ test('marker retraction is durable: delete and cascade survive a restart (#60)',
fs.rmSync(stateDir, { recursive: true, force: true }) fs.rmSync(stateDir, { recursive: true, force: true })
} }
}) })
// -------------------------------------------------------------------------------------------------
// #60 leak fix: a cause change and its `marker_seen` deletes are one commit.
//
// The bug: `wall.update` committed the wall row in its FULL transaction, but the retraction deletes
// rode the later NORMAL derived-memory transaction. A crash in between left the stale row; on
// restart `markers.restore` recomputed the anchor from the NEW wall, so a player who never saw the
// new geometry got it handed to them in the full marker set. The fix puts the deletes in the wall
// transaction, exactly as the FK cascade already does for `wall.remove`.
//
// The `LEAK_FAULT=markerCrash` hook (a `-d:leakfault` build only, never shipped) quits the process
// immediately after the wall commit and before the derived write. Each case then restarts on a clean
// build: the changed wall's old marker must not come back, while an untouched window's marker must
// be restored unchanged (the positive control, so the harness can fail).
async function waitProcessExit(handle, timeoutMs = 5000) {
const deadline = Date.now() + timeoutMs
while (handle.child.exitCode === null && handle.child.signalCode === null &&
Date.now() < deadline) {
await sleep(20)
}
assert.ok(handle.child.exitCode !== null || handle.child.signalCode !== null,
'the markerCrash fault did not kill the server')
}
async function markerCrashCase({ cause, patch, newAnchor, reEarns }) {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
let alice
let s = await startServer({ stateDir, defines: ['leakfault'],
env: { LEAK_FAULT: 'markerCrash' } })
let winMarker
let keepMarker
try {
const gm = await gmConnect(s.origin, gmKey)
// Two marked windows in the subject's sight: one is edited into a cause change, the other is
// untouched and is the positive control across the restart.
const changed = await addWall(gm, { preset: 'window', a: [200, 500], b: [200, 700] })
await addWall(gm, { preset: 'window', a: [400, 300], b: [400, 400] })
alice = await namedPlayer(gm, s.origin, `Crash ${cause}`)
await addSightToken(gm, alice, [300, 320])
const seen = await alice.conn.ws.waitFor(m => m.t === 'marker' && m.set.length === 2)
winMarker = seen.set.find(e => e.pos[0] === 200).id
keepMarker = seen.set.find(e => e.pos[0] === 400).id
// Fire the wall write by hand (no awaited ack): the fault kills the process inside the handler,
// after the wall+delete commit and before the derived transaction that used to carry the delete.
gm.ws.sendText(JSON.stringify({ t: 'wall.update', scene: gm.scene, id: changed.id,
...patch, reqId: 9001 }))
await waitProcessExit(s)
assert.equal(alice.conn.ws.messages.some(m => m.t === 'marker' &&
(m.del ?? []).includes(winMarker)), false,
`${cause}: the process died before the live del was sent`)
} finally {
try { alice.conn.ws.close() } catch {}
await stopServer(s)
}
s = await startServer({ stateDir })
try {
const again = await openAs(s.origin, alice.key)
await again.ws.waitText('hello')
const full = await again.ws.waitFor(m => m.t === 'marker' && m.full === true)
const kept = full.set.find(e => e.pos[0] === 400 && e.pos[1] === 350)
assert.equal(kept?.id, keepMarker,
`${cause}: positive control, the untouched window's marker is restored with the same id`)
assert.equal(full.set.some(e => e.id === winMarker), false,
`${cause}: a restart never restores a marker whose wall cause changed`)
if (newAnchor) {
assert.equal(full.set.some(e => e.pos[0] === newAnchor[0] && e.pos[1] === newAnchor[1]), false,
`${cause}: the player never receives the changed wall's new anchor`)
}
if (reEarns) {
const fresh = full.set.find(e => !(e.pos[0] === 400 && e.pos[1] === 350))
assert.ok(fresh, `${cause}: the still-visible wall is re-earned only through the normal gate`)
assert.notEqual(fresh.id, winMarker, `${cause}: a re-earned marker gets a fresh id`)
}
again.ws.close()
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
}
test('marker cause change and deletes are one commit: a crash before the derived write (#60)',
async t => {
await t.test('endpoint move', () => markerCrashCase({
cause: 'endpoint move', patch: { a: [1000, 1000], b: [1000, 1200] }, newAnchor: [1000, 1100],
reEarns: false }))
await t.test('thickness', () => markerCrashCase({
cause: 'thickness', patch: { thickness: 7 }, reEarns: true }))
await t.test('player_marker off', () => markerCrashCase({
cause: 'player_marker off', patch: { player_marker: false }, reEarns: false }))
await t.test('no longer a window', () => markerCrashCase({
cause: 'no longer a window', patch: { blocks_sight: true }, reEarns: false }))
})