Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: the drain-lease fence takes FOR KEY SHARE so the renewal passes it; the takeover upsert writes the key and still waits (#7442)
garrytanfd5ee561441c
diff --git a/src/core/db-lock.ts b/src/core/db-lock.tsindex 9b86c3bb5e..fa664f5ed6 100644--- a/src/core/db-lock.ts+++ b/src/core/db-lock.ts@@ -214,6 +214,17 @@ export function isLockHolderLive(snap: LockSnapshot, ttlMinutes: number = DEFAUL* `CONNECTION_ENDED`, which turned a finished sync into a thrown error and left* its lock row behind until the TTL lapsed.*/+/**+ * #7442: the fence on a lock row: the row with this token, unexpired, `FOR KEY SHARE`. KEY SHARE lets the holder's own+ * renewal (an UPDATE of non-key columns) through while a fenced transaction is open, so fenced transactions, however long+ * or overlapping, can no longer starve it and lapse a live lease. A takeover still waits for the fence: its upsert also+ * writes the key (`id = EXCLUDED.id` in `tryAcquireDbLock`), which takes the row lock KEY SHARE conflicts with, as every+ * DELETE (release, break-lock) does. Returns the row when the fence holds, none when the lease is gone.+ */+export function fenceLockRow(tx: Pick<BrainEngine, 'executeRaw'>, lockId: string, token: string): Promise<unknown[]> {+ return tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR KEY SHARE', [lockId, token]);+}+export async function tryAcquireDbLock(engine: BrainEngine,lockId: string,@@ -255,7 +266,8 @@ export async function tryAcquireDbLock(INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token)VALUES (${lockId}, ${pid}, ${host}, NOW(), NOW() + ${ttl}::interval, NOW(), ${acquisitionToken}::uuid)ON CONFLICT (id) DO UPDATE- SET holder_pid = ${pid},+ SET id = EXCLUDED.id,+ holder_pid = ${pid},holder_host = ${host},acquired_at = NOW(),acquisition_token = ${acquisitionToken}::uuid,@@ -315,7 +327,8 @@ export async function tryAcquireDbLock(`INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token)VALUES ($1, $2, $3, NOW(), NOW() + $4::interval, NOW(), $6::uuid)ON CONFLICT (id) DO UPDATE- SET holder_pid = $2,+ SET id = EXCLUDED.id,+ holder_pid = $2,holder_host = $3,acquired_at = NOW(),acquisition_token = $6::uuid,diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.tsindex 0c93c7186a..036e6d95ec 100644--- a/src/core/persistence/sync-lease.ts+++ b/src/core/persistence/sync-lease.ts@@ -11,9 +11,10 @@* - **Takeover.** `tryAcquireDbLock`'s rules, the same as `--break-lock`'s safe path: a TTL that expired with no* heartbeat inside the steal grace, or a same-host holder whose pid is provably dead and whose lease is older than* `HOLDER_TAKEOVER_GRACE_MS`.- * - **Fencing.** `assertDrainLease` reads the lock row with this pass's token `FOR SHARE` inside every transaction- * that admits sync work or swaps the cursor, so a pass that lost the lease admits nothing and advances no- * checkpoint: the row is gone or carries another token, and a takeover waits for the share lock.+ * - **Fencing.** `assertDrainLease` reads the lock row with this pass's token (`fenceLockRow`, `FOR KEY SHARE`) inside every+ * transaction that admits sync work or swaps the cursor, so a pass that lost the lease admits nothing and advances no+ * checkpoint: the row is gone or carries another token, and a takeover waits for the fence. The lease's own renewal+ * does not (#7442), so no fenced transaction, however long or overlapping, can lapse a live lease.* - **Cancellation.** The caller's signal aborts the pass; the lease is released in `withRefreshingLock`'s finally.* - **Reentrancy.** A pass inside a lease (the drain's passes, staged stages, a company catch-up) runs under it. A CLI* run hands itself to a serve before it takes the lease (`maybeDelegateManagedSyncToServe` runs first), so the serve's@@ -35,7 +36,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';import type { BrainEngine } from '../engine.ts';import type { SyncResult } from '../../commands/sync.ts';import type { Action } from '../agent-output.ts';-import { inspectLock, LockStolenError, LockUnavailableError, syncLockId, withRefreshingLock } from '../db-lock.ts';+import { fenceLockRow, inspectLock, LockStolenError, LockUnavailableError, syncLockId, withRefreshingLock } from '../db-lock.ts';import { currentRunDeadline, lastForwardProgressAt, noteForwardProgress } from '../forward-progress.ts';import { faultPoint } from './fault-points.ts';import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';@@ -89,18 +90,18 @@ export async function assertDrainLease(tx: Pick<BrainEngine, 'executeRaw'>, sourif (!lease) return;// A renewal that failed aborts the lease's signal before its row is released; an expired row is lost even untaken.if (lease.signal.aborted) throw new LockStolenError(lease.lockId, `the drain lease of source ${sourceId} lapsed in this pass`);- const rows = await tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE', [lease.lockId, lease.token]);+ const rows = await fenceLockRow(tx, lease.lockId, lease.token);if (!rows.length) throw new LockStolenError(lease.lockId, `the drain lease of source ${sourceId} is no longer held by this pass`);}-/** GBRA-133: the longest a transaction holding the fence stays open (plus the item that crosses it); a renewal times out after 30 s. */+/** GBRA-133: the longest a transaction holding the fence stays open (plus the item that crosses it); a takeover or release waits for it. */export const FENCED_SLICE_MS = 5_000;/*** GBRA-133: `write` for each item in fenced transactions of at most `FENCED_SLICE_MS`. The fence holds the lock row- * `FOR SHARE`, which blocks this lease's own renewal and release until the transaction ends: one transaction that wrote a- * round's holds at 65 ms per round trip stayed open for 14 minutes, every renewal timed out and the lease lapsed under the- * pass. Each slice is fenced again, so a lapsed lease stops the writes at the next slice. `committed` sees each slice once it commits.+ * until the transaction ends, so the lease's release and any takeover wait for it: one transaction that wrote a round's holds+ * at 65 ms per round trip stayed open for 14 minutes (when the fence was `FOR SHARE` it also blocked every renewal and lapsed+ * the lease, #7442). Each slice is fenced again, so a lapsed lease stops the writes at the next slice. `committed` sees each slice once it commits.*/export async function inFencedSlices<T>(engine: BrainEngine, sourceId: string, items: readonly T[],write: (tx: BrainEngine, item: T) => Promise<void>, committed?: (slice: readonly T[]) => void): Promise<void> {diff --git a/src/core/persistence/sync-pass-fold.ts b/src/core/persistence/sync-pass-fold.tsindex 777c4f2909..9dc9afd4f8 100644--- a/src/core/persistence/sync-pass-fold.ts+++ b/src/core/persistence/sync-pass-fold.ts@@ -33,7 +33,7 @@ import { fileContentHash } from './large-file.ts';import { readBlobBytes, readTreeBlobs } from './sync-blobs.ts';import type { PreparedMutation } from './coordinator.ts';import type { WriteRequest } from './model.ts';-import { syncLockId } from '../db-lock.ts';+import { fenceLockRow, syncLockId } from '../db-lock.ts';import { pipelined } from '../page-state/transactions.ts';import { findOpenPassWork } from './checkpoint-validation.ts';import { countsMatch, proveConfirm, type LevelMark } from './sync-pass-confirm.ts';@@ -141,7 +141,7 @@ async function provenStamp(tx: BrainEngine, { row, p, root }: { row: WriteRequesconst scope = { worktreeId: row.worktree_id!, sourceId: row.source_id, incarnation: row.source_incarnation };await faultPoint('sync:pass_fold', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id });const [lease, pass, blocker, watermark, sources, proof, refused] = await pipelined(tx, [- () => tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE', [syncLockId(row.source_id), stamp.leaseToken]),+ () => fenceLockRow(tx, syncLockId(row.source_id), stamp.leaseToken),() => readPassRow(tx, row.source_id, stamp.incarnation),() => findOpenPassWork(tx, row.worktree_id!, row.request_id, !!writeback),() => readConvergedWatermark(tx, scope, row.request_id, OPEN_AT_STAMP_CAP, writeback ? { own: writeback } : undefined),diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 68c5ae768d..644c9fdb4e 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -52,7 +52,7 @@ import { checkpointCursorReplaced } from './sync-checkpoint-replaced.ts';import { recordPassTail, recordSyncTail } from './sync-tail-record.ts';import { readPassRow, writePassRow, OPEN_AT_STAMP_CAP, type ManagedSyncPassValue } from './sync-pass-row.ts';import { admissionAllows, readSyncAdmission } from './sync-admission.ts';-import { syncLockId } from '../db-lock.ts';+import { fenceLockRow, syncLockId } from '../db-lock.ts';import { readConvergedWatermark } from './sync-pass-batch.ts';import { foldPassCheckpoint, type PassFold } from './sync-pass-fold.ts';import { frontmatterSlugConflictMessage } from './verb-errors.ts';@@ -503,7 +503,7 @@ export const PASS_LEASE_LOST_MESSAGE = 'The sync pass that admitted this checkpo/*** #6712 PR 4b (design v3.2 §3.3; v3 §3.3): a converged pass's stamp. Clause 1: the drain lease that admitted it is live- * (`FOR SHARE` on the lock row with the pass's token) and the pass row still names this pass. Clause 2: no recovery row and no+ * (`fenceLockRow`: `FOR KEY SHARE` on the lock row with the pass's token) and the pass row still names this pass. Clause 2: no recovery row and no* other open managed-sync request of the worktree (`findOpenPassWork`). Then, at the configured selection only,* `last_commit`, `last_sync_at` and the slug-root pin under `WHERE id AND incarnation` (and `chunker_version`); the tail* obligation, hold release, the retry compare-and-delete, and the pass row's converged state (`request_hwm`,@@ -511,7 +511,7 @@ export const PASS_LEASE_LOST_MESSAGE = 'The sync pass that admitted this checkpo*/async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string, releaseHold: (tx: BrainEngine, path: string | null) => Promise<void>): Promise<Record<string, unknown>> {const stamp = p.stamp!;- const lease = await tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE', [syncLockId(row.source_id), stamp.leaseToken]);+ const lease = await fenceLockRow(tx, syncLockId(row.source_id), stamp.leaseToken);const pass = lease.length ? await readPassRow(tx, row.source_id, stamp.incarnation) : null;if (!pass || pass.value.lease_token !== stamp.leaseToken || pass.value.telemetry.pass_id !== p.passId) throw syncPublicationRefusal('revision_conflict', PASS_LEASE_LOST_MESSAGE, row, p,`The pass that admitted checkpoint ${row.request_id} of ${row.source_id} lost the source's drain lease, or another pass started since, so nothing was stamped.`);diff --git a/test/drain-lease-key-share-7442.test.ts b/test/drain-lease-key-share-7442.test.tsnew file mode 100644index 0000000000..0018111dfc--- /dev/null+++ b/test/drain-lease-key-share-7442.test.ts@@ -0,0 +1,103 @@+/**+ * #7442 (found by GBRA-181's TLA+ model of the drain lease): the fence held the lease row `FOR SHARE`, which also blocks the+ * holder's own renewal (an UPDATE), and Postgres grants a new `FOR SHARE` beside held ones even while that UPDATE waits. So+ * fenced transactions longer than the 30 s renewal timeout, or overlapping ones (the coordinator's stamp checks beside the+ * pass's own), could keep the row share-locked across every renewal until a live holder's lease lapsed. The fence+ * (`fenceLockRow`) now takes `FOR KEY SHARE`, which a renewal passes; the takeover upsert also writes the key+ * (`id = EXCLUDED.id`), so it still waits for the fence, and a transaction fenced before a takeover keeps its token.+ *+ * PGLite (one connection) checks the fence's verdicts; Postgres also checks the lock conflicts, here and through+ * test/e2e/drain-lease-key-share-7442-postgres.test.ts.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { setTimeout as delay } from 'node:timers/promises';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { fenceLockRow, tryAcquireDbLock } from '../src/core/db-lock.ts';+import { testBackends, type TestBackend } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const engines: Array<{ backend: TestBackend; engine: BrainEngine; close: () => Promise<void> }> = [];+const ID = 'test-7442-drain';+const BLOCKED = 'still waiting';++function deferred() { let resolve!: () => void; const promise = new Promise<void>(r => { resolve = r; }); return { promise, resolve }; }+const within = <T>(work: Promise<T>, ms: number) => Promise.race([work, delay(ms).then(() => BLOCKED as typeof BLOCKED)]);+const tokenOf = async (engine: BrainEngine) => (await engine.executeRaw<{ token: string }>('SELECT acquisition_token::text AS token FROM gbrain_cycle_locks WHERE id=$1', [ID]))[0]?.token ?? null;++beforeAll(async () => {+ for (const backend of testBackends()) {+ if (backend === 'pglite') {+ const engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+ engines.push({ backend, engine, close: () => engine.disconnect() });+ } else {+ engines.push({ backend, ...await isolatedPersistencePostgres(process.env.DATABASE_URL!) });+ }+ }+}, 120_000);++afterAll(async () => { for (const e of engines) await e.close(); });+beforeEach(async () => { for (const { engine } of engines) await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [ID]); });++/** Opens a transaction that takes the fence with `token` and stays open until `release` resolves; `entered` once fenced. */+function fencedTransaction(engine: BrainEngine, token: string) {+ const entered = deferred(), release = deferred();+ let fenced: unknown[] = [], tokenInside: string | null = null;+ const done = engine.transaction(async tx => {+ fenced = await fenceLockRow(tx, ID, token);+ entered.resolve();+ await release.promise;+ tokenInside = (await tx.executeRaw<{ token: string }>('SELECT acquisition_token::text AS token FROM gbrain_cycle_locks WHERE id=$1', [ID]))[0]?.token ?? null;+ });+ return { entered: entered.promise, release: release.resolve, done, fenced: () => fenced, tokenInside: () => tokenInside };+}++describe('#7442: the drain-lease fence lets the renewal through and still holds off a takeover', () => {+ test('the fence holds for the live token only: not another token, not an expired row', async () => {+ for (const { engine } of engines) {+ const handle = (await tryAcquireDbLock(engine, ID, 2))!;+ expect(await fenceLockRow(engine, ID, handle.acquisitionToken)).toHaveLength(1);+ expect(await fenceLockRow(engine, ID, crypto.randomUUID())).toHaveLength(0);+ await engine.executeRaw("UPDATE gbrain_cycle_locks SET ttl_expires_at = now() - interval '1 second' WHERE id=$1", [ID]);+ expect(await fenceLockRow(engine, ID, handle.acquisitionToken)).toHaveLength(0);+ await handle.release();+ }+ }, 60_000);++ test('a renewal commits while a fenced transaction is open (Postgres)', async () => {+ for (const { backend, engine } of engines) {+ if (backend !== 'postgres') continue;+ const handle = (await tryAcquireDbLock(engine, ID, 2))!;+ const open = fencedTransaction(engine, handle.acquisitionToken);+ await open.entered;+ expect(open.fenced()).toHaveLength(1);+ try {+ expect(await within(handle.refresh(), 5_000)).toBe(true);+ } finally { open.release(); await open.done; }+ await handle.release();+ }+ }, 60_000);++ test('a takeover of an expired row waits for the fence, the fenced transaction keeps its token, and the old token is then refused (Postgres)', async () => {+ for (const { backend, engine } of engines) {+ if (backend !== 'postgres') continue;+ const handle = (await tryAcquireDbLock(engine, ID, 2))!;+ const open = fencedTransaction(engine, handle.acquisitionToken);+ await open.entered;+ await engine.executeRaw("UPDATE gbrain_cycle_locks SET ttl_expires_at = now() - interval '1 minute', last_refreshed_at = now() - interval '1 hour' WHERE id=$1", [ID]);+ const takeover = tryAcquireDbLock(engine, ID, 2);+ let successor;+ try {+ expect(await within(takeover, 2_000)).toBe(BLOCKED);+ } finally { open.release(); await open.done; successor = await takeover; }+ expect(open.tokenInside()).toBe(handle.acquisitionToken);+ expect(successor).not.toBeNull();+ expect(await tokenOf(engine)).toBe(successor!.acquisitionToken);+ expect(await fenceLockRow(engine, ID, handle.acquisitionToken)).toHaveLength(0);+ expect(await handle.refresh()).toBe(false);+ await successor!.release();+ }+ }, 60_000);+});diff --git a/test/e2e/drain-lease-key-share-7442-postgres.test.ts b/test/e2e/drain-lease-key-share-7442-postgres.test.tsnew file mode 100644index 0000000000..4d98f233a5--- /dev/null+++ b/test/e2e/drain-lease-key-share-7442-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../drain-lease-key-share-7442.test.ts'));