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
+11 -5
View File
@@ -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)
+74 -15
View File
@@ -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.
+3 -3
View File
@@ -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]
+14 -6
View File
@@ -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)] =