Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: stamp fence in the model, stamp share-lock tests, CancelMs, nightly lanes config, JUnit outcome classification, per-run dirs

garrytanbc1a520f3414
diff --git a/.github/workflows/tla-spec.yml b/.github/workflows/tla-spec.yml
index 80969c7f9a..c0d83f554a 100644
--- a/.github/workflows/tla-spec.yml
+++ b/.github/workflows/tla-spec.yml
@@ -26,6 +26,9 @@ on:
- 'test/e2e/drain-lease-guards-postgres.test.ts'
- 'test/drain-lease-stamp-fence.test.ts'
- 'test/e2e/drain-lease-stamp-fence-postgres.test.ts'
+ - 'test/helpers/managed-brain.ts'
+ - 'test/helpers/test-backends.ts'
+ - 'test/helpers/persistence-postgres.ts'
push:
branches: [master]
paths: *paths
@@ -78,7 +81,10 @@ jobs:
printf 'TLA2TOOLS=%s\n' "$jar" >> "$GITHUB_ENV"
- name: The configs match the code
run: bun test test/spec-drain-lease-constants.test.ts
- - name: Model-check every config
+ - name: Model-check every config (the *Nightly.cfg ones on the schedule and on dispatch)
+ env:
+ TLC_NIGHTLY: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && '1' || '0' }}
+ TLC_TIMEOUT_S: '900'
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
diff --git a/scripts/spec/mutants.ts b/scripts/spec/mutants.ts
index 2644541f8e..5040ac3b14 100644
--- a/scripts/spec/mutants.ts
+++ b/scripts/spec/mutants.ts
@@ -14,8 +14,8 @@
* 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 a test failed without the edit, matched no test, or did not run to a clean assertion failure with it: a
- * signal, timeout, load error or non-assertion failure proves nothing). Every child's full output is kept under TLC_OUT
- * (default .context/tlc).
+ * signal, timeout, load error or non-assertion failure proves nothing). Each invocation writes to its own directory under TLC_OUT
+ * (default .context/tlc), printed first: the scratch tree, every child's full output and each test's JUnit report.
*/
import { spawnSync } from 'node:child_process';
import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
@@ -24,7 +24,7 @@ import { join, resolve } from 'node:path';
interface Edit { file: string; before: string; after: string }
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 Mutant { id: string; kind: 'guard' | 'assumption' | 'survivor'; title: string; expect: string; reason?: string; config?: string; spec: Edit; code?: CodeEdit }
interface Catalog { module: string; config: string; mutants: Mutant[] }
const ROOT = resolve(import.meta.dir, '../..');
@@ -38,7 +38,7 @@ const only = args.includes('--only') ? args[args.indexOf('--only') + 1] : undefi
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 out = join(process.env.TLC_OUT ?? join(ROOT, '.context/tlc'), `mutants-${specName}-${new Date().toISOString().replace(/[:.]/g, '-')}-${process.pid}`);
const timeoutS = Number(process.env.TLC_TIMEOUT_S ?? 300);
const failures: string[] = [];
let skipped = 0, checked = 0;
@@ -57,19 +57,22 @@ function jar(): string {
}
function runSpec(m: Mutant, tla2tools: string): void {
- const work = join(out, `mutant-${specName}-${m.id}`);
+ const work = join(out, 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 config = m.config ?? catalog.config;
+ for (const f of [`${catalog.module}.tla`, 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 });
+ '-config', 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);
- if (r.error) return fail('MUTANT_INCOMPLETE', m.id, `cannot run java (${(r.error as NodeJS.ErrnoException).code ?? r.error.message}); TLC did not start. Install Java 11 or later on PATH and rerun: bun scripts/spec/mutants.ts --only ${m.id} --spec-only`);
+ const spawnCode = (r.error as NodeJS.ErrnoException | undefined)?.code;
+ if (spawnCode === 'ENOENT') return fail('MUTANT_INCOMPLETE', m.id, `cannot run java (ENOENT); TLC did not start. Install Java 11 or later on PATH and rerun: bun scripts/spec/mutants.ts --only ${m.id} --spec-only`);
+ if (r.error || r.signal) return fail('MUTANT_INCOMPLETE', m.id, `TLC did not finish within TLC_TIMEOUT_S (${timeoutS} s) or was killed (${spawnCode ?? r.signal}). If the spec or config changed, find the action that multiplies states; otherwise rerun once. Log: ${work}/tlc.log`);
checked++;
const violated = log.match(/(?:Invariant|Action property|Property) (\w+) is violated/)?.[1];
const clean = log.includes('Model checking completed. No error has been found.');
@@ -86,8 +89,7 @@ function runSpec(m: Mutant, tla2tools: string): void {
/** 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 });
+ const dir = join(out, 'tree');
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 });
@@ -96,32 +98,32 @@ function scratchCopy(): string {
}
/**
- * One run of one test file, its full output kept in `log`. `outcome` is `passed` (exit 0, every selected test passed),
- * `assertion` (exit 1, a selected test failed on an expect() and nothing else went wrong) or `broken`: a signal, a
- * timeout, a spawn error, a load or bootstrap error, no test selected, or a failure that is not an assertion. Only
- * `assertion` counts as a caught guard; `broken` proves nothing either way.
+ * One run of one test file, its full output kept in `log` and its JUnit report beside it. `outcome` is `passed` (exit 0,
+ * every selected test passed), `assertion` (exit 1, and every failed test failed on an expect(): an AssertionError in the
+ * JUnit report) or `broken`: a signal, a timeout, a spawn error, a load or bootstrap error, no test selected, or a
+ * failure of any other type, such as an Error thrown after a passing expect(). Only `assertion` counts as a caught
+ * guard; `broken` proves nothing either way.
*/
interface TestRun { outcome: 'passed' | 'assertion' | 'broken'; why: string; log: string }
function bunTest(cwd: string, t: CodeTest, log: string): TestRun {
- const r = spawnSync('bun', ['test', '--timeout=300000', t.test, '-t', t.filter], { cwd, encoding: 'utf8', env: process.env, timeout: 600_000 });
+ const junit = log.replace(/[.]log$/, '.xml');
+ rmSync(junit, { force: true });
+ const r = spawnSync('bun', ['test', '--timeout=300000', '--reporter=junit', `--reporter-outfile=${junit}`, t.test, '-t', t.filter],
+ { cwd, encoding: 'utf8', env: process.env, timeout: 600_000 });
const text = `${r.stdout ?? ''}${r.stderr ?? ''}`;
writeFileSync(log, `$ bun test ${t.test} -t ${JSON.stringify(t.filter)}\nexit ${r.status} signal ${r.signal} error ${r.error?.message ?? 'none'}\n\n${text}`);
- const lines = text.split('\n').map(line => line.trim());
- const count = (...words: string[]) => {
- const line = lines.find(l => words.includes(l.split(' ')[1] ?? '') && l.split(' ').length === 2 && Number.isInteger(Number(l.split(' ')[0])));
- return line ? Number(line.split(' ')[0]) : 0;
- };
- const passed = count('pass'), failed = count('fail'), errors = count('error', 'errors');
const broken = (why: string): TestRun => ({ outcome: 'broken', why, log });
if (r.error) return broken(`bun did not run (${(r.error as NodeJS.ErrnoException).code ?? r.error.message})`);
if (r.signal) return broken(`bun was terminated by ${r.signal}`);
- if (text.includes('timed out after')) return broken('a test timed out');
- if (!lines.some(l => l.startsWith('Ran ') && l.includes(' across '))) return broken('bun printed no test summary');
- if (errors > 0 || ['Unhandled error between tests', 'SyntaxError', 'Cannot find module'].some(s => text.includes(s))) return broken('the file did not load, or an error escaped between tests');
- if (passed + failed === 0) return broken(`-t "${t.filter}" matched no test`);
- if (r.status === 0 && failed === 0) return { outcome: 'passed', why: `${passed} passed`, log };
- if (r.status === 1 && failed > 0 && text.includes('expect(')) return { outcome: 'assertion', why: `${failed} failed on an assertion`, log };
- return broken(`exit ${r.status} with ${failed} failed, and no failed expect() in the output`);
+ if (['Unhandled error between tests', 'SyntaxError', 'Cannot find module'].some(s => text.includes(s))) return broken('the file did not load, or an error escaped between tests');
+ if (!existsSync(junit)) return broken('bun wrote no JUnit report');
+ const cases = readFileSync(junit, 'utf8').split('<testcase ').slice(1).map(c => c.split('</testcase>')[0]!).filter(c => !c.includes('<skipped'));
+ const failures = cases.map(c => c.includes('<failure') ? (c.split('<failure type="')[1]?.split('"')[0] ?? 'unknown') : null).filter((f): f is string => f !== null);
+ if (cases.length === 0) return broken(`-t "${t.filter}" matched no test`);
+ if (r.status === 0 && failures.length === 0) return { outcome: 'passed', why: `${cases.length} passed`, log };
+ const other = failures.filter(type => type !== 'AssertionError');
+ if (r.status === 1 && failures.length > 0 && other.length === 0) return { outcome: 'assertion', why: `${failures.length} failed on an assertion`, log };
+ return broken(`exit ${r.status}, ${failures.length} failed${other.length ? ` (${other.join(', ')}, not an assertion)` : ''}`);
}
function runCode(m: Mutant, tree: string): void {
@@ -142,7 +144,7 @@ function runCode(m: Mutant, tree: string): void {
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 logs = join(out, `mutant-${specName}-${m.id}`);
+ const logs = join(out, m.id);
mkdirSync(logs, { recursive: true });
for (const [i, t] of tests.entries()) {
checked++;
@@ -162,8 +164,13 @@ function runCode(m: Mutant, tree: string): void {
const selected = catalog.mutants.filter(m => !only || m.id === only);
if (selected.length === 0) { console.error(`no mutant ${only} in ${specName}`); process.exit(2); }
+console.log(`logs: ${out}`);
if (!flag('--code-only')) { const tla2tools = jar(); for (const m of selected) runSpec(m, tla2tools); }
-if (!flag('--spec-only') && selected.some(m => m.code)) { const tree = scratchCopy(); for (const m of selected) if (m.code) runCode(m, tree); }
+if (!flag('--spec-only') && selected.some(m => m.code)) {
+ const tree = scratchCopy();
+ for (const m of selected) if (m.code) runCode(m, tree);
+ rmSync(tree, { recursive: true, force: true });
+}
if (failures.length === 0 && checked === 0) { console.error(`MUTANT_NOTHING_CHECKED: every check the selection asked for was skipped (${skipped} Postgres code check(s) without DATABASE_URL); nothing was verified.`); process.exit(1); }
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${skipped ? `; partial: ${skipped} Postgres code check(s) skipped (set DATABASE_URL to a test database, or pass --require-postgres to fail instead)` : ''}`);
diff --git a/scripts/spec/tlc.sh b/scripts/spec/tlc.sh
index b36e3d105b..570e013eef 100755
--- a/scripts/spec/tlc.sh
+++ b/scripts/spec/tlc.sh
@@ -12,7 +12,8 @@
# 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.
+# .context/tlc), TLC_WORKERS (default: CPUs / configs run at once), TLC_TIMEOUT_S, TLC_JAVA_OPTS, TLC_NIGHTLY (1 also runs
+# the *Nightly.cfg configs, which take too long for every pull request).
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
jar="$(bash "$root/scripts/spec/tla-jar.sh")"
@@ -28,7 +29,12 @@ 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
+ if [ $# -ge 2 ]; then cfgs=("$2"); else
+ cfgs=(); for c in "$dir"/"$module"*.cfg; do
+ case "$c" in *Nightly.cfg) [ "${TLC_NIGHTLY:-0}" = 1 ] || { echo "skip $(basename "$dir")/$(basename "$c") (nightly only; TLC_NIGHTLY=1 runs it)"; continue; } ;; esac
+ 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)"
diff --git a/spec/tla/README.md b/spec/tla/README.md
index 961ab5a833..208eb4a75c 100644
--- a/spec/tla/README.md
+++ b/spec/tla/README.md
@@ -57,9 +57,11 @@ lock with the token stamped on its request: a folded stamp's proof (`provenStamp
| Config | What it checks |
| --- | --- |
| `DrainLease.cfg` | Two drainers, one fenced transaction at a time, the code's timing at 10 s ticks: every property. |
-| `DrainLeaseSafety.cfg` | Every adverse assumption on (live holders stolen by a lying pid probe or `--force-break-lock`, fenced transactions longer than the renewal timeout, no renewal priority), 20 s ticks: the safety properties, which must hold anyway. |
+| `DrainLeaseSafety.cfg` | Every adverse assumption on (live holders stolen by a lying pid probe or `--force-break-lock`, fenced transactions longer than the renewal timeout, no renewal priority, a cancelled renewal settling late), 20 s ticks: the safety properties, which must hold anyway. |
+| `DrainLeaseStamp.cfg` | The same, plus the pass stamp's fence: a coordinator transaction that holds the row `FOR SHARE` by any issued token, overlaps the holder's and survives its crash. |
+| `DrainLeaseLanesNightly.cfg` | The safety config with two overlapping fenced transactions per holder, at a shorter clock bound. About 5 minutes, so `tlc.sh` runs it only with `TLC_NIGHTLY=1` (the schedule and dispatch). |
-`test/spec-drain-lease-constants.test.ts` keeps both configs' timing equal to the code's constants and checks the
+`test/spec-drain-lease-constants.test.ts` keeps every config's timing equal to the code's constants and checks the
ordering the liveness property needs.
### Properties
@@ -80,7 +82,9 @@ timeout, its local lease deadline, or a fenced transaction at its bound. On top
fenced transactions up to 20 s and finds a lapse at 30 s: the renewal waits on the transaction's share lock, times
out just before it ends, and the next fenced transaction starts before the next renewal. `inFencedSlices` keeps its
own transactions to 5 s (`FENCED_SLICE_MS`, #7415); see the known gaps for the rest.
-- **Fenced transactions of one holder do not overlap.** Postgres 16 lets a new `FOR SHARE` in beside the share locks
+- **A cancelled renewal settles within `CancelMs`** (10 s; the database answers the cancel). The clock runs while it is
+ pending, and no new renewal starts until it settles.
+- **Fenced transactions of one holder do not overlap, and the pass stamp's fence does not overlap them** (`Stamps = FALSE`). Postgres 16 lets a new `FOR SHARE` in beside the share locks
already held even while an `UPDATE` waits, and gives the row to the waiting `UPDATE` once every share lock is gone.
So a waiting renewal lands between serial fenced transactions and can starve under overlapping ones.
@@ -94,10 +98,11 @@ counts from the request, not from the moment it got the row.
| --- | --- |
| `Acquire` | `tryAcquireDbLock`'s upsert: insert, or take over a row whose TTL expired and whose last refresh is older than the steal grace; it waits for every `FOR SHARE` |
| `DeadPidTakeover` | `tryAcquireDbLock`'s second path (#1780) and `--break-lock`'s safe path: an unexpired row whose same-host pid the probe calls dead, older than `HOLDER_TAKEOVER_GRACE_MS` |
+| `StampBegin`, `StampEnd` | the pass stamp's fence in `provenStamp` (sync-pass-fold.ts) and `applyPassCheckpoint` (sync-prepare.ts): token and expiry, `FOR SHARE`, no signal check, run by the write coordinator |
| `StartRenew`, `RenewLand` | `withRefreshingLock`'s interval and `handle.refresh()`: one renewal in flight, `UPDATE ... WHERE id AND holder_pid AND acquisition_token`; a refused renewal aborts the lease signal |
| `RenewTimeout`, `CancelSettle` | the renewal timeout aborts the query; it settles later and never extends local authority |
| `LocalDeadline` | the expiry timer: the TTL passed with no confirmed renewal (`renewDeadline`) |
-| `BeginFenced`, `Commit`, `Rollback` | `assertDrainLease` inside a transaction (signal, token, expiry, `FOR SHARE`); lane 1 swaps the cursor. The pass stamp's checks in `provenStamp` and `applyPassCheckpoint` are the same fence without the signal check, which the model shows is defense in depth (`fence-ignores-signal` survives) |
+| `BeginFenced`, `Commit`, `Rollback` | `assertDrainLease` inside a transaction (signal, token, expiry, `FOR SHARE`); lane 1 swaps the cursor. |
| `Release` | `withRefreshingLock`'s finally: wait for the in-flight renewal, then `DELETE ... WHERE id AND holder_pid AND acquisition_token` |
| `Sleep`, `Wake`, `Crash` | the environment: a sleeping holder keeps its open transaction and share lock; a crash rolls them back |
@@ -108,8 +113,10 @@ counts from the request, not from the moment it got the row.
| Mutant | Kind | Caught by | Code and test |
| --- | --- | --- | --- |
| `fence-ignores-token` | guard | `FencedTxnsMatchRow` | `assertDrainLease`; `test/persistence-sync-lease.test.ts` |
-| `fold-stamp-ignores-token` | guard | `FencedTxnsMatchRow` | `provenStamp` (sync-pass-fold.ts); `test/drain-lease-stamp-fence.test.ts` and its Postgres twin |
-| `checkpoint-stamp-ignores-token` | guard | `FencedTxnsMatchRow` | `applyPassCheckpoint` (sync-prepare.ts); the same |
+| `fold-stamp-ignores-token` | guard | `FencedTxnsMatchRow` (`DrainLeaseStamp.cfg`) | `provenStamp` (sync-pass-fold.ts); `test/drain-lease-stamp-fence.test.ts` and its Postgres twin |
+| `checkpoint-stamp-ignores-token` | guard | `FencedTxnsMatchRow` (`DrainLeaseStamp.cfg`) | `applyPassCheckpoint` (sync-prepare.ts); the same |
+| `fold-stamp-without-share-lock` | guard | `FencedTxnsMatchRow` (`DrainLeaseStamp.cfg`) | `provenStamp`; the Postgres twin (a takeover from another connection waits until the import commits) |
+| `checkpoint-stamp-without-share-lock` | guard | `FencedTxnsMatchRow` (`DrainLeaseStamp.cfg`) | `applyPassCheckpoint`; the same |
| `fence-without-share-lock` | guard | `FencedTxnsMatchRow` | `assertDrainLease`; `test/e2e/drain-lease-fence-postgres.test.ts` |
| `takeover-ignores-ttl` | guard | `NoSpuriousLapse` | the upsert's `ON CONFLICT ... WHERE`; `test/drain-lease-guards.test.ts` and its Postgres twin |
| `release-ignores-token` | guard | `NoSpuriousLapse` | `handle.release()`; the same |
@@ -117,7 +124,8 @@ counts from the request, not from the moment it got the row.
| `pid-probe-calls-live-holder-dead` | guard | `NoSpuriousLapse` | `classifyHolderLiveness` (EPERM is alive); `test/db-lock-auto-takeover.test.ts` |
| `fenced-transaction-outlives-renewal-timeout` | guard | `NoSpuriousLapse` | `FENCED_SLICE_MS` (#7415); `test/sync-fenced-slices-gbra133.test.ts` |
| `fence-skips-queued-renewal` | assumption | `NoSpuriousLapse` | Postgres gives the row to the waiting renewal between serial transactions |
-| `overlapping-fenced-transactions` | assumption | `NoSpuriousLapse` | one fenced transaction per holder at a time (known gap 2) |
+| `overlapping-fenced-transactions` | assumption | `NoSpuriousLapse` | one fenced transaction per holder at a time |
+| `stamp-overlaps-fence` | assumption | `NoSpuriousLapse` | the pass stamp's fence does not overlap the holder's (known gap 2) |
| `fence-ignores-signal` | survivor | — | defense in depth: an abort is also visible to the token or expiry check |
| `fence-ignores-expiry` | survivor | — | defense in depth: `FOR SHARE` blocks a takeover while the transaction is open and the token refuses after it; `test/persistence-sync-lease.test.ts` still pins the refusal |
@@ -127,8 +135,7 @@ Postgres only: PGLite is one connection and serializes everything. Also left out
`LEASE_BEACON_QUEUE` holder record older binaries see (`test/persistence-sync-lease.test.ts`,
`test/minions-lease-beacon-sweeps-7261.test.ts`); a follower's wait and `drain_stalled` (`test/persistence-sync-lease.test.ts`);
reentrant passes under one lease; older binaries that take no lock; side effects outside the database; how the
-local monotonic clock behaves across a machine suspend; a coordinator in another process that keeps a pass-stamp
-transaction open after the holder crashed (its share lock delays a takeover; its token check still holds); and table
+local monotonic clock behaves across a machine suspend; and table
locks on `gbrain_cycle_locks` (writer activation, admin intents, skill activation), which hold every renewal for the
length of their transaction, so they count against the renewal timeout like a long fenced transaction.
@@ -144,5 +151,5 @@ The model shows the lease's liveness rests on two properties the code does not e
renewal. A fix that weakens the fence to `FOR KEY SHARE` would let the takeover upsert through too
(the test behind `fence-without-share-lock` catches that).
-Both are filed with the sync lane. The model keeps `NoSpuriousLapse` as stated and names these as assumptions rather
+Both are tracked in #7442 for the sync lane. The model keeps `NoSpuriousLapse` as stated and names these as assumptions rather
than weakening the property.
diff --git a/spec/tla/drain-lease/DrainLease.cfg b/spec/tla/drain-lease/DrainLease.cfg
index e4e682f7a6..f2e533261d 100644
--- a/spec/tla/drain-lease/DrainLease.cfg
+++ b/spec/tla/drain-lease/DrainLease.cfg
@@ -11,8 +11,10 @@ CONSTANTS
StealGraceMs = 60000
TakeoverGraceMs = 60000
MaxTxMs = 20000
+ CancelMs = 10000
RenewalWinsGap = TRUE
UnsafeSteals = FALSE
+ Stamps = FALSE
MaxTime = 18
MaxTokens = 3
MaxCursor = 2
diff --git a/spec/tla/drain-lease/DrainLease.tla b/spec/tla/drain-lease/DrainLease.tla
index bc1d67aee0..2986d7b670 100644
--- a/spec/tla/drain-lease/DrainLease.tla
+++ b/spec/tla/drain-lease/DrainLease.tla
@@ -31,8 +31,10 @@ CONSTANTS
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)
+ CancelMs, \* assumption: the longest a timed-out renewal takes to settle once cancelled (the database answers the cancel)
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
+ Stamps, \* model the pass stamp's fence: a coordinator transaction that takes the row FOR SHARE by a stamped token
MaxTime, MaxTokens, MaxCursor, MaxSleeps, MaxCrashes
CeilDiv(a, b) == (a + b - 1) \div b
@@ -43,6 +45,7 @@ RenewTO == CeilDiv(RenewTimeoutMs, TickMs)
Grace == StealGraceMs \div TickMs
PidGrace == TakeoverGraceMs \div TickMs
MaxTx == CeilDiv(MaxTxMs, TickMs)
+Cancel == CeilDiv(CancelMs, TickMs)
LaneIds == 1..Lanes
None == 0
@@ -61,10 +64,11 @@ VARIABLES
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
+ stampTok, stampAt, \* the coordinator's open pass-stamp transaction: the token it fenced on (None = none), start + 1
sleeps, crashes
vars == <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, pc, tok, aborted, deadline, nextRenew,
- renewAt, cancelling, txAt, txRead, disturbed, sleeps, crashes>>
+ renewAt, cancelling, txAt, txRead, disturbed, stampTok, stampAt, sleeps, crashes>>
local == <<pc, tok, aborted, deadline, nextRenew, renewAt, cancelling, txAt, txRead, disturbed>>
Closed == [l \in LaneIds |-> None]
@@ -72,6 +76,10 @@ 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) # {}}
+\* The coordinator's pass-stamp transaction holds it FOR SHARE.
+StampSharing == stampTok # None
+\* Anything holds the row FOR SHARE: an UPDATE or DELETE of the row waits.
+RowShared == Sharers # {} \/ StampSharing
TypeOK ==
/\ now \in 0..MaxTime /\ rowTok \in 0..MaxTokens /\ cursor \in 0..MaxCursor
@@ -84,7 +92,7 @@ Init ==
/\ 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
+ /\ disturbed = [p \in Procs |-> FALSE] /\ stampTok = None /\ stampAt = None /\ sleeps = 0 /\ crashes = 0
(* A process's state once it no longer holds anything. *)
Reset(p) ==
@@ -106,11 +114,11 @@ 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>>
+ /\ UNCHANGED <<now, cursor, aborted, renewAt, cancelling, txAt, txRead, disturbed, stampTok, stampAt, sleeps, crashes>>
Acquire(p) ==
/\ pc[p] = "idle" /\ nextTok <= MaxTokens
- /\ rowTok = None \/ (Sharers = {} /\ TakeoverAllowed)
+ /\ rowTok = None \/ (~RowShared /\ TakeoverAllowed)
/\ Grant(p)
(***************************************************************************)
@@ -124,7 +132,7 @@ 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
+ /\ rowTok # None /\ ~Expired /\ ~RowShared /\ now >= rowAcq + PidGrace
/\ UnsafeSteals \/ ~RowOwnerLive
/\ Grant(p)
@@ -139,12 +147,12 @@ StartRenew(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>>
+ cancelling, txAt, txRead, disturbed, stampTok, stampAt, 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 = {}
+RenewCanLand(p) == pc[p] = "holding" /\ Renewing(p) /\ ~RowShared
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 *)
@@ -159,24 +167,28 @@ RenewLand(p) ==
/\ 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>>
+ /\ UNCHANGED <<now, rowTok, rowAcq, cursor, nextTok, pc, tok, nextRenew, txAt, txRead, disturbed, stampTok, stampAt, 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
+(* later (CancelSettle, within CancelMs), the clock keeps running meanwhile, and no new renewal starts *)
+(* until it has. *)
+RenewTimeoutDue(p) == pc[p] = "holding" /\ Renewing(p) /\ ~cancelling[p] /\ RowShared /\ 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>>
+ renewAt, txAt, txRead, disturbed, stampTok, stampAt, sleeps, crashes>>
+
+(* The cancelled statement ends having changed nothing (it never got the row). It is owed only once *)
+(* CancelMs has passed since the cancel. *)
+CancelDue(p) == pc[p] = "holding" /\ Renewing(p) /\ cancelling[p] /\ now >= renewAt[p] + RenewTO + Cancel
-(* 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>>
+ txAt, txRead, disturbed, stampTok, stampAt, sleeps, crashes>>
(* The expiry timer: the TTL passed with no confirmed renewal. *)
DeadlineDue(p) == pc[p] = "holding" /\ ~aborted[p] /\ now >= deadline[p]
@@ -185,7 +197,7 @@ 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>>
+ txAt, txRead, disturbed, stampTok, stampAt, sleeps, crashes>>
(***************************************************************************)
(* assertDrainLease, in each transaction that admits work or swaps the *)
@@ -200,7 +212,7 @@ FencePasses(p) == FenceSignal(p) /\ FenceToken(p) /\ FenceExpiry
\* 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 # {})
+FenceQueue(p) == RenewalWinsGap => (~Renewing(p) \/ RowShared)
BeginFenced(p, l) ==
/\ pc[p] = "holding" /\ txAt[p][l] = None /\ cursor < MaxCursor
@@ -208,7 +220,7 @@ BeginFenced(p, l) ==
/\ 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>>
+ renewAt, cancelling, disturbed, stampTok, stampAt, sleeps, crashes>>
TxDue(p) == pc[p] = "holding" /\ \E l \in OpenTx(p) : now + 1 >= txAt[p][l] + MaxTx
@@ -219,13 +231,36 @@ Commit(p, l) ==
/\ 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>>
+ disturbed, stampTok, stampAt, 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>>
+ renewAt, cancelling, disturbed, stampTok, stampAt, sleeps, crashes>>
+
+(***************************************************************************)
+(* The pass stamp's fence (provenStamp, applyPassCheckpoint): the write *)
+(* coordinator, possibly another process, SELECTs the row WHERE the token *)
+(* stamped on the request matches AND ttl_expires_at > now() FOR SHARE, *)
+(* with no lease signal to check. The token may be any issued one (a stale *)
+(* request). A holder's crash does not end it. *)
+(***************************************************************************)
+StampToken(t) == rowTok = t
+StampQueue == RenewalWinsGap => (\A q \in Procs : Renewing(q) => RowShared)
+
+StampBegin(t) ==
+ /\ Stamps /\ stampTok = None
+ /\ StampToken(t) /\ FenceExpiry /\ StampQueue
+ /\ stampTok' = t /\ stampAt' = now + 1
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, sleeps, crashes>> /\ UNCHANGED local
+
+StampEnd ==
+ /\ stampTok # None
+ /\ stampTok' = None /\ stampAt' = None
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, sleeps, crashes>> /\ UNCHANGED local
+
+StampDue == stampTok # None /\ now + 1 >= stampAt + MaxTx
(***************************************************************************)
(* The pass ends, done or refused (a failed fence throws LockStolenError): *)
@@ -235,10 +270,10 @@ Rollback(p, l) ==
ReleaseMatches(p) == rowTok = tok[p]
Release(p) ==
- /\ pc[p] = "holding" /\ OpenTx(p) = {} /\ ~Renewing(p) /\ Sharers = {}
+ /\ pc[p] = "holding" /\ OpenTx(p) = {} /\ ~Renewing(p) /\ ~RowShared
/\ rowTok' = IF ReleaseMatches(p) THEN None ELSE rowTok
/\ Reset(p)
- /\ UNCHANGED <<now, rowExp, rowRef, rowAcq, cursor, nextTok, sleeps, crashes>>
+ /\ UNCHANGED <<now, rowExp, rowRef, rowAcq, cursor, nextTok, stampTok, stampAt, sleeps, crashes>>
(***************************************************************************)
(* Environment: a holder sleeps (machine asleep, event loop blocked), with *)
@@ -250,26 +285,26 @@ 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>>
+ renewAt, cancelling, txAt, txRead, stampTok, stampAt, 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>>
+ renewAt, cancelling, txAt, txRead, disturbed, stampTok, stampAt, sleeps, crashes>>
Crash(p) ==
/\ pc[p] # "idle" /\ crashes < MaxCrashes
/\ Reset(p) /\ crashes' = crashes + 1
- /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, sleeps>>
+ /\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, stampTok, stampAt, 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)
+Owes(p) == RenewDue(p) \/ RenewCanLand(p) \/ RenewTimeoutDue(p) \/ CancelDue(p) \/ DeadlineDue(p) \/ TxDue(p)
Tick ==
- /\ now < MaxTime /\ \A p \in Procs : ~Owes(p)
+ /\ now < MaxTime /\ \A p \in Procs : ~Owes(p) /\ ~StampDue
/\ now' = now + 1
- /\ UNCHANGED <<rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, sleeps, crashes>> /\ UNCHANGED local
+ /\ UNCHANGED <<rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, stampTok, stampAt, 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
@@ -277,6 +312,8 @@ Done == now = MaxTime /\ UNCHANGED vars
Next ==
\/ Tick
\/ Done
+ \/ StampEnd
+ \/ \E t \in 1..MaxTokens : StampBegin(t)
\/ \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)
@@ -290,7 +327,9 @@ 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]
+FencedTxnsMatchRow ==
+ /\ \A p \in Procs : OpenTx(p) # {} => rowTok = tok[p]
+ /\ stampTok # None => rowTok = stampTok
\* At most one process has fenced work open.
OneDrainer == Cardinality(Sharers) <= 1
diff --git a/spec/tla/drain-lease/DrainLeaseLanesNightly.cfg b/spec/tla/drain-lease/DrainLeaseLanesNightly.cfg
new file mode 100644
index 0000000000..de77ea35ce
--- /dev/null
+++ b/spec/tla/drain-lease/DrainLeaseLanesNightly.cfg
@@ -0,0 +1,28 @@
+\* Nightly only (tlc.sh runs it with TLC_NIGHTLY=1; about 5 minutes on 3 workers): DrainLeaseSafety.cfg with two
+\* overlapping fenced transactions per holder (sync lanes), at a shorter clock bound and one cursor step.
+SPECIFICATION Spec
+CHECK_DEADLOCK TRUE
+CONSTANTS
+ Procs = {p1, p2}
+ Lanes = 2
+ TickMs = 20000
+ TtlMs = 120000
+ RefreshMs = 20000
+ RenewTimeoutMs = 30000
+ StealGraceMs = 60000
+ TakeoverGraceMs = 60000
+ MaxTxMs = 60000
+ CancelMs = 120000
+ RenewalWinsGap = FALSE
+ UnsafeSteals = TRUE
+ Stamps = FALSE
+ MaxTime = 8
+ MaxTokens = 3
+ MaxCursor = 1
+ MaxSleeps = 1
+ MaxCrashes = 1
+SYMMETRY Symm
+INVARIANT TypeOK
+INVARIANT FencedTxnsMatchRow
+INVARIANT OneDrainer
+PROPERTY CursorMonotone
diff --git a/spec/tla/drain-lease/DrainLeaseSafety.cfg b/spec/tla/drain-lease/DrainLeaseSafety.cfg
index 42b8cadd2d..c1e7622271 100644
--- a/spec/tla/drain-lease/DrainLeaseSafety.cfg
+++ b/spec/tla/drain-lease/DrainLeaseSafety.cfg
@@ -14,8 +14,10 @@ CONSTANTS
StealGraceMs = 60000
TakeoverGraceMs = 60000
MaxTxMs = 60000
+ CancelMs = 120000
RenewalWinsGap = FALSE
UnsafeSteals = TRUE
+ Stamps = FALSE
MaxTime = 10
MaxTokens = 3
MaxCursor = 2
diff --git a/spec/tla/drain-lease/DrainLeaseStamp.cfg b/spec/tla/drain-lease/DrainLeaseStamp.cfg
new file mode 100644
index 0000000000..e787f76459
--- /dev/null
+++ b/spec/tla/drain-lease/DrainLeaseStamp.cfg
@@ -0,0 +1,29 @@
+\* The pass stamp's fence beside the holder's: a coordinator transaction that takes the row FOR SHARE by the token
+\* stamped on its request, any issued token, surviving the holder's crash. Every adverse assumption on, as in
+\* DrainLeaseSafety.cfg, without sleeps (a stamp outliving its holder covers that). Safety properties only.
+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
+ CancelMs = 120000
+ RenewalWinsGap = FALSE
+ UnsafeSteals = TRUE
+ Stamps = TRUE
+ MaxTime = 10
+ MaxTokens = 3
+ MaxCursor = 2
+ MaxSleeps = 0
+ 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 aea4d158b9..a04ca70bec 100644
--- a/spec/tla/drain-lease/mutants.json
+++ b/spec/tla/drain-lease/mutants.json
@@ -36,8 +36,8 @@
"expect": "FencedTxnsMatchRow",
"spec": {
"file": "DrainLease.tla",
- "before": "FenceToken(p) == rowTok = tok[p]",
- "after": "FenceToken(p) == TRUE"
+ "before": "StampToken(t) == rowTok = t",
+ "after": "StampToken(t) == TRUE"
},
"code": {
"edits": [
@@ -58,7 +58,8 @@
"postgres": true
}
]
- }
+ },
+ "config": "DrainLeaseStamp.cfg"
},
{
"id": "checkpoint-stamp-ignores-token",
@@ -67,8 +68,8 @@
"expect": "FencedTxnsMatchRow",
"spec": {
"file": "DrainLease.tla",
- "before": "FenceToken(p) == rowTok = tok[p]",
- "after": "FenceToken(p) == TRUE"
+ "before": "StampToken(t) == rowTok = t",
+ "after": "StampToken(t) == TRUE"
},
"code": {
"edits": [
@@ -89,6 +90,63 @@
"postgres": true
}
]
+ },
+ "config": "DrainLeaseStamp.cfg"
+ },
+ {
+ "id": "fold-stamp-without-share-lock",
+ "kind": "guard",
+ "title": "a folded stamp's proof reads the row without FOR SHARE, so a takeover proceeds before its import commits",
+ "expect": "FencedTxnsMatchRow",
+ "config": "DrainLeaseStamp.cfg",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": "StampSharing == stampTok # None",
+ "after": "StampSharing == FALSE"
+ },
+ "code": {
+ "edits": [
+ {
+ "file": "src/core/persistence/sync-pass-fold.ts",
+ "before": "ttl_expires_at > now() FOR SHARE', [syncLockId(row.source_id), stamp.leaseToken]",
+ "after": "ttl_expires_at > now()', [syncLockId(row.source_id), stamp.leaseToken]"
+ }
+ ],
+ "tests": [
+ {
+ "test": "test/e2e/drain-lease-stamp-fence-postgres.test.ts",
+ "filter": "a folded stamp holds the lease row FOR SHARE",
+ "postgres": true
+ }
+ ]
+ }
+ },
+ {
+ "id": "checkpoint-stamp-without-share-lock",
+ "kind": "guard",
+ "title": "the checkpoint request reads the row without FOR SHARE, so a takeover proceeds before it commits",
+ "expect": "FencedTxnsMatchRow",
+ "config": "DrainLeaseStamp.cfg",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": "StampSharing == stampTok # None",
+ "after": "StampSharing == FALSE"
+ },
+ "code": {
+ "edits": [
+ {
+ "file": "src/core/persistence/sync-prepare.ts",
+ "before": "ttl_expires_at > now() FOR SHARE', [syncLockId(row.source_id), stamp.leaseToken]",
+ "after": "ttl_expires_at > now()', [syncLockId(row.source_id), stamp.leaseToken]"
+ }
+ ],
+ "tests": [
+ {
+ "test": "test/e2e/drain-lease-stamp-fence-postgres.test.ts",
+ "filter": "a checkpoint request holds the lease row FOR SHARE",
+ "postgres": true
+ }
+ ]
}
},
{
@@ -300,6 +358,17 @@
"after": "Lanes = 2"
}
},
+ {
+ "id": "stamp-overlaps-fence",
+ "kind": "assumption",
+ "title": "the coordinator's pass-stamp transaction holds the row FOR SHARE beside the holder's fenced transactions (#7442)",
+ "expect": "NoSpuriousLapse",
+ "spec": {
+ "file": "DrainLease.cfg",
+ "before": " Stamps = FALSE",
+ "after": " Stamps = TRUE"
+ }
+ },
{
"id": "fence-ignores-signal",
"kind": "survivor",
diff --git a/test/drain-lease-stamp-fence.test.ts b/test/drain-lease-stamp-fence.test.ts
index d1464ccff4..abea0c1332 100644
--- a/test/drain-lease-stamp-fence.test.ts
+++ b/test/drain-lease-stamp-fence.test.ts
@@ -16,7 +16,6 @@ import type { BrainEngine } from '../src/core/engine.ts';
import { syncLockId } from '../src/core/db-lock.ts';
import { installFaultHook } from '../src/core/persistence/fault-points.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
-import { stampByCheckpoint } from './helpers/pass-fold.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -80,5 +79,48 @@ for (const backend of testBackends()) {
expect(row!.state).not.toBe('committed');
expect(await lastCommit(engine)).toBe(before);
}), 180_000);
+
+ // Postgres only: PGLite is one connection, so nothing can try a takeover while the stamp's transaction is open.
+ if (backend === 'postgres') {
+ /** A takeover as tryAcquireDbLock's upsert or --break-lock writes it, from another connection, giving up after 1 s. */
+ const takeoverDuring = (engine: BrainEngine) => engine.transaction(async tx => {
+ await tx.executeRaw("SET LOCAL lock_timeout = '1s'");
+ return (await tx.executeRaw('UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid() WHERE id=$1 RETURNING id', [syncLockId('default')])).length;
+ }).catch((error: { code?: string }) => error.code ?? String(error));
+
+ test('a folded stamp holds the lease row FOR SHARE until its import commits, so a takeover waits', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A committed change of notes/a.')); commit(root, 'change a');
+ const stamped = new Set<string>();
+ let during = null as unknown;
+ installFaultHook(async (point, detail) => {
+ if (point === 'consumer:prepared' && detail.requestId && (await kindOf(engine, detail.requestId))?.stamp) stamped.add(detail.requestId);
+ // The publication transaction is open here, after the folded stamp's proof read the lease row.
+ if (point === 'publication:before_commit' && during === null && detail.requestId && stamped.has(detail.requestId)) during = await takeoverDuring(engine);
+ });
+ await performManagedSync(engine, OPTS).catch(() => undefined);
+ installFaultHook(undefined);
+ const [row] = await engine.executeRaw<{ stamp: string | null }>("SELECT outcome->>'pass_stamp' AS stamp FROM persistence_requests WHERE request_id=$1::uuid", [[...stamped][0]]);
+ expect(row?.stamp).toBe('folded');
+ expect(during).toBe('55P03');
+ }), 180_000);
+
+ test('a checkpoint request holds the lease row FOR SHARE until it commits, so a takeover waits', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A committed change of notes/a.')); commit(root, 'change a');
+ const checkpoints = new Set<string>();
+ let during = null as unknown;
+ installFaultHook(async (point, detail) => {
+ if (point === 'sync:pass_fold') throw new Error('The test refuses the folded stamp.');
+ if (point === 'consumer:prepared' && detail.requestId && (await kindOf(engine, detail.requestId))?.kind === 'managed_sync_checkpoint') checkpoints.add(detail.requestId);
+ if (point === 'publication:before_commit' && during === null && detail.requestId && checkpoints.has(detail.requestId)) during = await takeoverDuring(engine);
+ });
+ await performManagedSync(engine, OPTS).catch(() => undefined);
+ installFaultHook(undefined);
+ const [row] = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE request_id=$1::uuid", [[...checkpoints][0]]);
+ expect(row?.state).toBe('committed');
+ expect(during).toBe('55P03');
+ }), 180_000);
+ }
});
}
diff --git a/test/spec-drain-lease-constants.test.ts b/test/spec-drain-lease-constants.test.ts
index a451aa7a09..35acc36a60 100644
--- a/test/spec-drain-lease-constants.test.ts
+++ b/test/spec-drain-lease-constants.test.ts
@@ -4,7 +4,7 @@
* 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 { readdirSync, 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';
@@ -12,7 +12,7 @@ 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'];
+const CONFIGS = readdirSync(SPEC).filter(f => f.endsWith('.cfg')).sort();
function constants(cfg: string): Record<string, string> {
const out: Record<string, string> = {};