Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: code mutants in a scratch tree, both engines; guard tests; workflow; constants test

garrytandfcf05590508
diff --git a/.github/workflows/tla-spec.yml b/.github/workflows/tla-spec.yml
new file mode 100644
index 0000000000..5af17e3d17
--- /dev/null
+++ b/.github/workflows/tla-spec.yml
@@ -0,0 +1,88 @@
+name: TLA+ specs
+
+# Model-checks the TLA+ specs under spec/tla/ (spec/tla/README.md): TLC on every config, then every guard
+# mutant, in the model and in the code (scripts/spec/mutants.ts). Nightly, on dispatch, and on pull requests and
+# pushes that touch a spec, its runner, the code a spec models, or a test a mutant names.
+
+on:
+ pull_request:
+ branches: [master]
+ # Event parity (docs/ci-event-parity.md): path-gated named exception; covered by the nightly TLA+ specs schedule.
+ paths: &paths
+ - 'spec/tla/**'
+ - 'scripts/spec/**'
+ - '.github/workflows/tla-spec.yml'
+ - 'src/core/persistence/sync-lease.ts'
+ - 'src/core/db-lock.ts'
+ - 'test/spec-drain-lease-constants.test.ts'
+ - 'test/persistence-sync-lease.test.ts'
+ - 'test/db-lock-auto-takeover.test.ts'
+ - 'test/db-lock-fencing.test.ts'
+ - 'test/sync-fenced-slices-gbra133.test.ts'
+ - 'test/e2e/drain-lease-fence-postgres.test.ts'
+ push:
+ branches: [master]
+ paths: *paths
+ schedule:
+ - cron: '40 9 * * *' # nightly, 09:40 UTC
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ tla:
+ name: TLC and guard mutants
+ runs-on: ubicloud-standard-4-ubuntu-2404
+ timeout-minutes: 40
+ services:
+ postgres:
+ image: pgvector/pgvector:pg16
+ env:
+ POSTGRES_USER: gbrain_test
+ POSTGRES_PASSWORD: gbrain_test
+ POSTGRES_DB: gbrain_test
+ ports: ['5432:5432']
+ options: >-
+ --health-cmd "pg_isready -U gbrain_test -d gbrain_test"
+ --health-interval 5s --health-timeout 5s --health-retries 20
+ env:
+ TLC_OUT: ${{ runner.temp }}/tlc
+ TLA_CACHE: ${{ runner.temp }}/tla-cache
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ - uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
+ with:
+ distribution: temurin
+ java-version: '21'
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.4.4
+ - name: Install dependencies (bounded, retried once)
+ timeout-minutes: 8
+ run: bun scripts/ci-bun-install.ts --frozen-lockfile --ignore-scripts
+ # TLA_JAR_DOWNLOAD_FAILED is a network failure (rerun the job); TLA_JAR_SHA_MISMATCH is never rerun.
+ - name: Fetch TLC (pinned in scripts/spec/tla-tools.env, checked against its sha256)
+ run: echo "TLA2TOOLS=$(bash scripts/spec/tla-jar.sh)" >> "$GITHUB_ENV"
+ - name: The configs match the code
+ run: bun test test/spec-drain-lease-constants.test.ts
+ - name: Model-check every config
+ run: bash scripts/spec/tlc.sh
+ # Only after the model check passed: a mutant means something only against a spec whose properties hold.
+ - name: Every guard mutant is caught, in the model and in the code
+ env:
+ DATABASE_URL: postgres://gbrain_test:[email protected]:5432/gbrain_test
+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
+ run: bun scripts/spec/mutants.ts --require-postgres
+ - name: Keep the logs and counterexample traces
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: tla-spec-logs
+ path: ${{ runner.temp }}/tlc
+ if-no-files-found: ignore
+ retention-days: 14
diff --git a/scripts/spec/mutants.ts b/scripts/spec/mutants.ts
index 7b41e5b3f2..662cfb0b60 100644
--- a/scripts/spec/mutants.ts
+++ b/scripts/spec/mutants.ts
@@ -4,23 +4,25 @@
*
* - 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.
+ * - its `code` edits, when present, are applied to the implementation in a scratch copy of the working tree, and each
+ * named test must fail on its own assertions under them and pass without them. That ties each guard the model relies
+ * on to the lines that implement it (every engine branch) and the tests that pin 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).
+ * longer catches the guard), MUTANT_WRONG_PROPERTY, MUTANT_INCOMPLETE (TLC did not finish, or a test failed without
+ * the edit, matched no test, or did not load with it).
*/
import { spawnSync } from 'node:child_process';
-import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, 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 CodeTest { test: string; filter: string; postgres?: boolean }
+interface CodeEdit { edits: Edit[]; tests: CodeTest[] }
+interface Mutant { id: string; kind: 'guard' | 'assumption' | 'survivor'; title: string; expect: string; reason?: string; spec: Edit; code?: CodeEdit }
interface Catalog { module: string; config: string; mutants: Mutant[] }
const ROOT = resolve(import.meta.dir, '../..');
@@ -63,50 +65,73 @@ function runSpec(m: Mutant, tla2tools: string): void {
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 (clean) return void console.log(`ok ${m.id} (survivor): 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 === m.expect) return void console.log(`ok ${m.id} (${m.kind}): 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 });
+/** The code checks run in a scratch copy of the working tree, so an interrupted run never leaves the checkout edited. */
+function scratchCopy(): string {
+ const dir = join(out, `mutant-tree-${specName}`);
+ rmSync(dir, { recursive: true, force: true });
+ mkdirSync(dir, { recursive: true });
+ const files = spawnSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], { cwd: ROOT, encoding: 'utf8', maxBuffer: 1 << 28 }).stdout.split('\0').filter(Boolean);
+ for (const f of files) if (existsSync(join(ROOT, f))) cpSync(join(ROOT, f), join(dir, f), { recursive: true });
+ symlinkSync(join(ROOT, 'node_modules'), join(dir, 'node_modules'));
+ return dir;
+}
+
+interface TestRun { passed: number; failed: number; clean: boolean; tail: string }
+function bunTest(cwd: string, t: CodeTest): TestRun {
+ const r = spawnSync('bun', ['test', '--timeout=300000', t.test, '-t', t.filter], { cwd, 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') };
+ const count = (word: string) => Number(text.match(new RegExp(`^\\s*(\\d+) ${word}\\b`, 'm'))?.[1] ?? 0);
+ // A load or bootstrap failure is not a caught guard: the test must have run and failed on its own assertions.
+ const clean = !/Unhandled error between tests|SyntaxError|Cannot find module|error: Unexpected/.test(text);
+ return { passed: count('pass'), failed: count('fail'), clean, tail: text.split('\n').slice(-12).join('\n') };
}
-function runCode(m: Mutant): void {
+function runCode(m: Mutant, tree: string): 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 tests = code.tests.filter(t => {
+ if (!t.postgres || process.env.DATABASE_URL) return true;
+ if (flag('--require-postgres')) fail('MUTANT_INCOMPLETE', m.id, `${t.test} needs DATABASE_URL (a test Postgres)`);
+ else console.log(`skip ${m.id} (code): ${t.test} needs DATABASE_URL`);
+ return false;
+ });
+ if (tests.length === 0) return;
+ const originals = new Map<string, string>();
+ let mutated = new Map<string, string>();
+ for (const edit of code.edits) {
+ const text = mutated.get(edit.file) ?? readFileSync(join(tree, edit.file), 'utf8');
+ originals.set(edit.file, originals.get(edit.file) ?? text);
+ const next = applyOnce(text, edit);
+ if (next === null) return fail('MUTANT_STALE', m.id, `code text not found exactly once in ${edit.file}: ${JSON.stringify(edit.before)}`);
+ mutated.set(edit.file, next);
}
- 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);
+ for (const t of tests) {
+ const base = bunTest(tree, t);
+ if (!base.clean || base.failed > 0 || base.passed === 0) return fail('MUTANT_INCOMPLETE', m.id, `${t.test} -t "${t.filter}" does not pass (or matched no test) without the edit:\n${base.tail}`);
+ try {
+ for (const [file, text] of mutated) writeFileSync(join(tree, file), text);
+ const under = bunTest(tree, t);
+ if (!under.clean) return fail('MUTANT_INCOMPLETE', m.id, `${t.test} did not load or run with the edit, so it proves nothing:\n${under.tail}`);
+ if (under.failed === 0) return fail('MUTANT_SURVIVED', m.id, `${t.test} -t "${t.filter}" passes with the guard removed from ${[...mutated.keys()].join(', ')}; the test no longer pins it`);
+ console.log(`ok ${m.id} (code): ${t.test} fails with the guard removed from ${[...mutated.keys()].join(', ')}`);
+ } finally {
+ for (const [file, text] of originals) writeFileSync(join(tree, file), text);
+ }
}
}
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 (!flag('--spec-only') && selected.some(m => m.code)) { const tree = scratchCopy(); for (const m of selected) if (m.code) runCode(m, tree); }
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/spec/tla/drain-lease/DrainLease.tla b/spec/tla/drain-lease/DrainLease.tla
index fd13249c64..bc1d67aee0 100644
--- a/spec/tla/drain-lease/DrainLease.tla
+++ b/spec/tla/drain-lease/DrainLease.tla
@@ -196,8 +196,11 @@ 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)
+\* Postgres lets a new FOR SHARE in beside the share locks already held, even while an UPDATE waits on the row; once
+\* every share lock is gone the waiting UPDATE goes first (measured on Postgres 16). So a waiting renewal lands
+\* between serial fenced transactions but can starve under overlapping ones (Lanes > 1). RenewalWinsGap = FALSE drops
+\* even the serial guarantee.
+FenceQueue(p) == RenewalWinsGap => (~Renewing(p) \/ Sharers # {})
BeginFenced(p, l) ==
/\ pc[p] = "holding" /\ txAt[p][l] = None /\ cursor < MaxCursor
diff --git a/spec/tla/drain-lease/DrainLeaseSafety.cfg b/spec/tla/drain-lease/DrainLeaseSafety.cfg
new file mode 100644
index 0000000000..42b8cadd2d
--- /dev/null
+++ b/spec/tla/drain-lease/DrainLeaseSafety.cfg
@@ -0,0 +1,28 @@
+\* Coarser ticks (20 s) than DrainLease.cfg: safety does not depend on timing, and the state space stays small.
+\* Safety under every adverse assumption: fenced transactions longer than the renewal timeout,
+\* fenced transactions that overtake a waiting renewal, and pid probes (or --force-break-lock) that steal live leases.
+\* Leases may lapse here; two drainers may never both have fenced work open, and the cursor never moves backward.
+SPECIFICATION Spec
+CHECK_DEADLOCK TRUE
+CONSTANTS
+ Procs = {p1, p2}
+ Lanes = 1
+ TickMs = 20000
+ TtlMs = 120000
+ RefreshMs = 20000
+ RenewTimeoutMs = 30000
+ StealGraceMs = 60000
+ TakeoverGraceMs = 60000
+ MaxTxMs = 60000
+ RenewalWinsGap = FALSE
+ UnsafeSteals = TRUE
+ MaxTime = 10
+ MaxTokens = 3
+ MaxCursor = 2
+ MaxSleeps = 1
+ MaxCrashes = 1
+SYMMETRY Symm
+INVARIANT TypeOK
+INVARIANT FencedTxnsMatchRow
+INVARIANT OneDrainer
+PROPERTY CursorMonotone
diff --git a/spec/tla/drain-lease/mutants.json b/spec/tla/drain-lease/mutants.json
index 6aaa98ed0d..bbb7828db9 100644
--- a/spec/tla/drain-lease/mutants.json
+++ b/spec/tla/drain-lease/mutants.json
@@ -1,10 +1,11 @@
{
- "$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.",
+ "$comment": "Each mutant removes one guard (kind guard), breaks one timing or lock assumption (kind assumption), or removes a guard that is defense in depth at these bounds (kind survivor, expect survives). `spec` edits a copy of the model and TLC must report `expect`. `code` makes the same edit to the implementation; 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",
+ "kind": "guard",
"title": "the fence admits a transaction whose token is not the row's",
"expect": "FencedTxnsMatchRow",
"spec": {
@@ -13,15 +14,24 @@
"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"
+ "edits": [
+ {
+ "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"
+ }
+ ],
+ "tests": [
+ {
+ "test": "test/persistence-sync-lease.test.ts",
+ "filter": "taken over after its TTL"
+ }
+ ]
}
},
{
"id": "fence-without-share-lock",
+ "kind": "guard",
"title": "the fence reads the row without FOR SHARE, so a takeover proceeds under an open transaction",
"expect": "FencedTxnsMatchRow",
"spec": {
@@ -30,16 +40,25 @@
"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
+ "edits": [
+ {
+ "file": "src/core/persistence/sync-lease.ts",
+ "before": "AND ttl_expires_at > now() FOR SHARE'",
+ "after": "AND ttl_expires_at > now()'"
+ }
+ ],
+ "tests": [
+ {
+ "test": "test/e2e/drain-lease-fence-postgres.test.ts",
+ "filter": "blocks a takeover",
+ "postgres": true
+ }
+ ]
}
},
{
"id": "takeover-ignores-ttl",
+ "kind": "guard",
"title": "the upsert takes over a row whose TTL has not expired",
"expect": "NoSpuriousLapse",
"spec": {
@@ -48,15 +67,34 @@
"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"
+ "edits": [
+ {
+ "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() - ${stealGraceSeconds} * INTERVAL '1 second')",
+ "after": " WHERE ${stealGraceSeconds}::int IS NOT NULL"
+ },
+ {
+ "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"
+ }
+ ],
+ "tests": [
+ {
+ "test": "test/drain-lease-guards.test.ts",
+ "filter": "takeover-ignores-ttl"
+ },
+ {
+ "test": "test/e2e/drain-lease-guards-postgres.test.ts",
+ "filter": "takeover-ignores-ttl",
+ "postgres": true
+ }
+ ]
}
},
{
"id": "release-ignores-token",
+ "kind": "guard",
"title": "release deletes the row whatever its token, so a former holder frees its successor's lease",
"expect": "NoSpuriousLapse",
"spec": {
@@ -65,15 +103,34 @@
"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"
+ "edits": [
+ {
+ "file": "src/core/db-lock.ts",
+ "before": " release: async () => {\n deregister();\n await (maybePG.sql as any)`\n DELETE FROM gbrain_cycle_locks\n WHERE id = ${lockId} AND holder_pid = ${pid} AND acquisition_token = ${acquisitionToken}::uuid",
+ "after": " release: async () => {\n deregister();\n await (maybePG.sql as any)`\n DELETE FROM gbrain_cycle_locks\n WHERE id = ${lockId} AND holder_pid = ${pid} AND ${acquisitionToken}::uuid IS NOT NULL"
+ },
+ {
+ "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 holder_pid = $2 AND $3::uuid IS NOT NULL`,"
+ }
+ ],
+ "tests": [
+ {
+ "test": "test/drain-lease-guards.test.ts",
+ "filter": "release-ignores-token"
+ },
+ {
+ "test": "test/e2e/drain-lease-guards-postgres.test.ts",
+ "filter": "release-ignores-token",
+ "postgres": true
+ }
+ ]
}
},
{
"id": "pid-probe-calls-live-holder-dead",
+ "kind": "guard",
"title": "the dead-pid takeover reclaims a live holder (EPERM read as dead, or --force-break-lock)",
"expect": "NoSpuriousLapse",
"spec": {
@@ -82,15 +139,24 @@
"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"
+ "edits": [
+ {
+ "file": "src/core/db-lock.ts",
+ "before": "if (probeResult === 'alive' || probeResult === 'eperm') return 'alive';",
+ "after": "if (probeResult === 'alive') return 'alive';"
+ }
+ ],
+ "tests": [
+ {
+ "test": "test/db-lock-auto-takeover.test.ts",
+ "filter": "same-host \\+ EPERM"
+ }
+ ]
}
},
{
"id": "fenced-transaction-outlives-renewal-timeout",
+ "kind": "guard",
"title": "#7415: back-to-back fenced transactions that each outlive the renewal timeout starve the renewal until the lease lapses",
"expect": "NoSpuriousLapse",
"spec": {
@@ -99,16 +165,25 @@
"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"
+ "edits": [
+ {
+ "file": "src/core/persistence/sync-lease.ts",
+ "before": "export const FENCED_SLICE_MS = 5_000;",
+ "after": "export const FENCED_SLICE_MS = Number.POSITIVE_INFINITY;"
+ }
+ ],
+ "tests": [
+ {
+ "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)",
+ "kind": "assumption",
+ "title": "a new fenced transaction overtakes a renewal waiting on the row even between serial transactions (RenewalWinsGap fails)",
"expect": "NoSpuriousLapse",
"spec": {
"file": "DrainLease.cfg",
@@ -118,6 +193,7 @@
},
{
"id": "renewal-ignores-token",
+ "kind": "guard",
"title": "the renewal extends whatever row exists, so a late renewal from a former holder rewinds its successor's expiry",
"expect": "NoSpuriousLapse",
"spec": {
@@ -126,15 +202,45 @@
"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"
+ "edits": [
+ {
+ "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 refreshOpts,",
+ "after": " WHERE id = $2 AND holder_pid = $3 AND $4::uuid IS NOT NULL\n RETURNING id`,\n [ttl, lockId, pid, acquisitionToken],\n refreshOpts,"
+ },
+ {
+ "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;"
+ }
+ ],
+ "tests": [
+ {
+ "test": "test/drain-lease-guards.test.ts",
+ "filter": "renewal-ignores-token"
+ },
+ {
+ "test": "test/e2e/drain-lease-guards-postgres.test.ts",
+ "filter": "renewal-ignores-token",
+ "postgres": true
+ }
+ ]
+ }
+ },
+ {
+ "id": "overlapping-fenced-transactions",
+ "kind": "assumption",
+ "title": "a holder keeps the row FOR SHARE from overlapping transactions (sync lanes), so new share locks keep overtaking the waiting renewal until the lease lapses",
+ "expect": "NoSpuriousLapse",
+ "spec": {
+ "file": "DrainLease.cfg",
+ "before": "Lanes = 1",
+ "after": "Lanes = 2"
}
},
{
"id": "fence-ignores-signal",
+ "kind": "survivor",
"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).",
@@ -146,6 +252,7 @@
},
{
"id": "fence-ignores-expiry",
+ "kind": "survivor",
"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\").",
diff --git a/test/drain-lease-guards.test.ts b/test/drain-lease-guards.test.ts
new file mode 100644
index 0000000000..b3d506b1c8
--- /dev/null
+++ b/test/drain-lease-guards.test.ts
@@ -0,0 +1,83 @@
+/**
+ * The lock-row guards the drain lease's model (spec/tla/drain-lease) depends on, on both engines: a live holder's
+ * unexpired row is never taken over, and a former holder's refresh and release never touch its successor's row. Each is
+ * a guard mutant in spec/tla/drain-lease/mutants.json: removing it from src/core/db-lock.ts must fail its test here.
+ *
+ * Runs on PGLite here and on Postgres through test/e2e/drain-lease-guards-postgres.test.ts.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { tryAcquireDbLock } from '../src/core/db-lock.ts';
+import { DRAIN_LEASE_TTL_MINUTES } from '../src/core/persistence/sync-lease.ts';
+import { testBackends, type TestBackend } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const engines: Array<{ backend: TestBackend; engine: BrainEngine; close: () => Promise<void> }> = [];
+
+beforeAll(async () => {
+ for (const backend of testBackends()) {
+ if (backend === 'pglite') {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ engines.push({ backend, engine, close: () => engine.disconnect() });
+ } else {
+ engines.push({ backend, ...await isolatedPersistencePostgres(process.env.DATABASE_URL!) });
+ }
+ }
+}, 120_000);
+
+afterAll(async () => {
+ for (const e of engines) await e.close();
+});
+
+beforeEach(async () => {
+ for (const { engine } of engines) await engine.executeRaw(`DELETE FROM gbrain_cycle_locks WHERE id LIKE 'test-guard-%'`);
+});
+
+async function row(engine: BrainEngine, id: string) {
+ const rows = await engine.executeRaw<{ token: string; expires: string }>(
+ `SELECT acquisition_token::text AS token, ttl_expires_at::text AS expires FROM gbrain_cycle_locks WHERE id = $1`, [id]);
+ return rows[0] ?? null;
+}
+
+/** A successor took the row over: same pid (this process), a new token, as tryAcquireDbLock's takeover writes it. */
+async function succeed(engine: BrainEngine, id: string) {
+ await engine.executeRaw(`UPDATE gbrain_cycle_locks SET acquisition_token = gen_random_uuid(), acquired_at = now(),
+ ttl_expires_at = now() + interval '2 minutes', last_refreshed_at = now() WHERE id = $1`, [id]);
+ return row(engine, id);
+}
+
+describe('drain lease lock-row guards', () => {
+ test('a live holder whose row has not expired is never taken over (takeover-ignores-ttl)', async () => {
+ for (const { backend, engine } of engines) {
+ const holder = await tryAcquireDbLock(engine, 'test-guard-live', DRAIN_LEASE_TTL_MINUTES);
+ expect(holder, backend).not.toBeNull();
+ const before = await row(engine, 'test-guard-live');
+ expect(await tryAcquireDbLock(engine, 'test-guard-live', DRAIN_LEASE_TTL_MINUTES), backend).toBeNull();
+ expect(await row(engine, 'test-guard-live'), backend).toEqual(before);
+ await holder!.release();
+ }
+ });
+
+ test("a former holder's refresh leaves its successor's row as it was (renewal-ignores-token)", async () => {
+ for (const { backend, engine } of engines) {
+ const former = await tryAcquireDbLock(engine, 'test-guard-refresh', DRAIN_LEASE_TTL_MINUTES);
+ expect(former, backend).not.toBeNull();
+ const successor = await succeed(engine, 'test-guard-refresh');
+ expect(await former!.refresh(), backend).toBe(false);
+ expect(await row(engine, 'test-guard-refresh'), backend).toEqual(successor);
+ }
+ });
+
+ test("a former holder's release leaves its successor's row in place (release-ignores-token)", async () => {
+ for (const { backend, engine } of engines) {
+ const former = await tryAcquireDbLock(engine, 'test-guard-release', DRAIN_LEASE_TTL_MINUTES);
+ expect(former, backend).not.toBeNull();
+ const successor = await succeed(engine, 'test-guard-release');
+ await former!.release();
+ expect(await row(engine, 'test-guard-release'), backend).toEqual(successor);
+ }
+ });
+});
diff --git a/test/e2e/drain-lease-guards-postgres.test.ts b/test/e2e/drain-lease-guards-postgres.test.ts
new file mode 100644
index 0000000000..a945c2ac17
--- /dev/null
+++ b/test/e2e/drain-lease-guards-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../drain-lease-guards.test.ts'));
diff --git a/test/spec-drain-lease-constants.test.ts b/test/spec-drain-lease-constants.test.ts
new file mode 100644
index 0000000000..abcf71654c
--- /dev/null
+++ b/test/spec-drain-lease-constants.test.ts
@@ -0,0 +1,74 @@
+/**
+ * spec/tla/drain-lease models the drain lease with the code's timing. This test keeps the model's configs and the code in
+ * step: a changed lease constant fails here, naming the constant and the config to revisit, before the model silently
+ * checks a protocol the code no longer runs. Read spec/tla/README.md ("Timing") before changing either side.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { DRAIN_LEASE_REFRESH_MS, DRAIN_LEASE_TTL_MINUTES, FENCED_SLICE_MS } from '../src/core/persistence/sync-lease.ts';
+import { HOLDER_TAKEOVER_GRACE_MS, resolveStealGraceSeconds } from '../src/core/db-lock.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const ROOT = join(import.meta.dir, '..');
+const SPEC = join(ROOT, 'spec/tla/drain-lease');
+const CONFIGS = ['DrainLease.cfg', 'DrainLeaseSafety.cfg'];
+
+function constants(cfg: string): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const line of readFileSync(join(SPEC, cfg), 'utf8').split('\n')) {
+ const m = line.match(/^\s+(\w+)\s*=\s*(\S+)\s*$/);
+ if (m) out[m[1]!] = m[2]!;
+ }
+ return out;
+}
+
+/** withRefreshingLock's renewal deadline: min(heartbeatTimeoutMs ?? default, ttl / 3). The default is read from the source. */
+function renewalTimeoutMs(ttlMs: number): number {
+ const source = readFileSync(join(ROOT, 'src/core/db-lock.ts'), 'utf8');
+ const m = source.match(/const heartbeatTimeoutMs = Math\.min\(opts\.heartbeatTimeoutMs \?\? ([\d_]+), ttlMs \/ 3\);/);
+ expect(m, 'withRefreshingLock no longer computes its renewal timeout as min(opts.heartbeatTimeoutMs ?? <default>, ttlMs / 3); update this test and RenewTimeoutMs in spec/tla/drain-lease/*.cfg to the new rule').not.toBeNull();
+ return Math.min(Number(m![1]!.replace(/_/g, '')), ttlMs / 3);
+}
+
+const TTL_MS = DRAIN_LEASE_TTL_MINUTES * 60_000;
+const code = () => withEnv({ GBRAIN_LOCK_STEAL_GRACE_SECONDS: undefined }, () => ({
+ TtlMs: TTL_MS,
+ RefreshMs: DRAIN_LEASE_REFRESH_MS,
+ RenewTimeoutMs: renewalTimeoutMs(TTL_MS),
+ StealGraceMs: resolveStealGraceSeconds(DRAIN_LEASE_TTL_MINUTES) * 1000,
+ TakeoverGraceMs: HOLDER_TAKEOVER_GRACE_MS,
+}));
+const SOURCES: Record<string, string> = {
+ TtlMs: 'DRAIN_LEASE_TTL_MINUTES (src/core/persistence/sync-lease.ts)',
+ RefreshMs: 'DRAIN_LEASE_REFRESH_MS (src/core/persistence/sync-lease.ts)',
+ RenewTimeoutMs: 'withRefreshingLock heartbeatTimeoutMs (src/core/db-lock.ts)',
+ StealGraceMs: 'resolveStealGraceSeconds(DRAIN_LEASE_TTL_MINUTES) (src/core/db-lock.ts)',
+ TakeoverGraceMs: 'HOLDER_TAKEOVER_GRACE_MS (src/core/db-lock.ts)',
+};
+
+describe('spec/tla/drain-lease configs match the code', () => {
+ for (const cfg of CONFIGS) {
+ test(`${cfg}: the lease timing is the code's`, async () => {
+ const want = await code();
+ const have = constants(cfg);
+ for (const [name, value] of Object.entries(want)) {
+ expect(Number(have[name]), `${name} in spec/tla/drain-lease/${cfg} is ${have[name]}, but ${SOURCES[name]} gives ${value} ms. Set it to ${value}, run bun run test:tla, and read any new counterexample before accepting it.`).toBe(value);
+ }
+ });
+ }
+
+ test('DrainLease.cfg assumes a fenced-transaction bound the code keeps under the renewal timeout', async () => {
+ const { RenewTimeoutMs, RefreshMs, TtlMs } = await code();
+ const maxTx = Number(constants('DrainLease.cfg').MaxTxMs);
+ expect(FENCED_SLICE_MS, `FENCED_SLICE_MS (${FENCED_SLICE_MS}) must stay below MaxTxMs (${maxTx}) in DrainLease.cfg: a slice plus the item that crosses it is what the model assumes`).toBeLessThan(maxTx);
+ expect(maxTx, `MaxTxMs (${maxTx}) must stay below the renewal timeout (${RenewTimeoutMs}): TLC finds a live holder losing its lease once fenced transactions outlive it (mutant fenced-transaction-outlives-renewal-timeout)`).toBeLessThan(RenewTimeoutMs);
+ expect(RefreshMs + RenewTimeoutMs, 'a renewal and its timeout must fit inside the TTL').toBeLessThan(TtlMs);
+ });
+
+ test('DrainLeaseSafety.cfg keeps every adverse assumption on', () => {
+ const c = constants('DrainLeaseSafety.cfg');
+ expect({ UnsafeSteals: c.UnsafeSteals, RenewalWinsGap: c.RenewalWinsGap }).toEqual({ UnsafeSteals: 'TRUE', RenewalWinsGap: 'FALSE' });
+ expect(Number(c.MaxTxMs)).toBeGreaterThanOrEqual(Number(c.RenewTimeoutMs));
+ });
+});