Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

spec(tla): fold #7442's FOR KEY SHARE fence into the drain-lease model

garrytanf689b1f42560
diff --git a/.github/workflows/tla-spec.yml b/.github/workflows/tla-spec.yml
index 98928202f9..c055e9e97e 100644
--- a/.github/workflows/tla-spec.yml
+++ b/.github/workflows/tla-spec.yml
@@ -26,6 +26,8 @@ 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/drain-lease-key-share-7442.test.ts'
+ - 'test/e2e/drain-lease-key-share-7442-postgres.test.ts'
- 'test/helpers/managed-brain.ts'
- 'test/helpers/test-backends.ts'
- 'test/helpers/persistence-postgres.ts'
@@ -49,6 +51,8 @@ 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/drain-lease-key-share-7442.test.ts'
+ - 'test/e2e/drain-lease-key-share-7442-postgres.test.ts'
- 'test/helpers/managed-brain.ts'
- 'test/helpers/test-backends.ts'
- 'test/helpers/persistence-postgres.ts'
diff --git a/spec/tla/README.md b/spec/tla/README.md
index fdd248ca41..75fc1a00a5 100644
--- a/spec/tla/README.md
+++ b/spec/tla/README.md
@@ -50,15 +50,15 @@ copy of the tree there. A failed or interrupted run leaves only partial logs in
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
+swaps the cursor runs `assertDrainLease`, which reads the row by token `FOR KEY SHARE` (`fenceLockRow`, #7442). The pass
+stamp takes the same 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. |
+| `DrainLease.cfg` | Two drainers, one fenced transaction at a time, the code's timing at 10 s ticks, fenced transactions up to 60 s (twice the renewal timeout), no renewal priority and the pass stamp's fence on: 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, 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. |
+| `DrainLeaseStamp.cfg` | The same, plus the pass stamp's fence: a coordinator transaction that holds the row `FOR KEY 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 2 minutes on 4 CPUs, so `tlc.sh` runs it only with `TLC_NIGHTLY=1` (the schedule and dispatch). |
`test/spec-drain-lease-constants.test.ts` keeps every config's timing equal to the code's constants and checks the
@@ -78,15 +78,16 @@ ordering the liveness property needs.
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.
- **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.
+- **Fenced transactions of one holder do not overlap** (`Lanes = 1` in `DrainLease.cfg`; admissions are serial). Two lanes
+ were checked once at `MaxTime = 12` (6,420,020 states, every property); that run is not in CI.
+
+The fence no longer needs a bound on fenced transactions. Before #7442 it took the row `FOR SHARE`, so the renewal's
+`UPDATE` waited behind the holder's own fenced transactions and the pass stamp, and TLC found a live holder losing its lease
+once a fenced transaction outlived the renewal timeout. `FOR KEY SHARE` conflicts only with writes to the key (the takeover
+upsert's `SET id = EXCLUDED.id`) and with `DELETE`, so the renewal lands while the row is fenced; mutant
+`fence-takes-share-lock` puts the old lock back and TLC finds the lapse again.
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
@@ -96,13 +97,13 @@ counts from the request, not from the moment it got the row.
| 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` |
+| `Acquire` | `tryAcquireDbLock`'s upsert: insert, or take over a row whose TTL expired and whose last refresh is older than the steal grace; it writes the key (`SET id = EXCLUDED.id`), so it waits for every `FOR KEY 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 |
+| `StampBegin`, `StampEnd` | the pass stamp's fence in `provenStamp` (sync-pass-fold.ts) and `applyPassCheckpoint` (sync-prepare.ts): token and expiry, `FOR KEY SHARE` (`fenceLockRow`), 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`, which writes no key, so the fence does not block it; 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. |
+| `BeginFenced`, `Commit`, `Rollback` | `assertDrainLease` inside a transaction (signal, token, expiry, `FOR KEY 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 |
@@ -112,22 +113,20 @@ 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` (`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 |
+| `fence-ignores-token` | guard | `FencedTxnsMatchRow` | `assertDrainLease`'s `fenceLockRow` call; `test/persistence-sync-lease.test.ts` |
+| `fold-stamp-ignores-token` | guard | `FencedTxnsMatchRow` (`DrainLeaseStamp.cfg`) | `provenStamp`'s `fenceLockRow` call (sync-pass-fold.ts); `test/drain-lease-stamp-fence.test.ts` and its Postgres twin |
+| `checkpoint-stamp-ignores-token` | guard | `FencedTxnsMatchRow` (`DrainLeaseStamp.cfg`) | `applyPassCheckpoint`'s `fenceLockRow` call (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` |
+| `fence-takes-share-lock` | guard | `NoSpuriousLapse` | `fenceLockRow` takes `FOR SHARE` again (#7442); `test/e2e/drain-lease-key-share-7442-postgres.test.ts` (a renewal commits while a fenced transaction is open) |
+| `takeover-skips-key-write` | guard | `FencedTxnsMatchRow` | both upserts in `tryAcquireDbLock` drop `SET id = EXCLUDED.id`; `test/drain-lease-key-share-7442.test.ts` (the token census) and its Postgres twin (a takeover waits for the fence) |
| `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 |
-| `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 |
+| `fence-ignores-expiry` | survivor | — | defense in depth: `FOR KEY 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
@@ -141,15 +140,6 @@ length of their transaction, so they count against the renewal timeout like a lo
### 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 tracked in #7442 for the sync lane. The model keeps `NoSpuriousLapse` as stated and names these as assumptions rather
-than weakening the property.
+None in the lease protocol at these bounds. The two gaps this model first found (#7442: fenced transactions not bounded
+under the renewal timeout, and the pass stamp's share lock overlapping the holder's) are closed by the `FOR KEY SHARE`
+fence and the key-writing takeover upsert (#7450); `DrainLease.cfg` now checks `NoSpuriousLapse` with both conditions on.
diff --git a/spec/tla/drain-lease/DrainLease.cfg b/spec/tla/drain-lease/DrainLease.cfg
index f2e533261d..5cff2d18cf 100644
--- a/spec/tla/drain-lease/DrainLease.cfg
+++ b/spec/tla/drain-lease/DrainLease.cfg
@@ -1,4 +1,4 @@
-\* Two drainers, one lane each, the code's timing at 10 s ticks.
+\* Two drainers, one lane each, the code's timing at 10 s ticks; fenced transactions up to 60 s and the pass stamp's fence on (#7442).
SPECIFICATION Spec
CHECK_DEADLOCK TRUE
CONSTANTS
@@ -10,11 +10,11 @@ CONSTANTS
RenewTimeoutMs = 30000
StealGraceMs = 60000
TakeoverGraceMs = 60000
- MaxTxMs = 20000
+ MaxTxMs = 60000
CancelMs = 10000
- RenewalWinsGap = TRUE
+ RenewalWinsGap = FALSE
UnsafeSteals = FALSE
- Stamps = FALSE
+ Stamps = TRUE
MaxTime = 18
MaxTokens = 3
MaxCursor = 2
diff --git a/spec/tla/drain-lease/DrainLease.tla b/spec/tla/drain-lease/DrainLease.tla
index 2986d7b670..32846bed55 100644
--- a/spec/tla/drain-lease/DrainLease.tla
+++ b/spec/tla/drain-lease/DrainLease.tla
@@ -18,6 +18,8 @@
(* sleeps (machine asleep, event loop blocked) owes nothing. That makes *)
(* "a live holder keeps its lease" an invariant (NoSpuriousLapse), the *)
(* property #7415 broke, conditional on the stated timing assumptions. *)
+(* The fence takes the row FOR KEY SHARE (#7442): that holds off the *)
+(* takeover upsert and DELETEs, which write the key, but not the renewal. *)
(***************************************************************************)
EXTENDS Naturals, FiniteSets, TLC
@@ -30,11 +32,11 @@ CONSTANTS
RenewTimeoutMs, \* withRefreshingLock: min(30000, ttl / 3)
StealGraceMs, \* resolveStealGraceSeconds(ttl) * 1000
TakeoverGraceMs, \* HOLDER_TAKEOVER_GRACE_MS
- MaxTxMs, \* assumption: the longest a fenced transaction stays open (FENCED_SLICE_MS plus the item that crosses it)
+ MaxTxMs, \* the longest a fenced transaction stays open; since #7442 a bound the renewal does not depend on
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
+ RenewalWinsGap, \* a waiting renewal gets the row before the holder's next fenced transaction begins (FALSE drops it)
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
+ Stamps, \* model the pass stamp's fence: a coordinator transaction that takes the row FOR KEY SHARE by a stamped token
MaxTime, MaxTokens, MaxCursor, MaxSleeps, MaxCrashes
CeilDiv(a, b) == (a + b - 1) \div b
@@ -74,11 +76,11 @@ local == <<pc, tok, aborted, deadline, nextRenew, renewAt, cancelling, txAt, txR
Closed == [l \in LaneIds |-> None]
OpenTx(p) == {l \in LaneIds : txAt[p][l] # None}
Renewing(p) == renewAt[p] # None
-\* Processes holding the lock row FOR SHARE.
+\* Processes holding the lock row FOR KEY SHARE.
Sharers == {p \in Procs : OpenTx(p) # {}}
-\* The coordinator's pass-stamp transaction holds it FOR SHARE.
+\* The coordinator's pass-stamp transaction holds it FOR KEY SHARE.
StampSharing == stampTok # None
-\* Anything holds the row FOR SHARE: an UPDATE or DELETE of the row waits.
+\* Anything holds the row FOR KEY SHARE: a DELETE, or an UPDATE that writes the key (the takeover upsert), waits.
RowShared == Sharers # {} \/ StampSharing
TypeOK ==
@@ -105,7 +107,8 @@ Reset(p) ==
(***************************************************************************)
(* tryAcquireDbLock. The upsert inserts, or takes over a row whose TTL *)
(* expired and whose last refresh is older than the steal grace; the *)
-(* takeover UPDATEs the row, so it waits for every FOR SHARE. *)
+(* takeover's upsert writes the key (SET id = EXCLUDED.id), so it waits *)
+(* for every FOR KEY SHARE. *)
(***************************************************************************)
Expired == rowExp < now
TakeoverAllowed == Expired /\ rowRef + Grace < now
@@ -125,8 +128,8 @@ Acquire(p) ==
(* tryAcquireDbLock's second path (#1780), and --break-lock's safe path: a *)
(* row that has not expired, whose same-host pid the probe calls dead and *)
(* that is older than the takeover grace, is DELETEd by pid and token *)
-(* (waiting for every FOR SHARE) and the upsert retried. An honest probe *)
-(* calls dead only a holder that is gone. *)
+(* (waiting for every FOR KEY SHARE) and the upsert retried. An honest *)
+(* probe calls dead only a holder that is gone. *)
(***************************************************************************)
RowOwnerLive == \E q \in Procs : pc[q] # "idle" /\ tok[q] = rowTok
@@ -149,10 +152,10 @@ StartRenew(p) ==
/\ UNCHANGED <<now, rowTok, rowExp, rowRef, rowAcq, cursor, nextTok, pc, tok, aborted, deadline,
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) /\ ~RowShared
+(* UPDATE ... WHERE id AND holder_pid AND acquisition_token writes no key *)
+(* column, so FOR KEY SHARE does not block it (#7442): the renewal lands *)
+(* while fenced transactions and the pass stamp hold the row. *)
+RenewCanLand(p) == pc[p] = "holding" /\ Renewing(p)
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 *)
@@ -202,16 +205,15 @@ LocalDeadline(p) ==
(***************************************************************************)
(* assertDrainLease, in each transaction that admits work or swaps the *)
(* cursor: refuse when the signal aborted, else SELECT the row WHERE token *)
-(* matches AND ttl_expires_at > now() FOR SHARE. *)
+(* matches AND ttl_expires_at > now() FOR KEY SHARE (fenceLockRow). *)
(***************************************************************************)
FenceSignal(p) == ~aborted[p]
FenceToken(p) == rowTok = tok[p]
FenceExpiry == rowExp > now
FencePasses(p) == FenceSignal(p) /\ FenceToken(p) /\ FenceExpiry
-\* 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.
+\* Under FOR SHARE (before #7442) a waiting renewal landed between serial fenced transactions but could starve under
+\* overlapping ones; RenewalWinsGap = TRUE models that queue. With FOR KEY SHARE the renewal does not wait on the fence,
+\* and DrainLease.cfg sets RenewalWinsGap = FALSE.
FenceQueue(p) == RenewalWinsGap => (~Renewing(p) \/ RowShared)
BeginFenced(p, l) ==
@@ -242,7 +244,7 @@ Rollback(p, l) ==
(***************************************************************************)
(* 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, *)
+(* stamped on the request matches AND ttl_expires_at > now() FOR KEY 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. *)
(***************************************************************************)
diff --git a/spec/tla/drain-lease/DrainLeaseStamp.cfg b/spec/tla/drain-lease/DrainLeaseStamp.cfg
index e787f76459..cc12c60a19 100644
--- a/spec/tla/drain-lease/DrainLeaseStamp.cfg
+++ b/spec/tla/drain-lease/DrainLeaseStamp.cfg
@@ -1,4 +1,4 @@
-\* The pass stamp's fence beside the holder's: a coordinator transaction that takes the row FOR SHARE by the token
+\* The pass stamp's fence beside the holder's: a coordinator transaction that takes the row FOR KEY 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
diff --git a/spec/tla/drain-lease/mutants.json b/spec/tla/drain-lease/mutants.json
index a04ca70bec..d6b2a2f573 100644
--- a/spec/tla/drain-lease/mutants.json
+++ b/spec/tla/drain-lease/mutants.json
@@ -17,8 +17,8 @@
"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"
+ "before": "fenceLockRow(tx, lease.lockId, lease.token)",
+ "after": "tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND $2::uuid IS NOT NULL AND ttl_expires_at > now() FOR KEY SHARE', [lease.lockId, lease.token])"
}
],
"tests": [
@@ -43,8 +43,8 @@
"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"
+ "before": "fenceLockRow(tx, syncLockId(row.source_id), stamp.leaseToken)",
+ "after": "tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND $2::uuid IS NOT NULL AND ttl_expires_at > now() FOR KEY SHARE', [syncLockId(row.source_id), stamp.leaseToken])"
}
],
"tests": [
@@ -75,8 +75,8 @@
"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"
+ "before": "fenceLockRow(tx, syncLockId(row.source_id), stamp.leaseToken)",
+ "after": "tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND $2::uuid IS NOT NULL AND ttl_expires_at > now() FOR KEY SHARE', [syncLockId(row.source_id), stamp.leaseToken])"
}
],
"tests": [
@@ -96,7 +96,7 @@
{
"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",
+ "title": "a folded stamp's proof reads the row without FOR KEY SHARE, so a takeover proceeds before its import commits",
"expect": "FencedTxnsMatchRow",
"config": "DrainLeaseStamp.cfg",
"spec": {
@@ -108,14 +108,14 @@
"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]"
+ "before": "fenceLockRow(tx, syncLockId(row.source_id), stamp.leaseToken)",
+ "after": "tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND 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",
+ "filter": "a folded stamp holds the lease row FOR KEY SHARE",
"postgres": true
}
]
@@ -124,7 +124,7 @@
{
"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",
+ "title": "the checkpoint request reads the row without FOR KEY SHARE, so a takeover proceeds before it commits",
"expect": "FencedTxnsMatchRow",
"config": "DrainLeaseStamp.cfg",
"spec": {
@@ -136,14 +136,14 @@
"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]"
+ "before": "fenceLockRow(tx, syncLockId(row.source_id), stamp.leaseToken)",
+ "after": "tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND 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",
+ "filter": "a checkpoint request holds the lease row FOR KEY SHARE",
"postgres": true
}
]
@@ -152,7 +152,7 @@
{
"id": "fence-without-share-lock",
"kind": "guard",
- "title": "the fence reads the row without FOR SHARE, so a takeover proceeds under an open transaction",
+ "title": "the fence reads the row without FOR KEY SHARE, so a takeover proceeds under an open transaction",
"expect": "FencedTxnsMatchRow",
"spec": {
"file": "DrainLease.tla",
@@ -163,8 +163,8 @@
"edits": [
{
"file": "src/core/persistence/sync-lease.ts",
- "before": "AND ttl_expires_at > now() FOR SHARE'",
- "after": "AND ttl_expires_at > now()'"
+ "before": "fenceLockRow(tx, lease.lockId, lease.token)",
+ "after": "tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now()', [lease.lockId, lease.token])"
}
],
"tests": [
@@ -176,6 +176,69 @@
]
}
},
+ {
+ "id": "fence-takes-share-lock",
+ "kind": "guard",
+ "title": "#7442: the fence takes the row FOR SHARE instead of FOR KEY SHARE, so the holder's renewal waits behind its own fenced transactions and the pass stamp until the lease lapses",
+ "expect": "NoSpuriousLapse",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": "RenewCanLand(p) == pc[p] = \"holding\" /\\ Renewing(p)\n",
+ "after": "RenewCanLand(p) == pc[p] = \"holding\" /\\ Renewing(p) /\\ ~RowShared\n"
+ },
+ "code": {
+ "edits": [
+ {
+ "file": "src/core/db-lock.ts",
+ "before": "ttl_expires_at > now() FOR KEY SHARE', [lockId, token]",
+ "after": "ttl_expires_at > now() FOR SHARE', [lockId, token]"
+ }
+ ],
+ "tests": [
+ {
+ "test": "test/e2e/drain-lease-key-share-7442-postgres.test.ts",
+ "filter": "a renewal commits while a fenced transaction is open",
+ "postgres": true
+ }
+ ]
+ }
+ },
+ {
+ "id": "takeover-skips-key-write",
+ "kind": "guard",
+ "title": "#7442: the takeover upsert changes the token without writing the key, so it does not wait for the fence's FOR KEY SHARE",
+ "expect": "FencedTxnsMatchRow",
+ "spec": {
+ "file": "DrainLease.tla",
+ "before": " /\\ rowTok = None \\/ (~RowShared /\\ TakeoverAllowed)",
+ "after": " /\\ rowTok = None \\/ TakeoverAllowed"
+ },
+ "code": {
+ "edits": [
+ {
+ "file": "src/core/db-lock.ts",
+ "before": " SET id = EXCLUDED.id,\n holder_pid = ${pid},",
+ "after": " SET holder_pid = ${pid},"
+ },
+ {
+ "file": "src/core/db-lock.ts",
+ "before": " SET id = EXCLUDED.id,\n holder_pid = $2,",
+ "after": " SET holder_pid = $2,"
+ }
+ ],
+ "tests": [
+ {
+ "test": "test/drain-lease-key-share-7442.test.ts",
+ "filter": "the token changes only in an ON CONFLICT upsert that also writes the key"
+ },
+ {
+ "test": "test/e2e/drain-lease-key-share-7442-postgres.test.ts",
+ "filter": "a takeover of an expired row waits for the fence",
+ "postgres": true
+ }
+ ]
+ }
+ },
{
"id": "takeover-ignores-ttl",
"kind": "guard",
@@ -226,8 +289,8 @@
"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"
+ "before": " release: async () => {\n deregister();\n await retryReadOnlyAutocommit(maybePG.sql as any, (sql: any) => sql`\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 retryReadOnlyAutocommit(maybePG.sql as any, (sql: any) => sql`\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",
@@ -274,43 +337,6 @@
]
}
},
- {
- "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": {
- "file": "DrainLease.cfg",
- "before": "MaxTxMs = 20000",
- "after": "MaxTxMs = 30000"
- },
- "code": {
- "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",
- "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",
- "before": "RenewalWinsGap = TRUE",
- "after": "RenewalWinsGap = FALSE"
- }
- },
{
"id": "renewal-ignores-token",
"kind": "guard",
@@ -347,28 +373,6 @@
]
}
},
- {
- "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": "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",
@@ -386,7 +390,7 @@
"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\").",
+ "reason": "Defense in depth: FOR KEY SHARE blocks a takeover while the transaction is open, and the token check refuses after one. test/persistence-sync-lease.test.ts still pins the refusal (\"expired untaken\").",
"spec": {
"file": "DrainLease.tla",
"before": "FenceExpiry == rowExp > now",
diff --git a/test/drain-lease-stamp-fence.test.ts b/test/drain-lease-stamp-fence.test.ts
index 2aa95104bc..f5f94899a0 100644
--- a/test/drain-lease-stamp-fence.test.ts
+++ b/test/drain-lease-stamp-fence.test.ts
@@ -1,6 +1,6 @@
/**
* 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
+ * by token `FOR KEY 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
@@ -91,7 +91,7 @@ for (const backend of testBackends()) {
return (await tx.executeRaw('DELETE FROM gbrain_cycle_locks 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 }) => {
+ test('a folded stamp holds the lease row FOR KEY 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>();
@@ -108,7 +108,7 @@ for (const backend of testBackends()) {
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 }) => {
+ test('a checkpoint request holds the lease row FOR KEY 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>();
diff --git a/test/e2e/drain-lease-fence-postgres.test.ts b/test/e2e/drain-lease-fence-postgres.test.ts
index 35a2e624fb..ad028df78c 100644
--- a/test/e2e/drain-lease-fence-postgres.test.ts
+++ b/test/e2e/drain-lease-fence-postgres.test.ts
@@ -1,5 +1,5 @@
/**
- * The drain lease's fence (assertDrainLease) holds the lock row FOR SHARE for the life of its transaction, so a takeover,
+ * The drain lease's fence (assertDrainLease) holds the lock row FOR KEY SHARE for the life of its transaction, so a takeover,
* which must UPDATE or DELETE the row, waits until the transaction ends: a pass that passed its fence cannot have its
* lease taken from under it before it commits. spec/tla/drain-lease (mutant fence-without-share-lock) depends on it.
*/
@@ -23,7 +23,7 @@ beforeAll(async () => {
}, 60_000);
afterAll(async () => { await close?.(); });
-run('the fence holds the lease row FOR SHARE, so it blocks a takeover until its transaction ends', async () => {
+run('the fence holds the lease row FOR KEY SHARE, so it blocks a takeover until its transaction ends', async () => {
const other = postgres(url, { max: 1, prepare: false });
// A takeover as --break-lock writes it (a DELETE, which conflicts with every row lock a fence can take, FOR KEY SHARE
// included), from another connection, giving up after 1 s.
diff --git a/test/spec-drain-lease-constants.test.ts b/test/spec-drain-lease-constants.test.ts
index c1ce35a972..53ae65b992 100644
--- a/test/spec-drain-lease-constants.test.ts
+++ b/test/spec-drain-lease-constants.test.ts
@@ -58,11 +58,12 @@ describe('spec/tla/drain-lease configs match the code', () => {
});
}
- test('DrainLease.cfg assumes a fenced-transaction bound the code keeps under the renewal timeout', async () => {
+ test('DrainLease.cfg checks liveness with fenced transactions that outlive the renewal timeout and the pass stamp on (#7442)', 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);
+ const c = constants('DrainLease.cfg');
+ expect({ Stamps: c.Stamps, RenewalWinsGap: c.RenewalWinsGap, UnsafeSteals: c.UnsafeSteals }).toEqual({ Stamps: 'TRUE', RenewalWinsGap: 'FALSE', UnsafeSteals: 'FALSE' });
+ expect(Number(c.MaxTxMs)).toBeGreaterThan(RenewTimeoutMs);
+ expect(FENCED_SLICE_MS).toBeLessThan(Number(c.MaxTxMs));
expect(RefreshMs + RenewTimeoutMs, 'a renewal and its timeout must fit inside the TTL').toBeLessThan(TtlMs);
});