## Leak checker: replays a leak-transcript.jsonl written by tools/leak.mjs and verifies one player's ## whole view (DESIGN 10.1, 10.2, 10.3; M3 slice 5 / #20). Ground truth is the GM socket: the GM sees ## every token and every wall, so the checker never trusts the subject's own messages for *what is*. ## ## Independent oracles: the subject's visibility polygons and explored cells are recomputed from the ## GM's truth with geometry.nim, and the explored set is additionally probed with a clear-segment ## test (no ray fan), because the prototype's explored check was self-consistent only (10.2). ## ## Every failure carries a class, and tools/fault.test.mjs asserts the EXACT class set of each ## injected server fault: ## HIDDEN_TOKEN a token the subject may not see reached it ## GMONLY_TOKEN the same, for a `gm_only` token inside the subject's LOS ## WALLDATA a wall-ish key or frame reached the subject ## WITHHELD a token the subject may see was not sent (or was taken away while visible) ## NO_REMOVE a token that left the view was never withdrawn ## OWN_VIEW the subject's own token position or its vision polygon is wrong ## OTHER_PLAYER another player's polygon, `mine` flag, explored cells or presence leaked ## EXPLORED the explored set differs from the recomputation / the clear-segment oracle ## OWNER_PROP the `owner` property bucket reached someone who does not control the token ## GM_PROP the `gm` property bucket reached a player at all ## STATUS_SOURCE a player frame carried the `source` of a status (5.5, 6.1 note 6) ## GEOMETRY the recomputed polygon disagrees with the clear-segment oracle (sanity) ## PROTOCOL a frame the catalogue does not allow, a bad `n` sequence, a missing hello block ## ## usage: leakcheck exit 0 = clean import std/[algorithm, json, math, options, os, sets, strutils, tables] import geometry const AllowedTypes = ["hello", "ack", "token", "token_gone", "vision", "explored"] BannedKeys = ["walls", "wall", "wall_gone", "a", "b", "open", "kind", "controller", "gm_only", "flags", "descriptive_name", "actual_name", "reveal_all", "revealed", "source", "radius_own", "extra"] type TruthToken = object pos: Vec controller: int gmOnly: bool hasVision: bool visionRadius: Option[float] radius: float props: JsonNode ## the GM's three buckets (the truth for every bucket question) statuses: seq[string] ## the status names the GM sees, in order Truth = object walls: seq[Wall] tokens: Table[string, TruthToken] Group = object label: string gmMsgs: seq[JsonNode] subjMsgs: seq[JsonNode] var fails = 0 var classes: CountTable[string] proc fail(cls, s: string) = inc fails classes.inc cls if fails <= 25: echo "FAIL [", cls, "] ", s proc vec(j: JsonNode): Vec = (j[0].getFloat, j[1].getFloat) proc samePos(j: JsonNode, p: Vec): bool = ## JSON numbers lose their int/float spelling on the wire round trip: compare numerically. j.kind == JArray and j.len == 2 and abs(j[0].getFloat - p.x) < 1e-6 and abs(j[1].getFloat - p.y) < 1e-6 # --------------------------------------------------------------------------------------------------- # Transcript proc readGroups(path, subject: string): seq[Group] = ## One entry per group marker; every message belongs to the group that was open when it arrived. var current = -1 var groups: seq[Group] for line in lines(path): if line.strip.len == 0: continue let j = parseJson(line) case j["k"].getStr of "group": groups.add Group(label: j["label"].getStr) current = groups.high of "msg": if current < 0: continue let who = j["who"].getStr if who == "GM": groups[current].gmMsgs.add j["m"] elif who == subject: groups[current].subjMsgs.add j["m"] else: discard groups # --------------------------------------------------------------------------------------------------- # Truth from the GM socket (walls and every token) proc applyGmWalls(truth: var Truth, ids: var seq[int], m: JsonNode) = ## `wall` (upsert) and `wall_gone` need the id, which geometry.Wall does not carry. case m["t"].getStr of "walls": truth.walls.setLen(0) ids.setLen(0) for w in m["walls"]: truth.walls.add Wall(a: vec(w["a"]), b: vec(w["b"]), door: w["kind"].getStr == "door", open: w["open"].getBool) ids.add w["id"].getInt of "wall": let id = m["id"].getInt let w = Wall(a: vec(m["a"]), b: vec(m["b"]), door: m["kind"].getStr == "door", open: m["open"].getBool) var found = false for i in 0 ..< ids.len: if ids[i] == id: truth.walls[i] = w found = true if not found: truth.walls.add w ids.add id of "wall_gone": let id = m["id"].getInt for i in 0 ..< ids.len: if ids[i] == id: truth.walls.delete i ids.delete i break else: discard proc applyGmTokens(truth: var Truth, m: JsonNode) = case m["t"].getStr of "token": var t = TruthToken(pos: vec(m["pos"]), controller: (if m["controller"].kind == JNull: 0 else: m["controller"].getInt), gmOnly: m["gm_only"].getBool, hasVision: m["flags"].hasKey("vision") and m["flags"]["vision"].kind == JBool and m["flags"]["vision"].getBool, radius: m["radius"].getFloat) if m["vision_radius"].kind != JNull: t.visionRadius = some(m["vision_radius"].getFloat) t.props = m["props"] for st in m["statuses"]: t.statuses.add st["status"].getStr truth.tokens[m["id"].getStr] = t of "token_gone": truth.tokens.del m["id"].getStr else: discard # --------------------------------------------------------------------------------------------------- # Independent oracles proc clearLine(walls: seq[Wall], o, p: Vec): bool = ## The clear-segment oracle: no blocking wall between o and p (independent of the ray fan). for w in walls: if w.blocks and segsCross(o, p, w.a, w.b): return false true proc rangeOf(sceneDefault: float, t: TruthToken): float = if t.hasVision and t.visionRadius.isSome and t.visionRadius.get > 0: t.visionRadius.get else: sceneDefault proc polygonsOf(truth: Truth, controller: int, sceneDefault: float): seq[(string, seq[Vec])] = for id, t in truth.tokens: if t.controller != controller or not t.hasVision: continue result.add (id, visibilityPolygon(t.pos, truth.walls, rangeOf(sceneDefault, t))) # deterministic order: by token id (the server keeps creation order; the checker sorts) result.sort(proc (a, b: (string, seq[Vec])): int = cmp(a[0], b[0])) proc insideAny(polys: seq[(string, seq[Vec])], p: Vec): bool = for (_, pts) in polys: if inside(pts, p): return true proc cellOf(sceneW: float, cell: int, ix, iy: int): (float, float) = (float(ix * cell) + float(cell) / 2, float(iy * cell) + float(cell) / 2) proc definitelySeen(walls: seq[Wall], polys: seq[(string, seq[Vec])], sceneW: float, cell, cx, cy: int): bool = ## A cell is seen if any of its corners or its centre is in clear LOS inside a polygon. The ## tolerance for the opposite direction (explored but no sample in LOS) lives in the caller. let (mx, my) = cellOf(sceneW, cell, cx, cy) let pts = [(mx, my), (float(cx * cell), float(cy * cell)), (float((cx + 1) * cell), float(cy * cell)), (float((cx + 1) * cell), float((cy + 1) * cell)), (float(cx * cell), float((cy + 1) * cell))] for p in pts: if insideAny(polys, p) and clearLine(walls, (mx, my), p): return true false proc keysDeep(node: JsonNode, into: var HashSet[string]) = if node.kind == JObject: for k, v in node: into.incl k keysDeep(v, into) elif node.kind == JArray: for v in node: keysDeep(v, into) # --------------------------------------------------------------------------------------------------- proc checkArgs(): (string, string) = if paramCount() < 2: echo "usage: leakcheck " quit 2 (paramStr(1), paramStr(2)) proc main() = let (path, subject) = checkArgs() let groups = readGroups(path, subject) if groups.len == 0: echo "leakcheck: no groups in ", path quit 2 var truth: Truth var wallIds: seq[int] var me = 0 var other = 0 var sceneDefault = 400.0 var sceneW = 4096.0 var cell = 32 var haveHello = false var expectedN = 1 # what the subject has been told var view: Table[string, JsonNode] # token id -> last `token` frame var leaked: Table[string, string] # token id -> the class it was first reported under var exploredSent: HashSet[int] var otherExplored: HashSet[int] var removes = 0 var groupsSeen = 0 var recomputedSoFar: HashSet[int] # every cell the subject has ever seen, recomputed var seenAny: HashSet[string] # token ids the subject was legitimately shown for g in groups: inc groupsSeen for m in g.gmMsgs: applyGmWalls(truth, wallIds, m) applyGmTokens(truth, m) # player ids: the subject from its hello, the other from any token it does not control for m in g.subjMsgs: if m["t"].getStr == "hello": haveHello = true me = m["me"]["id"].getInt if m.hasKey("scene"): sceneW = m["scene"]["w"].getFloat cell = m["scene"]["cell"].getInt sceneDefault = m["scene"]["vision_radius_default"].getFloat else: fail "PROTOCOL", "hello without a scene block for a named player" for id, t in truth.tokens: if me != 0 and t.controller != me and t.controller != 0 and (other == 0 or t.controller < other): other = t.controller # Before the subject's hello there is no subject side to check: `me` is unknown, so "mine" and # "visible to the subject" would both be meaningless. Always apply the GM truth first. if me == 0: continue let polys = polygonsOf(truth, me, sceneDefault) let otherPolys = if other != 0: polygonsOf(truth, other, sceneDefault) else: @[] # the other player's explored cells, independently (attribute leaks, 3.1 OTHER_PLAYER) for (_, pts) in otherPolys: for (cx, cy) in cellsTouched(pts, float(cell)): if cx < 0 or cy < 0: continue otherExplored.incl cy * int(ceil(sceneW / float(cell))) + cx # --- the subject's frames of this group ----------------------------------------------------- for m in g.subjMsgs: let t = m["t"].getStr if not m.hasKey("n") or m["n"].getInt != expectedN: fail "PROTOCOL", "n " & (if m.hasKey("n"): $m["n"].getInt else: "missing") & " where " & $expectedN & " was expected (" & t & ")" expectedN = (if m.hasKey("n"): m["n"].getInt else: expectedN) + 1 if t notin AllowedTypes: fail (if t in ["walls", "wall", "wall_gone"]: "WALLDATA" else: "PROTOCOL"), "frame type the catalogue forbids: " & t continue var keys = initHashSet[string]() keysDeep(m, keys) for k in keys: if k == "source": # 5.5 / 6.1 note 6: a viewer sees the status, never what caused it. fail "STATUS_SOURCE", "player frame carries a status source" elif k in BannedKeys: fail "WALLDATA", "player frame has wall-ish/GM-only key " & k case t of "ack": # only a bad shape is interesting here; the driver already checked the outcomes it expected if m["ok"].getBool and m.hasKey("code"): fail "PROTOCOL", "ok ack with a code" of "token": let id = m["id"].getStr if id notin truth.tokens: fail "HIDDEN_TOKEN", "token " & id & " is not in the GM's truth" continue let actual = truth.tokens[id] # props: the public bucket always, the owner bucket only for the controller, the gm bucket # never (6.1 leak notes; the typed view has no field for it, so an injected fault shows here) var buckets = initHashSet[string]() if m.hasKey("props") and m["props"].kind == JObject: for name, _ in m["props"]: buckets.incl name if "gm" in buckets: fail "GM_PROP", "token " & id & " carried the gm property bucket to a player" # A frame that claims `mine` is the OTHER_PLAYER fault's shape: the bucket then matches the # (wrong) claim, so the claim itself is what gets reported, not the bucket. if "owner" in buckets and not (actual.controller == me) and not m["mine"].getBool: fail "OWNER_PROP", "token " & id & " carried the owner bucket to a non-controller" if actual.controller == me and "owner" notin buckets: fail "OWNER_PROP", "the controller is missing the owner bucket of token " & id if m.hasKey("props"): for name in ["public", "owner"]: if name notin buckets or not actual.props.hasKey(name): continue if m["props"][name] != actual.props[name]: fail (if name == "public": "OWN_VIEW" else: "OWNER_PROP"), "token " & id & " has a " & name & " bucket that is not the truth" # statuses: the names the GM sees, and nothing else on the entry var gotStatuses: seq[string] for st in m["statuses"]: if st.len != 1: fail "STATUS_SOURCE", "a player status entry carries more than `status`" gotStatuses.add st["status"].getStr if gotStatuses != actual.statuses: fail "OWN_VIEW", "token " & id & " statuses " & $gotStatuses & " != truth " & $actual.statuses if not samePos(m["pos"], actual.pos): fail "OWN_VIEW", "token " & id & " position " & $m["pos"] & " != truth " & $[actual.pos.x, actual.pos.y] let wantMine = actual.controller == me if m["mine"].getBool != wantMine: fail (if wantMine: "OWN_VIEW" else: "OTHER_PLAYER"), "mine flag on " & id view[id] = m let visible = wantMine or (not actual.gmOnly and insideAny(polys, actual.pos)) if not visible: let cls = if actual.gmOnly and insideAny(polys, actual.pos): "GMONLY_TOKEN" else: "HIDDEN_TOKEN" leaked[id] = cls fail cls, "token " & id & " sent but not visible (group " & g.label & ")" else: seenAny.incl id of "token_gone": let id = m["id"].getStr if id notin view: fail "PROTOCOL", "token_gone for a token this player never had: " & id else: view.del id inc removes if id in truth.tokens: let actual = truth.tokens[id] if actual.controller == me or (not actual.gmOnly and insideAny(polys, actual.pos)): fail "WITHHELD", "token_gone for a token still visible: " & id of "vision": var got: seq[(string, seq[Vec])] for p in m["polys"]: var pts: seq[Vec] for q in p["pts"]: pts.add vec(q) got.add (p["id"].getStr, pts) let want = polys var haveIds = initHashSet[string]() for (id, pts) in got: haveIds.incl id var matched = false for (wid, wpts) in want: if wid != id: continue matched = true if pts.len != wpts.len: fail "OWN_VIEW", "polygon " & id & " has " & $pts.len & " of " & $wpts.len & " vertices" else: for i in 0 ..< pts.len: # integer px on the wire (6.4): 0.5 px is the documented tolerance if abs(pts[i].x - wpts[i].x) > 0.5 + 1e-6 or abs(pts[i].y - wpts[i].y) > 0.5 + 1e-6: fail "OWN_VIEW", "polygon " & id & " vertex " & $i & " is " & $pts[i] & " not " & $wpts[i] break if not matched: var theirs = false for (oid, _) in otherPolys: if oid == id: theirs = true fail (if theirs: "OTHER_PLAYER" else: "PROTOCOL"), "vision carries a polygon for a token this player does not control: " & id for (id, _) in want: if id notin haveIds: fail "OWN_VIEW", "vision is missing the polygon of " & id of "explored": if m["full"].getBool: # a resync snapshot replaces the set; every cell must be one the recomputation has seen var cells: seq[(int, int)] let cols = int(ceil(sceneW / float(cell))) for row in m["rle"]: let cy = row[0].getInt var i = 1 while i + 1 < row.len: let x0 = row[i].getInt let len = row[i + 1].getInt for k in 0 ..< len: cells.add (x0 + k, cy) i += 2 discard cols exploredSent = initHashSet[int]() for (cx, cy) in cells: exploredSent.incl cy * int(ceil(sceneW / float(cell))) + cx else: for c in m["cells"]: let cx = c[0].getInt let cy = c[1].getInt let k = cy * int(ceil(sceneW / float(cell))) + cx exploredSent.incl k else: discard # --- the set of tokens the subject should hold at the end of this group --------------------- for id, actual in truth.tokens: let want = actual.controller == me or (not actual.gmOnly and insideAny(polys, actual.pos)) let have = view.hasKey(id) if want and not have: fail "WITHHELD", "visible token never sent: " & id & " (group " & g.label & ")" elif not want and have: # A token that was never legitimately in view stays a leak under its first class; one that # was legitimately seen and is now invisible is a missing withdrawal. `seenAny` decides, # so a `gm_only` flip after a legitimate sighting is not re-labelled as a gm_only leak. if leaked.hasKey(id): fail leaked[id], "leaked token still in view: " & id elif id notin seenAny and actual.gmOnly and insideAny(polys, actual.pos): fail "GMONLY_TOKEN", "gm_only token still in view: " & id else: fail "NO_REMOVE", "token left the view and was never withdrawn: " & id & " (group " & g.label & ")" elif want and have: if not samePos(view[id]["pos"], actual.pos): fail "OWN_VIEW", "stale position for " & id # --- the explored set ---------------------------------------------------------------------- var recomputed: HashSet[int] let cols = int(ceil(sceneW / float(cell))) let rows = int(ceil(sceneW / float(cell))) for (_, pts) in polys: for (cx, cy) in cellsTouched(pts, float(cell)): # cells outside the world are not cells: the server drops them too (vision.refresh) if cx < 0 or cy < 0 or cx >= cols or cy >= rows: continue recomputed.incl cy * cols + cx for k in recomputed: recomputedSoFar.incl k var suspect = initCountTable[string]() for k in exploredSent: # explored only grows (5.1): a cell seen in an earlier group is legitimately explored now if k in recomputedSoFar: continue let cx = k mod cols let cy = k div cols if definitelySeen(truth.walls, polys, sceneW, cell, cx, cy): recomputed.incl k # grazed cell the sampler does see: fine either way continue # attribution: a cell only the other player has explored is a presence leak, not a bad cell let cls = if k in otherExplored: "OTHER_PLAYER" else: "EXPLORED" suspect.inc(cls) if suspect[cls] <= 3: fail cls, "explored cell (" & $cx & "," & $cy & ") is outside the subject's sight (group " & g.label & ")" for cls, n in suspect: if n > 3: fail cls, $n & " explored cells the subject never saw (group " & g.label & ")" # completeness: every cell the recomputation says is seen must have been sent var missing = 0 for k in recomputed: if k notin exploredSent: inc missing if missing <= 3: fail "EXPLORED", "recomputed explored cell never sent: " & $k if missing > 3: fail "EXPLORED", $missing & " recomputed explored cells were never sent" if getEnv("LEAK_DEBUG") != "": for (id, pts) in polys: var cx0 = 100000; var cx1 = -1; var cy0 = 100000; var cy1 = -1 for (cx, cy) in cellsTouched(pts, float(cell)): cx0 = min(cx0, cx); cx1 = max(cx1, cx); cy0 = min(cy0, cy); cy1 = max(cy1, cy) echo " poly ", id, " verts ", pts.len, " cells x ", cx0, "..", cx1, " y ", cy0, "..", cy1, " group ", g.label, " cell ", cell, " sceneW ", sceneW # --- the clear-segment oracle on the polygon itself ----------------------------------------- for (id, pts) in polys: if pts.len < 3: continue var t: TruthToken for tid, tt in truth.tokens: if tid == id: t = tt let o = t.pos let r = rangeOf(sceneDefault, t) for i in 0 ..< 64: for k in [0.3, 0.6, 0.95]: let p: Vec = (o.x + k * r * cos(2 * PI * i.float / 64), o.y + k * r * sin(2 * PI * i.float / 64)) if p.x < 0 or p.y < 0 or p.x > sceneW or p.y > sceneW: continue if clearLine(truth.walls, o, p) and not inside(pts, p): fail "GEOMETRY", "polygon " & id & " misses a clear-LOS point " & $p if not haveHello: fail "PROTOCOL", "no hello for the subject" if me == 0: fail "PROTOCOL", "no player id in hello" 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" for cls, n in classes: echo "FAILCLASS ", cls, " ", n echo "leakcheck: subject ", subject, " (player ", me, "), ", groupsSeen, " groups, ", view.len, " tokens in view at the end, ", removes, " withdrawals, ", exploredSent.len, " explored cells, ", fails, " failures" quit(if fails > 0: 1 else: 0) main()