Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: drain lease TLA+ model, runner, mutants

garrytanb20046c2073b
diff --git a/scripts/spec/mutants.ts b/scripts/spec/mutants.ts
new file mode 100644
index 0000000000..7b41e5b3f2
--- /dev/null
+++ b/scripts/spec/mutants.ts
@@ -0,0 +1,112 @@
+#!/usr/bin/env bun
+/**
+ * Guard mutants for the TLA+ specs (spec/tla/README.md). Each mutant in spec/tla/<spec>/mutants.json removes one guard:
+ *
+ * - its `spec` edit is applied to a copy of the model, and TLC must report the named property (or nothing, for a
+ * mutant marked `survives`: a guard that is defense in depth at these bounds);
+ * - its `code` edit, when present, is applied to the implementation, and the named test must fail under it and pass
+ * without it. That ties each guard the model relies on to the line that implements it and the test that pins it.
+ *
+ * bun scripts/spec/mutants.ts [<spec>] [--only <id>] [--spec-only | --code-only] [--require-postgres]
+ *
+ * Failure codes: MUTANT_STALE (an edit's `before` text is not found exactly once: the spec or code moved; update the
+ * mutant), MUTANT_SURVIVED (TLC found no violation, or the test passed under the code edit: a property or a test no
+ * longer catches the guard), MUTANT_WRONG_PROPERTY, MUTANT_INCOMPLETE (TLC did not finish, or the test failed without
+ * the edit), MUTANT_DIRTY (the code file has uncommitted changes; the runner edits it in place and restores it).
+ */
+import { spawnSync } from 'node:child_process';
+import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+
+interface Edit { file: string; before: string; after: string }
+interface CodeEdit extends Edit { test: string; filter: string; postgres?: boolean }
+interface Mutant { id: string; title: string; expect: string; reason?: string; spec: Edit; code?: CodeEdit }
+interface Catalog { module: string; config: string; mutants: Mutant[] }
+
+const ROOT = resolve(import.meta.dir, '../..');
+const args = process.argv.slice(2);
+const flag = (name: string) => args.includes(name);
+const only = args.includes('--only') ? args[args.indexOf('--only') + 1] : undefined;
+const specName = args.find((a, i) => !a.startsWith('--') && args[i - 1] !== '--only') ?? 'drain-lease';
+const specDir = join(ROOT, 'spec/tla', specName);
+const catalog = JSON.parse(readFileSync(join(specDir, 'mutants.json'), 'utf8')) as Catalog;
+const out = process.env.TLC_OUT ?? join(ROOT, '.context/tlc');
+const timeoutS = Number(process.env.TLC_TIMEOUT_S ?? 300);
+const failures: string[] = [];
+const fail = (code: string, id: string, message: string) => { failures.push(`${code} ${id}: ${message}`); console.error(`FAIL ${code} ${id}: ${message}`); };
+
+function applyOnce(text: string, edit: Edit): string | null {
+ const at = text.indexOf(edit.before);
+ if (at < 0 || text.indexOf(edit.before, at + 1) >= 0) return null;
+ return text.slice(0, at) + edit.after + text.slice(at + edit.before.length);
+}
+
+function jar(): string {
+ const r = spawnSync('bash', [join(ROOT, 'scripts/spec/tla-jar.sh')], { encoding: 'utf8' });
+ if (r.status !== 0) { process.stderr.write(r.stderr); process.exit(2); }
+ return r.stdout.trim();
+}
+
+function runSpec(m: Mutant, tla2tools: string): void {
+ const work = join(out, `mutant-${specName}-${m.id}`);
+ rmSync(work, { recursive: true, force: true });
+ mkdirSync(join(work, 'tmp'), { recursive: true });
+ for (const f of [`${catalog.module}.tla`, catalog.config]) cpSync(join(specDir, f), join(work, f));
+ const target = join(work, m.spec.file);
+ const mutated = applyOnce(readFileSync(target, 'utf8'), m.spec);
+ if (mutated === null) return fail('MUTANT_STALE', m.id, `spec text not found exactly once in ${m.spec.file}: ${JSON.stringify(m.spec.before)}`);
+ writeFileSync(target, mutated);
+ const r = spawnSync('java', ['-XX:+UseParallelGC', `-Djava.io.tmpdir=${join(work, 'tmp')}`, '-cp', tla2tools, 'tlc2.TLC', '-workers', 'auto',
+ '-config', catalog.config, '-metadir', join(work, 'states'), `${catalog.module}.tla`], { cwd: work, encoding: 'utf8', timeout: timeoutS * 1000 });
+ const log = `${r.stdout ?? ''}${r.stderr ?? ''}`;
+ writeFileSync(join(work, 'tlc.log'), log);
+ const violated = log.match(/(?:Invariant|Action property|Property) (\w+) is violated/)?.[1];
+ const clean = log.includes('Model checking completed. No error has been found.');
+ if (m.expect === 'survives') {
+ if (clean) return void console.log(`ok ${m.id}: survives as expected (defense in depth)`);
+ if (violated) return fail('MUTANT_WRONG_PROPERTY', m.id, `expected to survive, but ${violated} is violated: the guard is now load-bearing; give it an expect and a code test. Log: ${work}/tlc.log`);
+ return fail('MUTANT_INCOMPLETE', m.id, `TLC did not finish (exit ${r.status ?? r.signal}). Log: ${work}/tlc.log`);
+ }
+ if (violated === m.expect) return void console.log(`ok ${m.id}: caught by ${violated}`);
+ if (violated) return fail('MUTANT_WRONG_PROPERTY', m.id, `expected ${m.expect}, but ${violated} caught it. Log: ${work}/tlc.log`);
+ if (clean) return fail('MUTANT_SURVIVED', m.id, `no property caught "${m.title}"; ${m.expect} no longer depends on this guard. Log: ${work}/tlc.log`);
+ fail('MUTANT_INCOMPLETE', m.id, `TLC did not finish (exit ${r.status ?? r.signal}). Log: ${work}/tlc.log`);
+}
+
+function bunTest(code: CodeEdit): { ok: boolean; tail: string } {
+ const r = spawnSync('bun', ['test', '--timeout=300000', code.test, '-t', code.filter], { cwd: ROOT, encoding: 'utf8', env: process.env, timeout: 600_000 });
+ const text = `${r.stdout ?? ''}${r.stderr ?? ''}`;
+ const ran = /\b[1-9]\d* pass\b|\b[1-9]\d* fail\b/.test(text);
+ return { ok: r.status === 0 && ran, tail: text.split('\n').slice(-12).join('\n') };
+}
+
+function runCode(m: Mutant): void {
+ const code = m.code!;
+ if (code.postgres && !process.env.DATABASE_URL) {
+ if (flag('--require-postgres')) return fail('MUTANT_INCOMPLETE', m.id, `${code.test} needs DATABASE_URL (a test Postgres)`);
+ return void console.log(`skip ${m.id} (code): ${code.test} needs DATABASE_URL`);
+ }
+ const file = join(ROOT, code.file);
+ const dirty = spawnSync('git', ['status', '--porcelain', '--', code.file], { cwd: ROOT, encoding: 'utf8' }).stdout.trim();
+ if (dirty) return fail('MUTANT_DIRTY', m.id, `${code.file} has uncommitted changes; commit or stash them first`);
+ const original = readFileSync(file, 'utf8');
+ const mutated = applyOnce(original, code);
+ if (mutated === null) return fail('MUTANT_STALE', m.id, `code text not found exactly once in ${code.file}: ${JSON.stringify(code.before)}`);
+ const base = bunTest(code);
+ if (!base.ok) return fail('MUTANT_INCOMPLETE', m.id, `${code.test} -t "${code.filter}" does not pass (or matched no test) without the edit:\n${base.tail}`);
+ try {
+ writeFileSync(file, mutated);
+ const under = bunTest(code);
+ if (under.ok) return fail('MUTANT_SURVIVED', m.id, `${code.test} -t "${code.filter}" passes with ${code.file} edited; the test no longer pins this guard`);
+ console.log(`ok ${m.id} (code): ${code.test} fails with the guard removed from ${code.file}`);
+ } finally {
+ writeFileSync(file, original);
+ }
+}
+
+const selected = catalog.mutants.filter(m => !only || m.id === only);
+if (selected.length === 0) { console.error(`no mutant ${only} in ${specName}`); process.exit(2); }
+if (!flag('--code-only')) { const tla2tools = jar(); for (const m of selected) runSpec(m, tla2tools); }
+if (!flag('--spec-only')) for (const m of selected) if (m.code) runCode(m);
+if (failures.length) { console.error(`\n${failures.length} mutant check(s) failed; spec/tla/README.md says what each code means.`); process.exit(1); }
+console.log(`\nall ${selected.length} mutant(s) behave as catalogued`);
diff --git a/scripts/spec/tla-jar.sh b/scripts/spec/tla-jar.sh
new file mode 100755
index 0000000000..713d1ab0ff
--- /dev/null
+++ b/scripts/spec/tla-jar.sh
@@ -0,0 +1,38 @@
+#!/usr/bin/env bash
+# Prints the path of a verified tla2tools.jar, downloading it into a cache on first use.
+#
+# TLA2TOOLS=<path> use this jar (it is still checked against the pinned sha256)
+# TLA_CACHE=<dir> cache directory (default ${XDG_CACHE_HOME:-~/.cache}/gbrain/tla)
+#
+# Exit 2 with a code on stderr: TLA_JAR_DOWNLOAD_FAILED (network; rerun), TLA_JAR_SHA_MISMATCH (never rerun:
+# the bytes are not the reviewed release), TLA_JAVA_MISSING (install Java 11+).
+set -euo pipefail
+here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+# shellcheck source=tla-tools.env
+. "$here/tla-tools.env"
+command -v java >/dev/null || { echo "TLA_JAVA_MISSING: java not found; install a JDK 11 or later (CI uses temurin 21)" >&2; exit 2; }
+sha_of() { if command -v sha256sum >/dev/null; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi; }
+if [ -n "${TLA2TOOLS:-}" ]; then
+ jar="$TLA2TOOLS"
+ [ -f "$jar" ] || { echo "TLA_JAR_MISSING: TLA2TOOLS=$jar does not exist; unset it to download v$TLA_TOOLS_VERSION into the cache" >&2; exit 2; }
+else
+ cache="${TLA_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/gbrain/tla}"
+ mkdir -p "$cache"
+ jar="$cache/tla2tools-$TLA_TOOLS_VERSION.jar"
+ if [ ! -f "$jar" ]; then
+ tmp="$jar.part.$$"
+ if ! curl -sSfL --retry 3 --retry-delay 2 "$TLA_TOOLS_URL" -o "$tmp"; then
+ rm -f "$tmp"
+ echo "TLA_JAR_DOWNLOAD_FAILED: could not download $TLA_TOOLS_URL; rerun, or download it yourself and set TLA2TOOLS to its path" >&2
+ exit 2
+ fi
+ mv "$tmp" "$jar"
+ fi
+fi
+actual="$(sha_of "$jar")"
+if [ "$actual" != "$TLA_TOOLS_SHA256" ]; then
+ [ -z "${TLA2TOOLS:-}" ] && rm -f "$jar"
+ echo "TLA_JAR_SHA_MISMATCH: $jar has sha256 $actual, not the pinned $TLA_TOOLS_SHA256 (scripts/spec/tla-tools.env). Do not retry; a changed pin needs review." >&2
+ exit 2
+fi
+echo "$jar"
diff --git a/scripts/spec/tla-tools.env b/scripts/spec/tla-tools.env
new file mode 100644
index 0000000000..194cb52e41
--- /dev/null
+++ b/scripts/spec/tla-tools.env
@@ -0,0 +1,5 @@
+# The TLA+ tools every spec under spec/tla/ is checked with (scripts/spec/tla-jar.sh, .github/workflows/tla-spec.yml).
+# The sha256 is of the reviewed release jar: a retargeted tag fails the check instead of running.
+TLA_TOOLS_VERSION=1.7.4
+TLA_TOOLS_URL=https://github.com/tlaplus/tlaplus/releases/download/v1.7.4/tla2tools.jar
+TLA_TOOLS_SHA256=936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88
diff --git a/scripts/spec/tlc.sh b/scripts/spec/tlc.sh
new file mode 100755
index 0000000000..b36e3d105b
--- /dev/null
+++ b/scripts/spec/tlc.sh
@@ -0,0 +1,62 @@
+#!/usr/bin/env bash
+# Model-checks every spec under spec/tla/ with TLC (spec/tla/README.md).
+#
+# bash scripts/spec/tlc.sh every config of every spec
+# bash scripts/spec/tlc.sh drain-lease one spec
+# bash scripts/spec/tlc.sh drain-lease DrainLease.cfg
+#
+# Each spec directory holds one module <M>.tla and its configs <M>*.cfg. A config passes only when TLC prints
+# "Model checking completed. No error has been found."; anything else fails with a code:
+# TLC_VIOLATION a property is violated: read the trace in the log, then fix the code, or fix the spec when the
+# spec is wrong and say why in the PR
+# TLC_TIMEOUT TLC did not finish within TLC_TIMEOUT_S (default 600): the state space grew; shrink the config
+# TLC_ERROR TLC stopped (parse or semantic error, out of memory): the log names the line
+# Env: TLA2TOOLS (a jar to use; otherwise scripts/spec/tla-jar.sh downloads the pinned one), TLC_OUT (logs; default
+# .context/tlc), TLC_WORKERS (default: CPUs / configs run at once), TLC_TIMEOUT_S, TLC_JAVA_OPTS.
+set -euo pipefail
+root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+jar="$(bash "$root/scripts/spec/tla-jar.sh")"
+out="${TLC_OUT:-$root/.context/tlc}"
+limit="${TLC_TIMEOUT_S:-600}"
+timeout_bin="$(command -v timeout || command -v gtimeout || true)"
+[ -n "$timeout_bin" ] || { echo "TLC_ERROR: GNU timeout not found (on macOS: brew install coreutils)" >&2; exit 2; }
+mkdir -p "$out"
+
+specs=()
+if [ $# -ge 1 ]; then specs=("$root/spec/tla/$1"); else for d in "$root"/spec/tla/*/; do specs+=("${d%/}"); done; fi
+jobs=()
+for dir in "${specs[@]}"; do
+ [ -d "$dir" ] || { echo "TLC_ERROR: no spec directory $dir" >&2; exit 2; }
+ module="$(cd "$dir" && ls *.tla | head -1)"; module="${module%.tla}"
+ if [ $# -ge 2 ]; then cfgs=("$2"); else cfgs=(); for c in "$dir"/"$module"*.cfg; do cfgs+=("$(basename "$c")"); done; fi
+ for cfg in "${cfgs[@]}"; do [ -f "$dir/$cfg" ] || { echo "TLC_ERROR: no config $dir/$cfg" >&2; exit 2; }; jobs+=("$dir|$module|$cfg"); done
+done
+cpus="$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 2)"
+workers="${TLC_WORKERS:-$(( cpus / ${#jobs[@]} > 0 ? cpus / ${#jobs[@]} : 1 ))}"
+
+run() { # dir module cfg -> runs TLC on a private copy, so its states/ directory never lands in the tree
+ local dir="$1" module="$2" cfg="$3" work="$out/$(basename "$1")-${3%.cfg}" rc=0
+ rm -rf "$work"; mkdir -p "$work/tmp"; cp "$dir/$module.tla" "$dir/$cfg" "$work/"
+ (cd "$work" && "$timeout_bin" --kill-after=10 "$limit" java ${TLC_JAVA_OPTS:--XX:+UseParallelGC} -Djava.io.tmpdir="$work/tmp" \
+ -cp "$jar" tlc2.TLC -workers "$workers" -config "$cfg" -metadir "$work/states" "$module.tla") > "$work/tlc.log" 2>&1 || rc=$?
+ echo "$rc" > "$work/rc"
+}
+pids=()
+for job in "${jobs[@]}"; do IFS='|' read -r d m c <<< "$job"; run "$d" "$m" "$c" & pids+=($!); done
+wait "${pids[@]}"
+
+status=0
+for job in "${jobs[@]}"; do
+ IFS='|' read -r d m c <<< "$job"
+ work="$out/$(basename "$d")-${c%.cfg}"; log="$work/tlc.log"; rc="$(cat "$work/rc")"; name="$(basename "$d")/$c"
+ if grep -q "Model checking completed. No error has been found." "$log"; then
+ echo "ok $name: $(grep -oE '[0-9]+ distinct states found' "$log" | tail -1) ($(grep -oE 'Finished in [^ ]+' "$log" | head -1))"
+ elif [ "$rc" = 124 ] || [ "$rc" = 137 ]; then
+ echo "FAIL TLC_TIMEOUT $name: TLC did not finish within ${limit}s. Log: $log" >&2; status=1
+ elif v="$(grep -oE '(Invariant|Action property|Temporal properties|Property) [A-Za-z0-9_]* ?(is|were) violated' "$log" | head -1)" && [ -n "$v" ]; then
+ echo "FAIL TLC_VIOLATION $name: $v. The counterexample trace is in $log; spec/tla/README.md maps each action to its code." >&2; status=1
+ else
+ echo "FAIL TLC_ERROR $name: TLC exited $rc without a result. Log: $log" >&2; grep -m3 -iE 'error|exception' "$log" >&2 || tail -5 "$log" >&2; status=1
+ fi
+done
+exit "$status"
diff --git a/spec/tla/drain-lease/DrainLease.cfg b/spec/tla/drain-lease/DrainLease.cfg
new file mode 100644
index 0000000000..e4e682f7a6
--- /dev/null
+++ b/spec/tla/drain-lease/DrainLease.cfg
@@ -0,0 +1,26 @@
+\* Two drainers, one lane each, the code's timing at 10 s ticks.
+SPECIFICATION Spec
+CHECK_DEADLOCK TRUE
+CONSTANTS
+ Procs = {p1, p2}
+ Lanes = 1
+ TickMs = 10000
+ TtlMs = 120000
+ RefreshMs = 20000
+ RenewTimeoutMs = 30000
+ StealGraceMs = 60000
+ TakeoverGraceMs = 60000
+ MaxTxMs = 20000
+ RenewalWinsGap = TRUE
+ UnsafeSteals = FALSE
+ MaxTime = 18
+ MaxTokens = 3
+ MaxCursor = 2
+ MaxSleeps = 1
+ MaxCrashes = 1
+SYMMETRY Symm
+INVARIANT TypeOK
+INVARIANT FencedTxnsMatchRow
+INVARIANT OneDrainer
+INVARIANT NoSpuriousLapse
+PROPERTY CursorMonotone
diff --git a/spec/tla/drain-lease/DrainLease.tla b/spec/tla/drain-lease/DrainLease.tla
new file mode 100644
index 0000000000..fd13249c64
--- /dev/null
+++ b/spec/tla/drain-lease/DrainLease.tla
@@ -0,0 +1,300 @@
+---------------------------- MODULE DrainLease ----------------------------
+(***************************************************************************)
+(* The managed-sync drain lease: one drainer per source at a time. *)
+(* *)
+(* Code: src/core/persistence/sync-lease.ts (withDrainLease, *)
+(* assertDrainLease, inFencedSlices) over src/core/db-lock.ts *)
+(* (tryAcquireDbLock, withRefreshingLock). The lease is one row of *)
+(* gbrain_cycle_locks; its acquisition_token is the fencing token. *)
+(* Postgres only: PGLite is one connection and renews in-process. *)
+(* *)
+(* Time is a discrete clock of TickMs. Every duration is derived from the *)
+(* code's millisecond constants, which the .cfg files carry and *)
+(* test/spec-drain-lease-constants.test.ts checks against the code. *)
+(* *)
+(* An awake holder owes its timers: the clock does not pass a renewal that *)
+(* is due, a renewal that can land, a renewal timeout, its local lease *)
+(* deadline, or a fenced transaction at its bound (MaxTxMs). A holder that *)
+(* sleeps (machine asleep, event loop blocked) owes nothing. That makes *)
+(* "a live holder keeps its lease" an invariant (NoSpuriousLapse), the *)
+(* property #7415 broke, conditional on the stated timing assumptions. *)
+(***************************************************************************)
+EXTENDS Naturals, FiniteSets, TLC
+
+CONSTANTS
+ Procs, \* drainer processes, all on one host (the worst case for the pid probe)
+ Lanes, \* fenced transactions one holder may have open at once
+ TickMs, \* one clock tick
+ TtlMs, \* DRAIN_LEASE_TTL_MINUTES * 60000
+ RefreshMs, \* DRAIN_LEASE_REFRESH_MS
+ RenewTimeoutMs, \* withRefreshingLock: min(30000, ttl / 3)
+ StealGraceMs, \* resolveStealGraceSeconds(ttl) * 1000
+ TakeoverGraceMs, \* HOLDER_TAKEOVER_GRACE_MS
+ MaxTxMs, \* assumption: the longest a fenced transaction stays open (FENCED_SLICE_MS plus the item that crosses it)
+ RenewalWinsGap, \* assumption: a waiting renewal gets the row before the holder's next fenced transaction begins
+ UnsafeSteals, \* a pid probe that calls a live holder dead (pid namespaces sharing a hostname), or --force-break-lock
+ MaxTime, MaxTokens, MaxCursor, MaxSleeps, MaxCrashes
+
+CeilDiv(a, b) == (a + b - 1) \div b
+\* Rounded so the model is never kinder to the code than the code is.
+TTL == TtlMs \div TickMs
+Refresh == CeilDiv(RefreshMs, TickMs)
+RenewTO == CeilDiv(RenewTimeoutMs, TickMs)
+Grace == StealGraceMs \div TickMs
+PidGrace == TakeoverGraceMs \div TickMs
+MaxTx == CeilDiv(MaxTxMs, TickMs)
+LaneIds == 1..Lanes
+None == 0
+
+VARIABLES
+ now, \* database clock (ticks)
+ rowTok, rowExp, rowRef, rowAcq, \* the lock row: token (None = no row), ttl_expires_at, last_refreshed_at, acquired_at
+ cursor, \* the sync checkpoint each fenced commit advances
+ nextTok, \* next acquisition token
+ pc, \* "idle" | "holding" | "asleep"
+ tok, \* the token this process holds
+ aborted, \* its lease AbortSignal fired (LockStolenError)
+ deadline, \* local lease deadline: the confirmed renewal's request start + TTL
+ nextRenew, \* next refresh interval tick
+ renewAt, \* start of the in-flight renewal (None = none); its statement's now()
+ cancelling, \* the in-flight renewal timed out: cancelled, not yet settled
+ txAt, \* [p][lane] start tick + 1 of an open fenced transaction; None = closed
+ txRead, \* [p][lane] the cursor it read under the fence
+ disturbed, \* ghost: this process slept while holding its current lease
+ sleeps, crashes
+
+vars == <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, pc, tok, aborted, deadline, nextRenew,
+ renewAt, cancelling, txAt, txRead, disturbed, sleeps, crashes>>
+local == <<pc, tok, aborted, deadline, nextRenew, renewAt, cancelling, txAt, txRead, disturbed>>
+
+Closed == [l \in LaneIds |-> None]
+OpenTx(p) == {l \in LaneIds : txAt[p][l] # None}
+Renewing(p) == renewAt[p] # None
+\* Processes holding the lock row FOR SHARE.
+Sharers == {p \in Procs : OpenTx(p) # {}}
+
+TypeOK ==
+ /\ now \in 0..MaxTime /\ rowTok \in 0..MaxTokens /\ cursor \in 0..MaxCursor
+ /\ pc \in [Procs -> {"idle", "holding", "asleep"}] /\ tok \in [Procs -> 0..MaxTokens]
+ /\ aborted \in [Procs -> BOOLEAN] /\ disturbed \in [Procs -> BOOLEAN]
+
+Init ==
+ /\ now = 0 /\ rowTok = None /\ rowExp = 0 /\ rowRef = 0 /\ rowAcq = 0 /\ cursor = 0 /\ nextTok = 1
+ /\ pc = [p \in Procs |-> "idle"] /\ tok = [p \in Procs |-> None] /\ aborted = [p \in Procs |-> FALSE]
+ /\ deadline = [p \in Procs |-> 0] /\ nextRenew = [p \in Procs |-> 0] /\ renewAt = [p \in Procs |-> None]
+ /\ cancelling = [p \in Procs |-> FALSE]
+ /\ txAt = [p \in Procs |-> Closed] /\ txRead = [p \in Procs |-> Closed]
+ /\ disturbed = [p \in Procs |-> FALSE] /\ sleeps = 0 /\ crashes = 0
+
+(* A process's state once it no longer holds anything. *)
+Reset(p) ==
+ /\ pc' = [pc EXCEPT ![p] = "idle"] /\ tok' = [tok EXCEPT ![p] = None]
+ /\ aborted' = [aborted EXCEPT ![p] = FALSE] /\ disturbed' = [disturbed EXCEPT ![p] = FALSE]
+ /\ deadline' = [deadline EXCEPT ![p] = 0] /\ nextRenew' = [nextRenew EXCEPT ![p] = 0]
+ /\ renewAt' = [renewAt EXCEPT ![p] = None] /\ cancelling' = [cancelling EXCEPT ![p] = FALSE]
+ /\ txAt' = [txAt EXCEPT ![p] = Closed] /\ txRead' = [txRead EXCEPT ![p] = Closed]
+
+(***************************************************************************)
+(* tryAcquireDbLock. The upsert inserts, or takes over a row whose TTL *)
+(* expired and whose last refresh is older than the steal grace; the *)
+(* takeover UPDATEs the row, so it waits for every FOR SHARE. *)
+(***************************************************************************)
+Expired == rowExp < now
+TakeoverAllowed == Expired /\ rowRef + Grace < now
+
+Grant(p) ==
+ /\ rowTok' = nextTok /\ rowExp' = now + TTL /\ rowRef' = now /\ rowAcq' = now /\ nextTok' = nextTok + 1
+ /\ pc' = [pc EXCEPT ![p] = "holding"] /\ tok' = [tok EXCEPT ![p] = nextTok]
+ /\ deadline' = [deadline EXCEPT ![p] = now + TTL] /\ nextRenew' = [nextRenew EXCEPT ![p] = now + Refresh]
+ /\ UNCHANGED <<now, cursor, aborted, renewAt, cancelling, cancelling, txAt, txRead, disturbed, sleeps, crashes>>
+
+Acquire(p) ==
+ /\ pc[p] = "idle" /\ nextTok <= MaxTokens
+ /\ rowTok = None \/ (Sharers = {} /\ TakeoverAllowed)
+ /\ Grant(p)
+
+(***************************************************************************)
+(* tryAcquireDbLock's second path (#1780), and --break-lock's safe path: a *)
+(* row that has not expired, whose same-host pid the probe calls dead and *)
+(* that is older than the takeover grace, is DELETEd by pid and token *)
+(* (waiting for every FOR SHARE) and the upsert retried. An honest probe *)
+(* calls dead only a holder that is gone. *)
+(***************************************************************************)
+RowOwnerLive == \E q \in Procs : pc[q] # "idle" /\ tok[q] = rowTok
+
+DeadPidTakeover(p) ==
+ /\ pc[p] = "idle" /\ nextTok <= MaxTokens
+ /\ rowTok # None /\ ~Expired /\ Sharers = {} /\ now >= rowAcq + PidGrace
+ /\ UnsafeSteals \/ ~RowOwnerLive
+ /\ Grant(p)
+
+(***************************************************************************)
+(* withRefreshingLock's interval: one renewal in flight; a tick that finds *)
+(* one in flight skips it. Nothing is renewed after loss. *)
+(***************************************************************************)
+RenewDue(p) == pc[p] = "holding" /\ ~aborted[p] /\ now >= nextRenew[p]
+
+StartRenew(p) ==
+ /\ RenewDue(p)
+ /\ renewAt' = IF Renewing(p) THEN renewAt ELSE [renewAt EXCEPT ![p] = now]
+ /\ nextRenew' = [nextRenew EXCEPT ![p] = now + Refresh]
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, pc, tok, aborted, deadline,
+ cancelling, txAt, txRead, disturbed, sleeps, crashes>>
+
+(* UPDATE ... WHERE id AND holder_pid AND acquisition_token needs the row *)
+(* exclusively, so it waits while any transaction holds it FOR SHARE, the *)
+(* holder's own fenced transactions included (#7415). *)
+RenewCanLand(p) == pc[p] = "holding" /\ Renewing(p) /\ Sharers = {}
+RenewMatches(p) == rowTok = tok[p]
+
+(* The UPDATE lands once the row is free. Its now() is the statement's start, so the row's expiry and *)
+(* last refresh count from the request, not from the moment it got the row. A renewal that timed out *)
+(* and lands anyway extends the row but never the holder's local authority. *)
+RenewLand(p) ==
+ /\ RenewCanLand(p)
+ /\ renewAt' = [renewAt EXCEPT ![p] = None] /\ cancelling' = [cancelling EXCEPT ![p] = FALSE]
+ /\ IF RenewMatches(p)
+ THEN /\ rowExp' = renewAt[p] + TTL /\ rowRef' = renewAt[p]
+ /\ deadline' = [deadline EXCEPT ![p] = IF aborted[p] \/ cancelling[p] THEN @ ELSE renewAt[p] + TTL]
+ /\ UNCHANGED aborted
+ ELSE /\ aborted' = [aborted EXCEPT ![p] = IF cancelling[p] THEN @ ELSE TRUE]
+ /\ UNCHANGED <<rowExp, rowRef, deadline>>
+ /\ UNCHANGED <<now, rowTok, rowAcq, cursor, nextTok, pc, tok, nextRenew, txAt, txRead, disturbed, sleeps, crashes>>
+
+(* withRefreshingLock's timeout aborts a renewal still waiting on the row; the cancellation settles *)
+(* later (CancelSettle), and no new renewal starts until it has. *)
+RenewTimeoutDue(p) == pc[p] = "holding" /\ Renewing(p) /\ ~cancelling[p] /\ Sharers # {} /\ now >= renewAt[p] + RenewTO
+
+RenewTimeout(p) ==
+ /\ RenewTimeoutDue(p)
+ /\ cancelling' = [cancelling EXCEPT ![p] = TRUE]
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, pc, tok, aborted, deadline, nextRenew,
+ renewAt, txAt, txRead, disturbed, sleeps, crashes>>
+
+(* The cancelled statement ends having changed nothing (it never got the row). *)
+CancelSettle(p) ==
+ /\ pc[p] = "holding" /\ Renewing(p) /\ cancelling[p]
+ /\ renewAt' = [renewAt EXCEPT ![p] = None] /\ cancelling' = [cancelling EXCEPT ![p] = FALSE]
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, pc, tok, aborted, deadline, nextRenew,
+ txAt, txRead, disturbed, sleeps, crashes>>
+
+(* The expiry timer: the TTL passed with no confirmed renewal. *)
+DeadlineDue(p) == pc[p] = "holding" /\ ~aborted[p] /\ now >= deadline[p]
+
+LocalDeadline(p) ==
+ /\ DeadlineDue(p)
+ /\ aborted' = [aborted EXCEPT ![p] = TRUE]
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, pc, tok, deadline, nextRenew, renewAt, cancelling,
+ txAt, txRead, disturbed, sleeps, crashes>>
+
+(***************************************************************************)
+(* assertDrainLease, in each transaction that admits work or swaps the *)
+(* cursor: refuse when the signal aborted, else SELECT the row WHERE token *)
+(* matches AND ttl_expires_at > now() FOR SHARE. *)
+(***************************************************************************)
+FenceSignal(p) == ~aborted[p]
+FenceToken(p) == rowTok = tok[p]
+FenceExpiry == rowExp > now
+FencePasses(p) == FenceSignal(p) /\ FenceToken(p) /\ FenceExpiry
+\* A FOR SHARE that arrives while the holder's renewal waits queues behind it (RenewalWinsGap).
+FenceQueue(p) == RenewalWinsGap => ~Renewing(p)
+
+BeginFenced(p, l) ==
+ /\ pc[p] = "holding" /\ txAt[p][l] = None /\ cursor < MaxCursor
+ /\ FencePasses(p) /\ FenceQueue(p)
+ /\ txAt' = [txAt EXCEPT ![p][l] = now + 1]
+ /\ txRead' = [txRead EXCEPT ![p][l] = cursor]
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, pc, tok, aborted, deadline, nextRenew,
+ renewAt, cancelling, disturbed, sleeps, crashes>>
+
+TxDue(p) == pc[p] = "holding" /\ \E l \in OpenTx(p) : now + 1 >= txAt[p][l] + MaxTx
+
+(* The transaction commits. Lane 1 is the pass's cursor transaction: the cursor advances from the *)
+(* value it read under the fence. Other lanes admit work and leave the cursor to lane 1. *)
+Commit(p, l) ==
+ /\ pc[p] = "holding" /\ txAt[p][l] # None
+ /\ cursor' = IF l = 1 THEN txRead[p][l] + 1 ELSE cursor
+ /\ txAt' = [txAt EXCEPT ![p][l] = None] /\ txRead' = [txRead EXCEPT ![p][l] = None]
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, nextTok, pc, tok, aborted, deadline, nextRenew, renewAt, cancelling,
+ disturbed, sleeps, crashes>>
+
+Rollback(p, l) ==
+ /\ pc[p] = "holding" /\ txAt[p][l] # None
+ /\ txAt' = [txAt EXCEPT ![p][l] = None] /\ txRead' = [txRead EXCEPT ![p][l] = None]
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, pc, tok, aborted, deadline, nextRenew,
+ renewAt, cancelling, disturbed, sleeps, crashes>>
+
+(***************************************************************************)
+(* The pass ends, done or refused (a failed fence throws LockStolenError): *)
+(* withRefreshingLock's finally waits for the in-flight renewal, then *)
+(* DELETEs WHERE holder_pid AND token, which needs the row exclusively. *)
+(***************************************************************************)
+ReleaseMatches(p) == rowTok = tok[p]
+
+Release(p) ==
+ /\ pc[p] = "holding" /\ OpenTx(p) = {} /\ ~Renewing(p) /\ Sharers = {}
+ /\ rowTok' = IF ReleaseMatches(p) THEN None ELSE rowTok
+ /\ Reset(p)
+ /\ UNCHANGED <<now, rowExp, rowRef, rowAcq, cursor, nextTok, sleeps, crashes>>
+
+(***************************************************************************)
+(* Environment: a holder sleeps (machine asleep, event loop blocked), with *)
+(* or without a transaction open (the server keeps it open and its FOR *)
+(* SHARE held), and later wakes; a process crashes, rolling back its open *)
+(* transactions and leaving its row to expire. *)
+(***************************************************************************)
+Sleep(p) ==
+ /\ pc[p] = "holding" /\ sleeps < MaxSleeps
+ /\ pc' = [pc EXCEPT ![p] = "asleep"] /\ disturbed' = [disturbed EXCEPT ![p] = TRUE] /\ sleeps' = sleeps + 1
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, tok, aborted, deadline, nextRenew,
+ renewAt, cancelling, txAt, txRead, crashes>>
+
+Wake(p) ==
+ /\ pc[p] = "asleep"
+ /\ pc' = [pc EXCEPT ![p] = "holding"]
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, tok, aborted, deadline, nextRenew,
+ renewAt, cancelling, txAt, txRead, disturbed, sleeps, crashes>>
+
+Crash(p) ==
+ /\ pc[p] # "idle" /\ crashes < MaxCrashes
+ /\ Reset(p) /\ crashes' = crashes + 1
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, sleeps>>
+
+(* What an awake holder owes before the clock moves. *)
+Owes(p) == RenewDue(p) \/ RenewCanLand(p) \/ RenewTimeoutDue(p) \/ (pc[p] = "holding" /\ cancelling[p]) \/ DeadlineDue(p) \/ TxDue(p)
+
+Tick ==
+ /\ now < MaxTime /\ \A p \in Procs : ~Owes(p)
+ /\ now' = now + 1
+ /\ UNCHANGED <<rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, sleeps, crashes>> /\ UNCHANGED local
+
+(* The exploration bound: at MaxTime the behavior may stop. A state before it with no step is a deadlock. *)
+Done == now = MaxTime /\ UNCHANGED vars
+
+Next ==
+ \/ Tick
+ \/ Done
+ \/ \E p \in Procs :
+ \/ Acquire(p) \/ DeadPidTakeover(p) \/ StartRenew(p) \/ RenewLand(p) \/ RenewTimeout(p)
+ \/ CancelSettle(p) \/ LocalDeadline(p) \/ Release(p) \/ Sleep(p) \/ Wake(p) \/ Crash(p)
+ \/ \E l \in LaneIds : BeginFenced(p, l) \/ Commit(p, l) \/ Rollback(p, l)
+
+Spec == Init /\ [][Next]_vars
+
+Symm == Permutations(Procs)
+
+(***************************************************************************)
+(* Properties *)
+(***************************************************************************)
+\* Every open fenced transaction belongs to the row's current holder, so every commit is made under the live lease.
+FencedTxnsMatchRow == \A p \in Procs : OpenTx(p) # {} => rowTok = tok[p]
+
+\* At most one process has fenced work open.
+OneDrainer == Cardinality(Sharers) <= 1
+
+\* A live holder (one that has not slept while holding) never loses its lease.
+NoSpuriousLapse == \A p \in Procs : aborted[p] => disturbed[p]
+
+\* The sync cursor never moves backward.
+CursorMonotone == [][cursor' >= cursor]_vars
+=============================================================================
diff --git a/spec/tla/drain-lease/mutants.json b/spec/tla/drain-lease/mutants.json
new file mode 100644
index 0000000000..6aaa98ed0d
--- /dev/null
+++ b/spec/tla/drain-lease/mutants.json
@@ -0,0 +1,159 @@
+{
+ "$comment": "Each mutant removes one guard. `spec` edits the model and TLC must report `expect` (or nothing, for `survives`). `code` makes the same edit to the implementation and the named test must fail under it and pass without it. Run: bun scripts/spec/mutants.ts [--spec-only|--code-only] [--only <id>]. See spec/tla/README.md.",
+ "module": "DrainLease",
+ "config": "DrainLease.cfg",
+ "mutants": [
+ {
+ "id": "fence-ignores-token",
+ "title": "the fence admits a transaction whose token is not the row's",
+ "expect": "FencedTxnsMatchRow",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": "FenceToken(p) == rowTok = tok[p]",
+ "after": "FenceToken(p) == TRUE"
+ },
+ "code": {
+ "file": "src/core/persistence/sync-lease.ts",
+ "before": "WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE",
+ "after": "WHERE id=$1 AND $2::uuid IS NOT NULL AND ttl_expires_at > now() FOR SHARE",
+ "test": "test/persistence-sync-lease.test.ts",
+ "filter": "taken over after its TTL"
+ }
+ },
+ {
+ "id": "fence-without-share-lock",
+ "title": "the fence reads the row without FOR SHARE, so a takeover proceeds under an open transaction",
+ "expect": "FencedTxnsMatchRow",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": "Sharers == {p \\in Procs : OpenTx(p) # {}}",
+ "after": "Sharers == {}"
+ },
+ "code": {
+ "file": "src/core/persistence/sync-lease.ts",
+ "before": "AND ttl_expires_at > now() FOR SHARE'",
+ "after": "AND ttl_expires_at > now()'",
+ "test": "test/e2e/drain-lease-fence-postgres.test.ts",
+ "filter": "blocks a takeover",
+ "postgres": true
+ }
+ },
+ {
+ "id": "takeover-ignores-ttl",
+ "title": "the upsert takes over a row whose TTL has not expired",
+ "expect": "NoSpuriousLapse",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": "TakeoverAllowed == Expired /\\ rowRef + Grace < now",
+ "after": "TakeoverAllowed == TRUE"
+ },
+ "code": {
+ "file": "src/core/db-lock.ts",
+ "before": " WHERE gbrain_cycle_locks.ttl_expires_at < NOW()\n AND (gbrain_cycle_locks.last_refreshed_at IS NULL\n OR gbrain_cycle_locks.last_refreshed_at < NOW() - $5 * INTERVAL '1 second')",
+ "after": " WHERE $5::int IS NOT NULL",
+ "test": "test/db-lock-auto-takeover.test.ts",
+ "filter": "does NOT reclaim a live same-host holder"
+ }
+ },
+ {
+ "id": "release-ignores-token",
+ "title": "release deletes the row whatever its token, so a former holder frees its successor's lease",
+ "expect": "NoSpuriousLapse",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": "ReleaseMatches(p) == rowTok = tok[p]",
+ "after": "ReleaseMatches(p) == TRUE"
+ },
+ "code": {
+ "file": "src/core/db-lock.ts",
+ "before": " release: async () => {\n deregister();\n await db.query(\n `DELETE FROM gbrain_cycle_locks WHERE id = $1 AND holder_pid = $2 AND acquisition_token = $3::uuid`,",
+ "after": " release: async () => {\n deregister();\n await db.query(\n `DELETE FROM gbrain_cycle_locks WHERE id = $1 AND $2::int IS NOT NULL AND $3::uuid IS NOT NULL`,",
+ "test": "test/db-lock-fencing.test.ts",
+ "filter": "release\\(\\) after a steal is a fenced no-op"
+ }
+ },
+ {
+ "id": "pid-probe-calls-live-holder-dead",
+ "title": "the dead-pid takeover reclaims a live holder (EPERM read as dead, or --force-break-lock)",
+ "expect": "NoSpuriousLapse",
+ "spec": {
+ "file": "DrainLease.cfg",
+ "before": "UnsafeSteals = FALSE",
+ "after": "UnsafeSteals = TRUE"
+ },
+ "code": {
+ "file": "src/core/db-lock.ts",
+ "before": "if (probeResult === 'alive' || probeResult === 'eperm') return 'alive';",
+ "after": "if (probeResult === 'alive') return 'alive';",
+ "test": "test/db-lock-auto-takeover.test.ts",
+ "filter": "same-host \\+ EPERM"
+ }
+ },
+ {
+ "id": "fenced-transaction-outlives-renewal-timeout",
+ "title": "#7415: back-to-back fenced transactions that each outlive the renewal timeout starve the renewal until the lease lapses",
+ "expect": "NoSpuriousLapse",
+ "spec": {
+ "file": "DrainLease.cfg",
+ "before": "MaxTxMs = 20000",
+ "after": "MaxTxMs = 30000"
+ },
+ "code": {
+ "file": "src/core/persistence/sync-lease.ts",
+ "before": "export const FENCED_SLICE_MS = 5_000;",
+ "after": "export const FENCED_SLICE_MS = Number.POSITIVE_INFINITY;",
+ "test": "test/sync-fenced-slices-gbra133.test.ts",
+ "filter": "fenced slices"
+ }
+ },
+ {
+ "id": "fence-skips-queued-renewal",
+ "title": "a new fenced transaction overtakes a renewal waiting on the row (the RenewalWinsGap assumption fails)",
+ "expect": "NoSpuriousLapse",
+ "spec": {
+ "file": "DrainLease.cfg",
+ "before": "RenewalWinsGap = TRUE",
+ "after": "RenewalWinsGap = FALSE"
+ }
+ },
+ {
+ "id": "renewal-ignores-token",
+ "title": "the renewal extends whatever row exists, so a late renewal from a former holder rewinds its successor's expiry",
+ "expect": "NoSpuriousLapse",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": "RenewMatches(p) == rowTok = tok[p]",
+ "after": "RenewMatches(p) == rowTok # None"
+ },
+ "code": {
+ "file": "src/core/db-lock.ts",
+ "before": " WHERE id = $2 AND holder_pid = $3 AND acquisition_token = $4::uuid\n RETURNING id`,\n [ttl, lockId, pid, acquisitionToken],\n );\n return res.rows.length > 0;",
+ "after": " WHERE id = $2 AND holder_pid = $3 AND $4::uuid IS NOT NULL\n RETURNING id`,\n [ttl, lockId, pid, acquisitionToken],\n );\n return res.rows.length > 0;",
+ "test": "test/db-lock-fencing.test.ts",
+ "filter": "after a steal, the old handle refresh\\(\\) returns false"
+ }
+ },
+ {
+ "id": "fence-ignores-signal",
+ "title": "the fence ignores an aborted lease signal",
+ "expect": "survives",
+ "reason": "Defense in depth: every abort is also visible to the fence's token or expiry check (the local deadline never outlasts the row's expiry, and a refused renewal means the token moved).",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": "FenceSignal(p) == ~aborted[p]",
+ "after": "FenceSignal(p) == TRUE"
+ }
+ },
+ {
+ "id": "fence-ignores-expiry",
+ "title": "the fence admits under an expired row that nobody took over",
+ "expect": "survives",
+ "reason": "Defense in depth: FOR SHARE blocks a takeover while the transaction is open, and the token check refuses after one. test/persistence-sync-lease.test.ts still pins the refusal (\"expired untaken\").",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": "FenceExpiry == rowExp > now",
+ "after": "FenceExpiry == TRUE"
+ }
+ }
+ ]
+}