Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: pass-stamp fence mutants and tests, README, docs, test:tla, nightly watch

garrytan5be8262a07e9
diff --git a/.github/workflows/nightly-watch.yml b/.github/workflows/nightly-watch.yml
index 4e5f21c54f..0be4f37383 100644
--- a/.github/workflows/nightly-watch.yml
+++ b/.github/workflows/nightly-watch.yml
@@ -56,6 +56,7 @@ on:
- Semgrep
- OSV-Scanner
- CI health
+ - TLA+ specs
types: [completed]
branches: [master]
workflow_dispatch:
diff --git a/.github/workflows/tla-spec.yml b/.github/workflows/tla-spec.yml
index 5af17e3d17..a38b826bd9 100644
--- a/.github/workflows/tla-spec.yml
+++ b/.github/workflows/tla-spec.yml
@@ -14,12 +14,18 @@ on:
- '.github/workflows/tla-spec.yml'
- 'src/core/persistence/sync-lease.ts'
- 'src/core/db-lock.ts'
+ - 'src/core/persistence/sync-pass-fold.ts'
+ - 'src/core/persistence/sync-prepare.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'
+ - 'test/drain-lease-guards.test.ts'
+ - 'test/e2e/drain-lease-guards-postgres.test.ts'
+ - 'test/drain-lease-stamp-fence.test.ts'
+ - 'test/e2e/drain-lease-stamp-fence-postgres.test.ts'
push:
branches: [master]
paths: *paths
diff --git a/docs/TESTING.md b/docs/TESTING.md
index d4137616cf..ea67154014 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -1,9 +1,8 @@
# Testing (gbrain repo)
-This is the contributor reference for how gbrain is tested: which lanes exist,
-what each one proves, how CI runs them, and the guards that keep those claims
-honest. It describes current behavior and invariants only. Release history
-lives in `CHANGELOG.md`; per-file detail lives in the test files and in
+How gbrain is tested: which lanes exist, what each proves, how CI runs them and
+the guards that keep those claims honest. Current behavior and invariants only:
+history lives in `CHANGELOG.md`, per-file detail in the tests and
`docs/architecture/KEY_FILES.md`.
## Quick start
@@ -16,9 +15,8 @@ runner validates Bun's JUnit reports with the standard-library XML parser).
bun install --frozen-lockfile && bun run test && bun run verify
```
-`bun run test` is the parallel unit loop plus the serial pass (a few minutes on
-a laptop); `bun run verify` is CI's guard battery (about a minute). For E2E,
-follow [E2E test DB lifecycle](#e2e-test-db-lifecycle-always-follow-this) and
+`bun run test` is the parallel unit loop plus the serial pass; `bun run verify`
+is CI's guard battery (about a minute). For E2E, follow [E2E test DB lifecycle](#e2e-test-db-lifecycle-always-follow-this) and
run `DATABASE_URL=postgresql://postgres:postgres@localhost:5434/gbrain_test bun run test:e2e`.
`bun run ci:local` runs the whole CI gate in Docker; `bun run ci:ubicloud` runs
it on ephemeral VMs in about five minutes.
@@ -215,6 +213,7 @@ JSONB, locking and pooler behavior are not established by a PGLite pass.
| Keyless behavior, structural guards and shared contracts | Unit shards and `verify` in `test.yml`; process-isolated serial and dedicated slow lanes where required | Real PostgreSQL, native activation or compiled behavior |
| PostgreSQL behavior and engine parity | Selected E2E and named jobs in `e2e.yml`; the complete nightly runner corpus | Execution of key-gated or native-door assertions merely because their files were discovered |
| Durable publication and recovery under sustained load | `persistence-validation.yml` and `scripts/persistence/README.md` | Power-loss safety, production authentication or equivalence to two smaller databases |
+| All interleavings of a TLA+ model | `tla-spec.yml`, `spec/tla/README.md` | Behavior outside the model |
| Native lock ABI and compiled-process exclusion | `native-locks.yml`, compiled smoke and release validation | All compiled CLI features or native-harness activation |
| Browser journeys | Required `admin-browser` job and `admin/e2e/*.pw.ts` | Vendor-native agent behavior |
| Native agent doors and heavier operational scenarios | Explicit jobs in `heavy-tests.yml` | A passing skipped door or generic protocol test is not native activation |
diff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.md
index fe7867905d..20cc73e4d7 100644
--- a/docs/architecture/key-files/ci-health-and-test-guards.md
+++ b/docs/architecture/key-files/ci-health-and-test-guards.md
@@ -32,3 +32,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/check-skill-refs.mjs` + `scripts/portable-skill-links.ts` + `scripts/skills-commit-gate.sh` — skills-tree integrity gate (`bun run check:skill-refs`, in verify and the skills commit gate). Fails on dangling backtick `skills/` refs, `./`/`../` links, `composes:` and RESOLVER dispatcher slugs; donor-workspace paths outside the shrink-only allowlist; any `gbrain <cmd>` in a fenced line or inline code span (command position only: line/span start, after a shell separator, `nohup`/env prefixes) that is not a real command (union of `--tools-json`, `CLI_FLAG_REGISTRY`, `src/cli.ts` dispatch, the command table and op `cliHints`), plus curated known-bad subcommands (`embed refresh`); and a relative link that resolves outside the skills root, in `skills/` and in the generated `plugin/skills` and `plugin-variants/*/skills` trees (`skills/migrations/**` exempt). W4.7: a tools-json load failure FAILS the CLI lane (`--no-cli-refs` skips it deliberately); links are read in every form (`](./x)`, bare `](x.md)` unless a placeholder, `](<x>)`, titled, `[id]: x` definitions); a `[paid-consent]` lane, migrations included, fails a paid `gbrain` command carrying `--yes`/`--max-usd`/`--max-cost[-usd]` with no ask/agree/approve/consent/confirm/permission wording on its line or the 8 before. `portable-skill-links.ts` is that rule's fix: it points `docs/protocol/AGENT_OPERATOR_v1.md` links at the bundled `skills/conventions/agent-operator-protocol.md` and other repo files at absolute blob URLs derived from `LLMS_REPO_BASE` (raw.githubusercontent base → github.com blob base; default `garrytan/gbrain/blob/master`; a non-https or credentialed value throws via `repoBaseOrThrow`, as in `scripts/llms-config.ts`), retargeting default-base links for forks; `--check` reports pending rewrites. Tests: `test/check-skill-refs.test.ts`, `test/skills-portable-links.test.ts` (scaffold `--all` into a tmp host: 0 broken local links).
- `scripts/check-file-url-pathname.sh` — `check:file-url-pathname` (in verify, #6845): no `.pathname` of a file URL (`import.meta.url).pathname`, `pathToFileURL(...).pathname`) in test/, which keeps `%20` and breaks a checkout under a path with a space; use `fileURLToPath` or `import.meta.dir`. Self-tested via `GBRAIN_GUARD_ROOT` fixtures; skips `test/fixtures/guards/`.
+- `spec/tla/` + `scripts/spec/{tlc.sh,tla-jar.sh,tla-tools.env,mutants.ts}` + `.github/workflows/tla-spec.yml` — TLA+ models checked exhaustively by TLC within small bounds; `spec/tla/drain-lease` models the managed-sync drain lease (`sync-lease.ts` over `db-lock.ts`, plus the pass stamp's fences in `sync-pass-fold.ts` and `sync-prepare.ts`). `tlc.sh` runs every config on a private copy and fails `TLC_VIOLATION`, `TLC_TIMEOUT` or `TLC_ERROR`; `tla-jar.sh` fetches the pinned tla2tools.jar and refuses a sha256 mismatch. `mutants.ts` checks `mutants.json`: each guard mutant's model edit must break its named property, and its code edits (every engine branch), applied in a scratch copy of the tree, must fail each named test on its own assertions; assumption mutants document what liveness rests on, survivors stay defense in depth. `bun run test:tla` runs both; the workflow runs them nightly and on changes to anything a mutant names (`test/spec-drain-lease-constants.test.ts` pins that path filter and the configs' timing to the code's constants). Guard tests: `test/drain-lease-guards.test.ts`, `test/drain-lease-stamp-fence.test.ts` (Postgres twins in `test/e2e/`), `test/e2e/drain-lease-fence-postgres.test.ts`. Docs: `spec/tla/README.md`.
diff --git a/package.json b/package.json
index ad4dc96546..91f535e8b5 100644
--- a/package.json
+++ b/package.json
@@ -100,6 +100,7 @@
"test:profile": "bash scripts/profile-tests.sh",
"test:serial": "bash scripts/run-serial-tests.sh",
"test:convergence": "GBRAIN_TEST_CONVERGENCE=1 bun --no-env-file test --timeout=3600000 test/sync-convergence.serial.test.ts",
+ "test:tla": "bash scripts/spec/tlc.sh && bun scripts/spec/mutants.ts",
"ci:local": "bash scripts/ci-local.sh",
"ci:local:diff": "bash scripts/ci-local.sh --diff",
"ci:ubicloud": "bun run scripts/ci-ubicloud.ts",
diff --git a/spec/tla/README.md b/spec/tla/README.md
new file mode 100644
index 0000000000..57acf562fa
--- /dev/null
+++ b/spec/tla/README.md
@@ -0,0 +1,139 @@
+# TLA+ specs
+
+TLA+ models of gbrain's concurrency protocols, checked exhaustively at small bounds by TLC, the TLA+ model checker. Each
+guard a model relies on is a mutant: removing it from the model must break a named property, and removing it from the
+code must fail a named test. The crash robot (`scripts/persistence/`) samples real schedules; these models cover every
+interleaving of the modelled actions inside their bounds. The approach follows Parcha's agentrun `spec/receipts`
+(Apache-2.0); no code was copied.
+
+## Run it
+
+```sh
+bun run test:tla # every config of every spec, then every mutant (model and code)
+bash scripts/spec/tlc.sh drain-lease DrainLease.cfg # one config
+bun scripts/spec/mutants.ts --only renewal-ignores-token
+bun scripts/spec/mutants.ts --spec-only # model mutants only (no Bun tests)
+```
+
+Needs Java 11 or later (CI uses temurin 21), GNU `timeout` (`brew install coreutils` on macOS) and Bun.
+`scripts/spec/tla-jar.sh` downloads tla2tools.jar once into `~/.cache/gbrain/tla` and checks it against the sha256 in
+`scripts/spec/tla-tools.env`; set `TLA2TOOLS` to use a jar you already have (it is checked too). The code mutants
+that need Postgres run when `DATABASE_URL` points at a test database (with `GBRAIN_TEST_ALLOW_DATABASE_URL=1`);
+otherwise they print `skip`, and CI passes `--require-postgres`. Logs and counterexample traces land in
+`.context/tlc/` (`TLC_OUT`), and CI uploads them as the `tla-spec-logs` artifact.
+
+`.github/workflows/tla-spec.yml` runs all of it nightly, on dispatch, and on pull requests and master pushes that touch a
+spec, its runner, the code a spec models, or a test a mutant names.
+
+### When it fails
+
+| Code | Meaning | What to do |
+| --- | --- | --- |
+| `TLC_VIOLATION` | A property is violated. | Read the trace in the log; the action table below maps each step to code. Fix the code, or fix the spec when it is wrong and say why in the PR. |
+| `TLC_TIMEOUT` | TLC did not finish within `TLC_TIMEOUT_S` (600 s). | The state space grew: shrink the config's bounds, or find the action that multiplies states. |
+| `TLC_ERROR` | TLC stopped: a parse or semantic error, or out of memory. | The log names the line. |
+| `TLA_JAR_DOWNLOAD_FAILED` | The jar did not download. | Rerun. |
+| `TLA_JAR_SHA_MISMATCH` | The jar is not the reviewed release. | Never rerun; a new pin needs review. |
+| `MUTANT_STALE` | A mutant's `before` text is not found exactly once. | The spec or code moved: update the mutant's text in `mutants.json`. |
+| `MUTANT_SURVIVED` | No property caught a model mutant, or the named test passed with the guard removed from the code. | A property or a test stopped pinning the guard. Restore it; never delete the mutant to go green. |
+| `MUTANT_WRONG_PROPERTY` | A different property caught it, or a survivor became load-bearing. | Read the trace; update `expect`, and give a new load-bearing guard a code edit and a test. |
+| `MUTANT_INCOMPLETE` | TLC did not finish, or a named test failed without the edit, matched no test, or did not load with it. | Fix the test or the filter first; a failure that is not the test's own assertion proves nothing. |
+
+## drain-lease: the managed-sync drain lease
+
+One drainer per source at a time (`src/core/persistence/sync-lease.ts` over `src/core/db-lock.ts`). The lease is one
+`gbrain_cycle_locks` row; its `acquisition_token` is the fencing token. Every transaction that admits sync work or
+swaps the cursor runs `assertDrainLease`, which reads the row by token `FOR SHARE`. The pass stamp takes the same share
+lock with the token stamped on its request: a folded stamp's proof (`provenStamp`) and the checkpoint request
+(`applyPassCheckpoint`), both run by the write coordinator, possibly in another process.
+
+| 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. |
+
+`test/spec-drain-lease-constants.test.ts` keeps both configs' timing equal to the code's constants and checks the
+ordering the liveness property needs.
+
+### Properties
+
+| Property | Holds that |
+| --- | --- |
+| `FencedTxnsMatchRow` | every open fenced transaction belongs to the row's current holder, so every commit is made under the live lease |
+| `OneDrainer` | at most one process has fenced work open |
+| `CursorMonotone` | the sync cursor never moves backward |
+| `NoSpuriousLapse` | a holder that never slept (machine asleep, event loop blocked) never loses its lease, under the timing assumptions below |
+
+### Timing assumptions
+
+An awake holder runs its timers on time: the clock does not pass a due renewal, a renewal that can land, a renewal
+timeout, its local lease deadline, or a fenced transaction at its bound. On top of that, `NoSpuriousLapse` needs:
+
+- **Every fenced transaction closes in under the renewal timeout** (30 s, `withRefreshingLock`). TLC passes with
+ 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
+ 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.
+
+Times are rounded so the model is never kinder than the code: TTL and graces round down, the refresh interval,
+renewal timeout and transaction bound round up. A renewal's `now()` is its statement's start, so the row's expiry
+counts from the request, not from the moment it got the row.
+
+### Actions and code
+
+| Action | Code |
+| --- | --- |
+| `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` |
+| `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) |
+| `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 |
+
+### Mutants
+
+`mutants.json`. A guard mutant has a code edit (every engine branch) and the tests that must fail under it.
+
+| 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 |
+| `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 |
+| `renewal-ignores-token` | guard | `NoSpuriousLapse` | `handle.refresh()`: a former holder's late renewal, its `now()` taken when it was sent, would rewind its successor's expiry; the same |
+| `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) |
+| `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 |
+
+### Not modelled
+
+Postgres only: PGLite is one connection and serializes everything. Also left out, each covered elsewhere: the
+`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; and 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).
+
+### Known gaps
+
+The model shows the lease's liveness rests on two properties the code does not enforce yet:
+
+1. Nothing bounds every fenced transaction under the 30 s renewal timeout. `inFencedSlices` checks its 5 s budget only
+ between items, other call sites of `assertDrainLease` run one transaction over a whole batch, and the pass stamp's
+ checks run inside the coordinator's publication transactions, whose length the lease does not bound.
+2. The holder's own fenced transactions run one after another (admissions are serial), but the pass stamp's checks run
+ in the coordinator's publication transactions alongside them, so the row can stay `FOR SHARE` across a waiting
+ 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
+than weakening the property.
diff --git a/spec/tla/drain-lease/mutants.json b/spec/tla/drain-lease/mutants.json
index bbb7828db9..aea4d158b9 100644
--- a/spec/tla/drain-lease/mutants.json
+++ b/spec/tla/drain-lease/mutants.json
@@ -29,6 +29,68 @@
]
}
},
+ {
+ "id": "fold-stamp-ignores-token",
+ "kind": "guard",
+ "title": "a folded pass stamp's proof admits a token that is not the row's",
+ "expect": "FencedTxnsMatchRow",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": "FenceToken(p) == rowTok = tok[p]",
+ "after": "FenceToken(p) == TRUE"
+ },
+ "code": {
+ "edits": [
+ {
+ "file": "src/core/persistence/sync-pass-fold.ts",
+ "before": "acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE",
+ "after": "$2::uuid IS NOT NULL AND ttl_expires_at > now() FOR SHARE"
+ }
+ ],
+ "tests": [
+ {
+ "test": "test/drain-lease-stamp-fence.test.ts",
+ "filter": "a folded stamp is refused"
+ },
+ {
+ "test": "test/e2e/drain-lease-stamp-fence-postgres.test.ts",
+ "filter": "a folded stamp is refused",
+ "postgres": true
+ }
+ ]
+ }
+ },
+ {
+ "id": "checkpoint-stamp-ignores-token",
+ "kind": "guard",
+ "title": "the checkpoint request's stamp admits a token that is not the row's",
+ "expect": "FencedTxnsMatchRow",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": "FenceToken(p) == rowTok = tok[p]",
+ "after": "FenceToken(p) == TRUE"
+ },
+ "code": {
+ "edits": [
+ {
+ "file": "src/core/persistence/sync-prepare.ts",
+ "before": "acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE",
+ "after": "$2::uuid IS NOT NULL AND ttl_expires_at > now() FOR SHARE"
+ }
+ ],
+ "tests": [
+ {
+ "test": "test/drain-lease-stamp-fence.test.ts",
+ "filter": "a checkpoint request is refused"
+ },
+ {
+ "test": "test/e2e/drain-lease-stamp-fence-postgres.test.ts",
+ "filter": "a checkpoint request is refused",
+ "postgres": true
+ }
+ ]
+ }
+ },
{
"id": "fence-without-share-lock",
"kind": "guard",
diff --git a/test/drain-lease-stamp-fence.test.ts b/test/drain-lease-stamp-fence.test.ts
new file mode 100644
index 0000000000..d1464ccff4
--- /dev/null
+++ b/test/drain-lease-stamp-fence.test.ts
@@ -0,0 +1,84 @@
+/**
+ * The pass stamp's own drain-lease fences, on both engines. Besides `assertDrainLease`, two transactions read the lease row
+ * by token `FOR SHARE`: a folded stamp's proof (`provenStamp`, sync-pass-fold.ts) and the checkpoint request's
+ * (`applyPassCheckpoint`, sync-prepare.ts). A coordinator runs them with the token stamped on the request, so they fence the
+ * holder's lease even when they run in another process. The drain lease's model (spec/tla/drain-lease) treats them as
+ * fenced transactions of the holder: each token check is a guard mutant in spec/tla/drain-lease/mutants.json, and removing
+ * it from the code must fail its test here.
+ *
+ * Runs on PGLite here and on Postgres through test/e2e/drain-lease-stamp-fence-postgres.test.ts.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+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';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const note = (slug: string, body: string) => `---\ntype: concept\ntitle: ${slug}\n---\n\n${body}\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (const slug of ['a', 'b']) writeFileSync(join(root, `notes/${slug}.md`), note(`notes/${slug}`, `The committed body of notes/${slug}.`));
+ commit(root, 'notes');
+};
+const lastCommit = async (engine: BrainEngine) => (await engine.executeRaw<{ last_commit: string | null }>("SELECT last_commit FROM sources WHERE id='default'"))[0]?.last_commit ?? null;
+const kindOf = async (engine: BrainEngine, requestId: string) =>
+ (await engine.executeRaw<{ kind: string | null; stamp: boolean }>("SELECT intent->>'kind' AS kind, intent ? 'stamp' AS stamp FROM persistence_requests WHERE request_id=$1::uuid", [requestId]))[0];
+/** Another drainer took the lease over: the row is live, under a token the pass does not hold. */
+const takeOver = (engine: BrainEngine) => engine.executeRaw('UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid() WHERE id=$1', [syncLockId('default')]);
+
+afterEach(() => installFaultHook(undefined));
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ const brain = (run: Parameters<typeof managedBrain>[0]) => managedBrain(run, { ...(databaseUrl ? { databaseUrl } : {}), setup });
+
+ describe(`drain lease: the pass stamp's fences (${backend})`, () => {
+ test('a folded stamp is refused once the lease is taken over before its import publishes', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ const before = await lastCommit(engine);
+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A committed change of notes/a.')); commit(root, 'change a');
+ let stamped = null as string | null;
+ installFaultHook(async (point, detail) => {
+ if (point !== 'consumer:prepared' || stamped || !detail.requestId || !(await kindOf(engine, detail.requestId))?.stamp) return;
+ stamped = detail.requestId;
+ await takeOver(engine);
+ });
+ await performManagedSync(engine, OPTS).catch(() => undefined);
+ installFaultHook(undefined);
+ expect(stamped).not.toBeNull();
+ const [outcome] = await engine.executeRaw<{ stamp: string | null; skipped: string | null }>(
+ "SELECT outcome->>'pass_stamp' AS stamp, outcome->>'pass_stamp_skipped' AS skipped FROM persistence_requests WHERE request_id=$1::uuid", [stamped]);
+ expect(outcome).toEqual({ stamp: null, skipped: 'lease' });
+ expect(await lastCommit(engine)).toBe(before);
+ }), 180_000);
+
+ test('a checkpoint request is refused once the lease is taken over before it publishes', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ const before = await lastCommit(engine);
+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A committed change of notes/a.')); commit(root, 'change a');
+ let checkpoint = null as string | null;
+ installFaultHook(async (point, detail) => {
+ if (point === 'sync:pass_fold') throw new Error('The test refuses the folded stamp.');
+ if (point !== 'consumer:prepared' || checkpoint || !detail.requestId || (await kindOf(engine, detail.requestId))?.kind !== 'managed_sync_checkpoint') return;
+ checkpoint = detail.requestId;
+ await takeOver(engine);
+ });
+ await performManagedSync(engine, OPTS).catch(() => undefined);
+ installFaultHook(undefined);
+ expect(checkpoint).not.toBeNull();
+ const [row] = await engine.executeRaw<{ state: string; error: string | null }>(
+ "SELECT state, error_detail->>'message' AS error FROM persistence_requests WHERE request_id=$1::uuid", [checkpoint]);
+ expect(row!.state).not.toBe('committed');
+ expect(await lastCommit(engine)).toBe(before);
+ }), 180_000);
+ });
+}
diff --git a/test/e2e/drain-lease-stamp-fence-postgres.test.ts b/test/e2e/drain-lease-stamp-fence-postgres.test.ts
new file mode 100644
index 0000000000..a6b58f99e5
--- /dev/null
+++ b/test/e2e/drain-lease-stamp-fence-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../drain-lease-stamp-fence.test.ts'));
diff --git a/test/spec-drain-lease-constants.test.ts b/test/spec-drain-lease-constants.test.ts
index abcf71654c..a451aa7a09 100644
--- a/test/spec-drain-lease-constants.test.ts
+++ b/test/spec-drain-lease-constants.test.ts
@@ -72,3 +72,13 @@ describe('spec/tla/drain-lease configs match the code', () => {
expect(Number(c.MaxTxMs)).toBeGreaterThanOrEqual(Number(c.RenewTimeoutMs));
});
});
+
+describe('the TLA+ workflow runs when anything a mutant names changes', () => {
+ test('every code file and test in mutants.json is in tla-spec.yml\'s path filter', () => {
+ const workflow = readFileSync(join(ROOT, '.github/workflows/tla-spec.yml'), 'utf8');
+ const paths = new Set([...workflow.matchAll(/^\s+- '([^']+)'$/gm)].map(m => m[1]!));
+ const { mutants } = JSON.parse(readFileSync(join(SPEC, 'mutants.json'), 'utf8')) as { mutants: Array<{ code?: { edits: Array<{ file: string }>; tests: Array<{ test: string }> } }> };
+ const named = new Set(mutants.flatMap(m => m.code ? [...m.code.edits.map(e => e.file), ...m.code.tests.map(t => t.test)] : []));
+ expect([...named].filter(file => !paths.has(file)), 'add these to on.pull_request.paths in .github/workflows/tla-spec.yml').toEqual([]);
+ });
+});