Files
FFF_vtt_frozen/tools/mutation.sh
T
SirStone 8e045b0ac8 names: per-player reveal, one encountered write path, link by update (#27, #29, #30)
name.reveal wrote the subject's actual name into the encountered row of every
player who had met it: the SQL had no player predicate, so the leak was silent
live and visible only after a restart. rewriteEncountered is now the one path
that keeps a snapshot in step with its subject: it rewrites the SQLite row and
the live in-memory entry together from the name rule, takes onlyPlayer for
name.reveal (every player for reveal_all), and also runs on a rename, a link
change and an owner change, so the wire and a post-restart reload cannot
disagree (#30). The DB-only renameEncountered*/revealEncountered* helpers are
gone, which is what let the two stores drift.

token.update {character_id} now drops the token's own two names as part of the
link patch (#29): a plain token can be linked, names supplied with a link stay
invalid and unlinking still needs both names.

Tests: tcharacters covers the per-player row, the DB/memory equality, the link
handover; restart.test.mjs builds three named players, reveals to one of them
and asserts the rows directly and the whole resync over SIGTERM/SIGKILL, plus a
mid-session rename; leak.mjs/leakcheck.nim pit two players on the same subject
and pin each entry's expected name (STALE_NAME). Mutations e1-e3 and the
repointed b2 pin the three rules.
2026-11-15 14:26:07 +01:00

203 lines
20 KiB
Bash
Executable File

#!/usr/bin/env bash
# usage: devbox run mutation (or tools/mutation.sh inside devbox shell)
# Mutation check on a TEMP COPY of server/ + tests/ + tools/ (the tree is never touched). One mutation per run, ALL
# tests/t*.nim are run. Control must pass; every mutation must fail >=1 expected test; a sed that changes nothing is an error.
# a: no +-RayEps rays | b: upper segment end exclusive | c: lower segment end exclusive (rayHit only)
# d1/d2: drop arm 1/2 of the shared-vertex fixture
# e: cellsTouched without the fill spans | f: escape rule without the crossing check | g: GM moves checked against walls
# h: capsule reduced to centre path + destination circle (prototype H10) | i: no step cap | j: blocked trigger needs centre-on-wall
# k: wall removal / door open clears stuck unconditionally (no KEEP) | l: GM moves never set/clear stuck
# m: door push goes to the wrong side first | n: door push skips the validity check | o: push ignores the previous-position rule
# p: token bucket never refills | q: reqId upper bound dropped | r: malformed flood never fires | s: frame counter frozen
# t: wall removal renumbers next_wall_id (the dense-id design, #3) | u: the id counter is not loaded from the DB
# v: the id counter is never written to the DB | w: a wall may stay open | x: zero-length walls accepted
# y: wall endpoints unchecked against the world bounds | z: door.set on a plain wall accepted | z2: persisted `open` loaded inverted
# aa: the egress sends every token (LOS and gm_only ignored) | ab: gm_only ignored in the view rule
# ac: a controlled token is not always visible | ad: no token_gone when a token leaves view
# ae: a player token frame carries the GM-only `kind` | af: explored forgets the cells outside the current polygon
# ag: the chunk row stride is dropped | ah: a cell coordinate used as a chunk coordinate | ai: restore forgets rows
# aj: chunks keyed by scene, not player | ak: a chunk rewrite ignored (INSERT OR IGNORE) | al: dirty chunks keyed by row only
# slice 8 (#23): av: everyone is told the actual name | aw: an unrevealed name lands in the snapshot
# ax: a rename tells a player an actual name it never knew | ay: a linked token may keep its own names
# az: in-use not enforced | b1: player.remove forgets the characters | b2: an encountered rename
# overwrites a name the player never knew | b3: cprops carries the character owner bucket |
# b4: a player is sent every character
# #27/#29/#30: the per-player reveal scope, the link patch's name handover and the live
# snapshot update. e1: a reveal rewrites every player's snapshot (the old subject-only
# SQL) | e2: the encountered rewrite updates the DB but not memory (live list stale) |
# e3: a link patch keeps the plain token's own names (every link attempt is invalid)
# slice 9 (#24): the canonical tile URL and the "any explored cell allows" gate
# c1: a tile is allowed without any explored cell | c2: every overlapping cell is required
# c3: an out-of-grid coordinate is accepted | c4: a leading-zero coordinate is canonical
# d3: scene.set accepts a patch with no field (slice 10, #25)
# Parallel: MUTATION_JOBS (default nproc/4) jobs, each in its own temp copy + nimcache; output collected, printed in fixed order.
# Tests run with FFF_MUTATION=1 (iteration counts ~/10, see tests/testutil.nim scaled()); only test files holding an expected
# test are run per mutation (control runs all). Debug build. Wrapped in systemd-inhibit (sleep:idle) when that works.
# Ctrl-C / TERM / EXIT: kills all jobs and removes the temp dir (fffmut.* under $TMPDIR or /tmp).
# Log: results/mutation.log
cd "$(dirname "$0")/.." || exit 1
PKGS=${NIMBLE_DIR:-$PWD/.devbox/nimble}/pkgs2 # mummy/db_connector for the new server modules
job() { # runs in its own session: $1 id $2 title $3 file to mutate $4 sed script ("" = control) $5 expected-failure regex
local id=$1 title=$2 file=$3 sedscr=$4 expect=$5 w=$T/$1/w res=$T/$1/res tfs tf out=$T/$1/out r=0 rr F verdict=ok rc=0
mkdir -p "$w"; cp -r server tests tools nim.cfg "$w"/
find "$w/tests" -maxdepth 1 -type f ! -name '*.nim' -delete
echo "## $id: $title" > "$res"
if [ -n "$sedscr" ]; then
sed -i "$sedscr" "$w/$file"
if cmp -s "$file" "$w/$file"; then
echo "MUTATION $id DID NOT APPLY (sed matched nothing)" >> "$res"; echo "## $id: sed no-op" >> "$res"
echo "$id: sed no-op" > "$T/$id/verdict"; echo 1 > "$T/$id/rc"; return
fi
{ echo "# diff $file -> mutated copy:"; diff "$file" "$w/$file" | sed 's/^/# /'; } >> "$res"
tfs=$(grep -lE "(test|suite) \".*($expect)" tests/t*.nim); [ -n "$tfs" ] || tfs=$(ls tests/t*.nim)
else tfs=$(ls tests/t*.nim); fi
: > "$out"
for tf in $tfs; do
(cd "$w" && nim c -r --hints:off --nimblePath:"$PKGS" --nimcache:"$T/$id/nc-$(basename "$tf" .nim)" "$tf") >> "$out" 2>&1; rr=$?
[ $rr -eq 0 ] || r=$rr
done
grep -E '\[(OK|FAILED)\]|Success|Failure|Error' "$out" | sed 's/^ *\.* */ /' >> "$res"
F=$(grep '\[FAILED\]' "$out" | grep -E "$expect")
{ echo "# test exit=$r; expected tests failed: $(printf '%s' "$F" | grep -c .)"; [ -n "$F" ] && echo "$F"; echo; } >> "$res"
if [ -z "$sedscr" ]; then [ $r -eq 0 ] || { verdict="CONTROL FAILED"; rc=1; }
else [ -n "$F" ] || { verdict="SURVIVED"; rc=1; }; fi
echo "$id: exit=$r expected_failed=$(printf '%s' "$F" | grep -c .) $verdict" > "$T/$id/verdict"; echo $rc > "$T/$id/rc"
}
if [ "$1" = __job ]; then shift; job "$@"; exit 0; fi
if [ -z "$MUT_INHIBITED" ] && systemd-inhibit --what=sleep:idle --who=mutation --why=test true 2>/dev/null; then
MUT_INHIBITED=1 exec systemd-inhibit --what=sleep:idle --who=mutation --why="mutation run" "$0" "$@"
fi
mkdir -p results
LOG=$PWD/results/mutation.log
JOBS=${MUTATION_JOBS:-$(( $(nproc) / 4 ))}; [ "$JOBS" -ge 1 ] || JOBS=1
export FFF_MUTATION=1
T=$(mktemp -d -t fffmut.XXXXXX)
PAA="the set of tokens follows the visibility rule"
AB="a gm_only token inside the LOS is not visible"
AC="a controlled token is always visible"
AD="leaving view sends"
AE="no GM-only field"
AF="moving adds cells and never forgets"
IDS=()
cleanup() { trap - EXIT INT TERM; local p; for p in "${PIDS[@]}"; do kill -TERM -- "-$p" 2>/dev/null; done; wait 2>/dev/null; rm -rf "$T"; }
trap cleanup EXIT; trap 'exit 130' INT; trap 'exit 143' TERM
NEW="shared endpoint: no leak at the vertex|'<' apex|every segment endpoint|rays nudged past a corner"
D="shared vertex: both arms required"
E="random visibility polygons|random simple polygons|corpus|prototype scene, all tokens|random wall fields|concave polygon|square polygon"
F="exactly on a wall: can step off|overlapping 10 px off|escape from a closed door|GM placement and GM move onto a wall"
G="GM: ignores walls, step cap and the lock"
H="corner clipping|leg of the path|diagonal squeeze past"
I="step cap|over-cap, blocked-by-wall|P1:|P2:"
J="wall added within r of the circle|Q14: a door closed"
K="KEEP:|GM manual clear inside|Q14: a door closed"
L="GM moves a stuck token|GM drops a token|GM manual clear inside|GM: ignores walls"
M="Q14: a door closed|push: centre on the door line|push: one side blocked|doorway: token in an open doorway|GM drops a token"
N="push: one side blocked|push: both sides invalid"
O="push: centre on the door line"
P="refill is continuous"
Q="reqId boundaries"
R="nine malformed frames are tolerated"
S="the frame counter starts at 1"
AA="the set of tokens follows the visibility rule"
AB="a gm_only token inside the LOS is not visible"
AC="a controlled token is always visible"
AD="leaving view sends"
AE="no GM-only field"
AF="moving adds cells and never forgets"
IDS=()
run() {
while [ "$(jobs -rp | wc -l)" -ge "$JOBS" ]; do wait -n; done
mkdir -p "$T/$1"; IDS+=("$1")
setsid env T="$T" FFF_MUTATION=1 "$0" __job "$@" & PIDS+=($!)
}
run control "unmutated copy (must pass)" server/geometry.nim "" ""
run a "remove the +-RayEps rays" server/geometry.nim '/angles.add ang [-+] RayEps/d' "$NEW"
run b "upper segment end exclusive" server/geometry.nim 's/u <= 1 + Eps/u < 1 - Eps/' "$NEW"
run c "lower segment end exclusive" server/geometry.nim 's/u >= -Eps/u > Eps/' "$NEW"
run d1 "shared-vertex fixture without arm 1" tests/tgeometry.nim 's/@\[arm1, arm2\] *# SHARED-VERTEX/@[arm2]/' "$D"
run d2 "shared-vertex fixture without arm 2" tests/tgeometry.nim 's/@\[arm1, arm2\] *# SHARED-VERTEX/@[arm1]/' "$D"
run e "cellsTouched without fill spans" server/geometry.nim '/for k in countup(0, xs\[row\].len - 2, 2)/d' "$E"
run f "escape rule without the crossing check" server/moverules.nim 's/if pathCrosses(s, d, w.a, w.b) or segDist(d, w.a, w.b) < r: return false/if segDist(d, w.a, w.b) < r: return false/' "$F"
run g "GM moves checked against walls" server/moverules.nim 's/^ if not inBounds(sc, d): return nack(s)$/ if not inBounds(sc, d) or not pathClear(sc.walls, s, d, sc.tokens[ti].radius): return nack(s)/' "$G"
run h "capsule = centre path + destination circle (prototype)" server/moverules.nim 's/elif segsCross(s, d, w.a, w.b) or segSegDist(s, d, w.a, w.b) < r: return false/elif segsCross(s, d, w.a, w.b) or segDist(d, w.a, w.b) < r: return false/' "$H"
run i "no step cap" server/moverules.nim '/if hypot(dd.x, dd.y) > stepCap(sc, sc.tokens\[ti\]): return nack(s)/d' "$I"
run j "stuck trigger needs the centre on the wall" server/moverules.nim 's/segDist(t.pos, w.a, w.b) < t.radius/segDist(t.pos, w.a, w.b) < 1e-9/' "$J"
run k "removal/open clears stuck unconditionally (no KEEP)" server/moverules.nim 's/if not overlapsAny(sc, sc.tokens\[i\]): sc.tokens\[i\].clearWalls()/sc.tokens[i].clearWalls()/' "$K"
run l "GM moves never set or clear stuck" server/moverules.nim '/^ if who.role == roleGM: sc.placeToken(ti)$/d' "$L"
run m "door push: wrong side first" server/moverules.nim 's/for sg in \[(if side > 0: 1.0 else: -1.0), (if side > 0: -1.0 else: 1.0)\]:/for sg in [(if side > 0: -1.0 else: 1.0), (if side > 0: 1.0 else: -1.0)]:/' "$M"
run n "door push: no validity check" server/moverules.nim 's/if inBounds(sc, p) and not overlapsAny(sc, tt): return (true, p)/return (true, p)/' "$N"
run o "door push: previous position ignored on the line" server/moverules.nim 's/side = if t.hasPrev: dot(t.prev - w.a, n) else: 0.0/side = 0.0/' "$O"
run p "token bucket never refills" server/protocol.nim '/r.tokens = min(r.burst/d' "$P"
run q "reqId upper bound dropped" server/protocol.nim 's/if reqId < 0 or reqId > MaxReqId: return/if reqId < 0: return/' "$Q"
run r "malformed flood never fires" server/protocol.nim 's/f.count >= MalformedFloodLimit/f.count > MalformedFloodLimit/' "$R"
run s "the frame counter never advances" server/conns.nim 's/ inc c.active\[i\].frames/ discard/' "$S"
# slice 4 (#19): the wall id counter (never reused, #3), the "a wall is never open" invariant, the
# 6.1 validation (a != b, in bounds) and the persisted door state.
TW="never reuses|id counter survives"
run t "wall removal renumbers next_wall_id" server/world.nim 's/^ sc\.walls\.delete idx\.get$/ sc.walls.delete idx.get; sc.nextWallId = sc.walls.len + 1/' "$TW"
run u "the id counter is not loaded from the DB" server/world.nim 's/nextWallId: parseInt(row\[10\])/nextWallId: 1/' "$TW"
run v "the id counter is never written to the DB" server/world.nim '/db.exec(sql"UPDATE scene SET next_wall_id/d' "$TW"
run w "a wall may stay open" server/world.nim 's/^ if result\.kind == wkWall: result\.open = false$/ discard/' "a wall is never open"
run x "zero-length walls accepted" server/world.nim 's/ (rec\.a\.x != rec\.b\.x or rec\.a\.y != rec\.b\.y) and inBounds/ inBounds/' "zero-length wall"
run y "wall endpoints unchecked against the world bounds" server/world.nim 's/p\.x >= 0 and p\.y >= 0 and p\.x <= sc\.w and p\.y <= sc\.h/p.x >= 0 and p.y >= 0/' "both endpoints must be inside"
run z "door.set accepted on a plain wall" server/world.nim '/if sc.walls\[idx.get\].kind != wkDoor: return waNotDoor/d' "wrong kinds are their own"
run z2 "persisted open state loaded inverted" server/world.nim 's/open: row\[6\] == "1",/open: row[6] == "0",/' "round-trip through a reload"
# slice 5 (#20): the view rule, the egress diff and the explored set
run aa "the egress ignores LOS, gm_only and ownership" server/views.nim 's/^ if not pv\[\]\.visibleTo(t, playerId): continue$/ if false: continue/' "$AA"
run ab "gm_only ignored by the view rule" server/vision.nim '/^ if t\.gmOnly: return false$/d' "$AB"
run ac "a controlled token is not always visible" server/vision.nim '/^ if t\.owner == playerId: return true$/d' "$AC"
run ad "no token_gone when a token leaves the view" server/views.nim 's/^ result\.add tokenGoneFrame(id)$/ discard/' "$AD"
run ae "a player token frame carries the GM-only kind" server/views.nim 's/ "statuses": statusKindsJson(v.statuses), "props": buckets/ "statuses": statusKindsJson(v.statuses), "props": buckets, "kind": "npc"/' "$AE"
run af "explored forgets cells outside the current polygon" server/vision.nim 's/^ for idx in added: pv\.explored\.incl idx$/ pv.explored = added/' "$AF"
# slice 6 (#21): the chunk format, the per-player keying, the upsert and the startup restore
run ag "the chunk row stride is dropped" server/explored.nim 's/((cy mod ChunkCells) \* ChunkCells) + (cx mod ChunkCells)/(cy mod ChunkCells) + (cx mod ChunkCells)/' "bitmap layout is pinned"
run ah "a cell coordinate is used as a chunk coordinate" server/explored.nim 's/^ cell div ChunkCells$/ cell/' "bitmap layout is pinned|one chunk covers 64x64"
run ai "restore forgets the decoded cells" server/explored.nim 's/^ result\.mgetOrPut(pid, PlayerVision())\.explored\.incl idx$/ discard/' "stored cells come back exactly"
run aj "explored chunks keyed by scene, not player" server/explored.nim 's/db\.exec(ps, c\.playerId, sceneId, c\.cx, c\.cy, c\.bits)/db.exec(ps, sceneId, sceneId, c.cx, c.cy, c.bits)/' "never mix"
run ak "a chunk rewrite is ignored" server/explored.nim 's/DO UPDATE SET bits = excluded\.bits"""$/DO NOTHING"""/' "replaces the bitmap"
run al "dirty chunks keyed by row only" server/explored.nim 's/^ let key = ccy \* sc\.chunkCols + ccx$/ let key = ccy/' "two chunks in one chunk row are both written"
# slice 7 (#22): the bucket filter, the caps, the status set/clear and the resize/grow rules
run am "the owner bucket reaches a non-controller" server/views.nim 's/propsOwner: (if mine: objectOf(t.props\[pbOwner\]) else: nil)/propsOwner: t.props[pbOwner]/' "never the gm bucket|gets the public bucket only"
run an "a new wall does not stick a token" server/moverules.nim 's/sc.tokens\[i\].stuckWalls = true/discard/' "wall added within r of the circle"
run ao "a shrink never clears the walls entries" server/moverules.nim 's/^ sc.tokens\[ti\]\.clearWalls()$/ discard/' "a squeeze from a failed grow clears|a shrink that still overlaps keeps"
run ap "the property cap is not enforced" server/props.nim '/and p\[bucket\]\.len >= MaxPropKeys/d' "64 keys per bucket|the 65th"
run aq "the grow push is skipped" server/moverules.nim 's/^ if not grew:$/ if true:/' "grow inside r of a wall pushes it out"
run ar "a failed grow is not flagged squeezed" server/moverules.nim '/^ sc.tokens\[ti\]\.squeezedWalls = true$/d' "grow with no room on either side squeezes"
run as "a failed door push sticks instead of squeezing" server/moverules.nim 's/^ sc.tokens\[i\]\.squeezedWalls = true$/ sc.tokens[i].stuckWalls = true/' "push: both sides invalid"
run at "one bucket budget shared by all buckets" server/props.nim 's/and p\[bucket\]\.len >= MaxPropKeys/and p[pbPublic].len >= MaxPropKeys/' "64 keys per bucket"
run au "a grow that already fits still pushes" server/moverules.nim 's/^ if not overlapsAny(sc, sc.tokens\[ti\]):$/ if false:/' "a grow that already fits does not move the token"
# slice 8 (#23): the name rule, the encountered snapshot, the token link, in-use, the transfer and
# the character buckets
run av "everyone is told the actual name" server/characters.nim 's/^ isOwner or revealAll or revealed$/ true/' "a character owner sees the actual name|a linked token borrows"
run aw "the encountered snapshot ignores what the player knows" server/characters.nim 's/actualName: (if knowsActual: some(n\.actual) else: none(string))/actualName: some(n.actual)/' "a first sighting records|a rename follows the subject"
run ax "a rename tells a player an actual name it never knew" server/characters.nim 's/ if e\.actualName\.isSome: result\.actualName = some(actual)/ result.actualName = some(actual)/' "a rename follows the subject"
run ay "a linked token may keep its own names" server/tokens.nim 's/ if t\.characterId\.isSome: t\.descriptiveName\.len == 0/ if false: t.descriptiveName.len == 0/' "a linked token carries no names"
run az "in-use is not enforced" server/characters.nim 's/^ if t\.characterId\.isSome and t\.characterId\.get == characterId: inc result$/ discard/' "a character still figured by a token is in use"
run b1 "player.remove forgets the characters" server/characters.nim 's/WHERE owner_player_id = ?", gmId, playerId)/WHERE owner_player_id = ? AND 0", gmId, playerId)/' "hands the player"
run b2 "an encountered rename overwrites a secret" server/characters.nim 's/actualName: (if knows: some(n\.actual) else: none(string))/actualName: some(n.actual)/' "a character rename"
run b3 "cprops carries the character owner bucket" server/views.nim 's/cpropsPublic: objectOf(if ch\.isSome and not ownsCharacter: ch\.get\.props\[pbPublic\]/cpropsPublic: objectOf(if ch.isSome and not ownsCharacter: ch.get.props[pbOwner]/' "cprops carries the character"
run b4 "a player is sent every character" server/views.nim 's/ if c\.owner != playerId: continue/ if false: continue/' "a player gets only its own characters"
run e1 "an encountered rewrite ignores what the player knows" server/characters.nim 's/let updated = e\.refreshed(n, knowsActual(/let updated = e.refreshed(n, true or knowsActual(/' "a link change moves the snapshot"
run e2 "an encountered rewrite updates the DB only" server/characters.nim 's/^ enc\[pid\]\[e\.entityId\] = e$/ discard/' "a character rename rewrites the live snapshots"
run e3 "a link patch keeps the token's own names" server/tokens.nim 's/^ if result\.characterId\.isSome:$/ if false:/' "linking through a patch hands the names over"
# slice 9 (#24): the tile URL grammar and the access rule (server/tiles.nim)
TILE_GATE="an unexplored tile is refused|a tile is allowed when any overlapping cell"
TILE_ZERO="leading zero tile coordinates"
TILE_RANGE="outside the grid is out of range"
run c1 "the tile gate ignores the explored set" server/tiles.nim 's/ if sc\.cellIndex(cx, cy) in explored: return true/ if true: return true/' "$TILE_GATE"
run c2 "the tile gate needs every overlapping cell" server/tiles.nim 's/ if sc\.cellIndex(cx, cy) in explored: return true/ if sc.cellIndex(cx, cy) notin explored: return false/' "$TILE_GATE"
run c3 "an out-of-grid tile coordinate is accepted" server/tiles.nim 's/^ x >= 0 and y >= 0 and x < tileCols(sc) and y < tileRows(sc)$/ x >= 0 and y >= 0/' "$TILE_RANGE"
run c4 "a leading-zero tile coordinate is canonical" server/tiles.nim "s/ if raw\[0\] == '0' and raw.len > 1: return false/ discard/" "$TILE_ZERO"
# slice 10 (#25): scene.set needs at least one patch field (server/world.nim parseScenePatch)
run d3 "scene.set accepts a patch with no field" server/world.nim 's/^ if not any: return none(ScenePatch)$/ discard/' "a patch with none is invalid"
wait
rc=0; : > "$LOG"
for id in control a b c d1 d2 d3 e e1 e2 e3 f g h i j k l m n o p q r s t u v w x y z z2 aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az b1 b2 b3 b4 c1 c2 c3 c4; do
[ -f "$T/$id/res" ] && cat "$T/$id/res" >> "$LOG"
if [ -f "$T/$id/verdict" ]; then tee -a "$LOG" < "$T/$id/verdict"; [ "$(cat "$T/$id/rc")" = 0 ] || rc=1
else echo "$id: NO RESULT (job killed?)" | tee -a "$LOG"; rc=1; fi
done
echo "exit=$rc" | tee -a "$LOG"
exit $rc