Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): a lost or hung claim renewal no longer holds the consumer (#5373)

time-attackcf9ba90dd655
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 96496db7fe..6b4b4992f8 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -26,7 +26,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier.
+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Claims are renewed every `renewalIntervalMs` (10 s) under a `phaseMs` deadline; a renewal that reports the claim gone, fails or outlives its deadline during preparation loses the claim: on the single route the preparation is raced against that loss and aborted, on the grouped and lane route (`executeClaimedGroup` in `group-publish.ts`) any member's loss abandons the group. The still-held claims are released unpublished (`claim_lost`, token-fenced, so a competing consumer's claim is never reset), the abandoned preparation is never published, its root (or lane slot) stays held until it settles so the same root cannot overtake it, and `stop()` drains abandoned preparations and renewals before engine close. Tests: `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`.
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 70f3afcb9f..2f4c1a230a 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -69,6 +69,10 @@ export class PersistenceConsumer {
private idleLane: { conn: ReservedConnection; release: () => Promise<void> } | undefined;
private idleLaneRetryAt = 0;
private active = new Set<Promise<void>>();
+ /** #5373: preparations and renewals left running after a claim loss; stop() drains them before engine close. */
+ private abandoned = new Set<Promise<unknown>>();
+ /** #5373: per claimed head row, the abandoned preparation its root (or lane slot) waits for before release. */
+ private rootHolds = new Map<string, Promise<unknown>>();
private activeRoots = new Set<string>();
/** #5984 lanes: running lane tasks per worktree. */
private laneTasks = new Map<string, number>();
@@ -99,7 +103,7 @@ export class PersistenceConsumer {
private abandonedReleased = false;
readonly hostId: string;
constructor(readonly engine: BrainEngine, readonly config: GBrainConfig, readonly prepare: PrepareMutation,
- private opts: { hostId?: string; concurrency?: number; pollMs?: number; idleMaxMs?: number; phaseMs?: number; preparationMs?: number; onError?: (error: unknown) => void;
+ private opts: { hostId?: string; concurrency?: number; pollMs?: number; idleMaxMs?: number; phaseMs?: number; preparationMs?: number; renewalIntervalMs?: number; onError?: (error: unknown) => void;
onSettled?: (row: WriteRequest) => void;
/** Engine graduation drain: claim, recover and publish requests only; effect, projection, topology and maintenance workers never start. */
requestsOnly?: boolean } = {}) {
@@ -393,7 +397,12 @@ export class PersistenceConsumer {
const task = this.executeOrGroup(row).then(result => { progressed = result; }).catch(error => this.report(error)).finally(() => {
if (!progressed) this.rootRetryAfter.set(key, Date.now() + (this.opts.pollMs ?? 250));
else { this.progressWake = true; this.publishedSinceMaintenance++; }
- this.active.delete(task); done(); this.schedule(progressed ? 0 : this.opts.pollMs ?? 250);
+ this.active.delete(task);
+ const hold = this.rootHolds.get(row.id);
+ this.rootHolds.delete(row.id);
+ if (hold) void hold.then(() => { done(); this.schedule(0); });
+ else done();
+ this.schedule(progressed ? 0 : this.opts.pollMs ?? 250);
});
this.active.add(task);
}
@@ -486,12 +495,26 @@ export class PersistenceConsumer {
if (!this.opts.onError) process.stderr.write(`[persistence] phase=${phase} reason=${code}${detail ? ` message="${detail}"` : ''}${timing}`
+ '; unfinished work remains tracked; fix: gbrain sources writer status --json; docs: docs/ENGINES.md#persistence-consumer-log\n');
}
+ /** #5373: keep a promise that outlived its claim tracked until it settles; it never rejects into the caller. */
+ private abandon(work: Promise<unknown>, holdFor?: string): void {
+ const settled = work.then(() => undefined, () => undefined);
+ this.abandoned.add(settled);
+ void settled.then(() => this.abandoned.delete(settled));
+ if (holdFor) this.rootHolds.set(holdFor, settled);
+ }
private async execute(row: WriteRequest): Promise<boolean> {
- let renewing: Promise<unknown> | undefined;
+ let renewing: Promise<void> | undefined;
let claimLive = true;
let closed = false;
let preparationActive = true;
const abort = new AbortController();
+ const claimLost = Promise.withResolvers<void>();
+ const loseClaim = () => {
+ if (!claimLive) return;
+ claimLive = false;
+ abort.abort({ code: 'claim_lost' });
+ claimLost.resolve();
+ };
const observation = { request_id: row.request_id, started_at: new Date().toISOString(), deadline_exceeded: false, attempt: ++this.preparationAttempts };
this.preparing.set(row.id, observation);
this.executing.add(row.id);
@@ -509,14 +532,24 @@ export class PersistenceConsumer {
const interval = setInterval(() => {
if (closed || renewing) return;
const renewalAbort = new AbortController();
- const deadline = setTimeout(() => { claimLive = false; renewalAbort.abort(); }, this.opts.phaseMs ?? 5000);
- renewing = renewWriteClaim({ executeRaw: this.engine.executeRawDirect.bind(this.engine) }, row.id, row.execution_token!, 30_000,
- this.engine.kind === 'postgres' ? renewalAbort.signal : undefined).then(live => { claimLive &&= live; })
- .catch(() => { claimLive = false; }).finally(() => { clearTimeout(deadline); renewing = undefined; });
- }, 10_000);
+ const deadline = setTimeout(() => { loseClaim(); renewalAbort.abort(); }, this.opts.phaseMs ?? 5000);
+ const task: Promise<void> = renewWriteClaim({ executeRaw: this.engine.executeRawDirect.bind(this.engine) }, row.id, row.execution_token!, 30_000,
+ this.engine.kind === 'postgres' ? renewalAbort.signal : undefined).then(live => { if (!live) loseClaim(); })
+ .catch(() => { loseClaim(); }).finally(() => { clearTimeout(deadline); if (renewing === task) renewing = undefined; });
+ renewing = task;
+ }, this.opts.renewalIntervalMs ?? 10_000);
interval.unref?.();
try {
- const prepared = await this.prepare(this.engine, row, this.config, bounded ? abort.signal : undefined);
+ const preparation = this.prepare(this.engine, row, this.config, bounded ? abort.signal : undefined)
+ .then(prepared => ({ kind: 'prepared' as const, prepared }), error => ({ kind: 'error' as const, error }));
+ const outcome = await Promise.race([preparation, claimLost.promise.then(() => ({ kind: 'claim_lost' as const }))]);
+ if (outcome.kind === 'claim_lost') {
+ this.abandon(preparation, row.id);
+ await releaseUnpublishedClaim(this.engine, row, 'claim_lost');
+ return false;
+ }
+ if (outcome.kind === 'error') throw outcome.error;
+ const prepared = outcome.prepared;
if (timeout) clearTimeout(timeout);
if (bounded && performance.now() >= deadline && !abort.signal.aborted) {
observation.deadline_exceeded = true;
@@ -524,7 +557,7 @@ export class PersistenceConsumer {
this.log('preparation', 'deadline_exceeded');
}
if (!claimLive || this.stopping || abort.signal.aborted) {
- await releaseUnpublishedClaim(this.engine, row, observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping'); return false;
+ await releaseUnpublishedClaim(this.engine, row, !claimLive ? 'claim_lost' : observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping'); return false;
}
this.preparing.delete(row.id);
preparationActive = false;
@@ -538,7 +571,7 @@ export class PersistenceConsumer {
} catch (error) {
if (preparationActive && bounded && performance.now() >= deadline) observation.deadline_exceeded = true;
if (preparationActive && (abort.signal.aborted || observation.deadline_exceeded)) {
- await releaseUnpublishedClaim(this.engine, row, observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping');
+ await releaseUnpublishedClaim(this.engine, row, !claimLive ? 'claim_lost' : observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping');
return false;
}
const current = await getWriteRequestById(this.engine, row.id);
@@ -550,7 +583,8 @@ export class PersistenceConsumer {
throw error;
} finally {
closed = true; clearInterval(interval); if (timeout) clearTimeout(timeout);
- this.abort.signal.removeEventListener('abort', stop); this.preparing.delete(row.id); this.executing.delete(row.id); await renewing;
+ this.abort.signal.removeEventListener('abort', stop); this.preparing.delete(row.id); this.executing.delete(row.id);
+ if (renewing) this.abandon(renewing);
}
}
/** #5984: a claimed bulk sync head takes its directly following group members along; one row runs the single path. */
@@ -569,6 +603,7 @@ export class PersistenceConsumer {
for (const member of rows) this.executing.add(member.id);
try {
return await executeClaimedGroup(this.engine, rows, { hostId: this.hostId, lane, prepare: member => this.prepare(this.engine, member, this.config),
+ claim: { intervalMs: this.opts.renewalIntervalMs, phaseMs: this.opts.phaseMs, abandon: (work, holdRoot) => this.abandon(work, holdRoot ? row.id : undefined) },
settled: done => {
this.executing.delete(done.id);
if (done.state === 'committed' && done.worktree_id && !String(done.intent?.kind).startsWith('managed_sync_')) {
@@ -586,6 +621,7 @@ export class PersistenceConsumer {
await this.tickPromise;
await this.releaseIdleLane();
await Promise.allSettled([...this.active]);
+ while (this.abandoned.size) await Promise.allSettled([...this.abandoned]);
await this.projectionWorker;
await this.effectsWorker;
await this.topologyWorker;
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 3d972d8ee8..a599d273a4 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -312,6 +312,8 @@ export interface GroupExecution {
settled(row: WriteRequest): void;
hostId: string;
hooks?: GroupHooks;
+ /** #5373: renewal cadence and per-renewal deadline, and where a preparation left running after a claim loss is tracked. */
+ claim?: { intervalMs?: number; phaseMs?: number; abandon?: (work: Promise<unknown>, holdRoot?: boolean) => void };
}
/**
@@ -320,21 +322,44 @@ export interface GroupExecution {
* members one at a time in order. After a member ends in failure the later
* members are cancelled, and after one is released back to the queue the
* later ones are released too, so nothing overtakes it. Claims are renewed
- * for the whole group while it runs. Returns whether any member settled.
+ * for the whole group while it runs; a renewal that loses a member's claim,
+ * fails or outlives its deadline during preparation abandons the group: the
+ * still-held claims are released unpublished and the preparation is handed to
+ * `claim.abandon`, never published. Returns whether any member settled.
*/
export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequest[], run: GroupExecution): Promise<boolean> {
- let renewing: Promise<unknown> | undefined;
- const interval = setInterval(() => { renewing ??= renewGroupClaims(engine, rows).catch(() => undefined).finally(() => { renewing = undefined; }); }, 10_000);
+ let renewing: Promise<void> | undefined;
+ let preparing = true;
+ const claimLost = Promise.withResolvers<'claim_lost'>();
+ const loseClaim = () => { if (preparing) claimLost.resolve('claim_lost'); };
+ const interval = setInterval(() => {
+ if (renewing) return;
+ const renewalAbort = new AbortController();
+ const deadline = setTimeout(() => { loseClaim(); renewalAbort.abort(); }, run.claim?.phaseMs ?? 5000);
+ const task: Promise<void> = renewGroupClaims(engine, rows, 30_000, renewalAbort.signal).then(held => { if (held.size < rows.length) loseClaim(); })
+ .catch(loseClaim).finally(() => { clearTimeout(deadline); if (renewing === task) renewing = undefined; });
+ renewing = task;
+ }, run.claim?.intervalMs ?? 10_000);
interval.unref?.();
if (run.lane) laneClaimed(run.lane, rows);
try {
const prepared: Array<{ ok: PreparedMutation } | { error: unknown }> = new Array(rows.length);
// A put_pages group prepares all of its (at most PAGE_BATCH_GROUP_MAX) pages at once.
const width = publicationGroupKey(rows[0]!)?.startsWith('batch:') ? PAGE_BATCH_GROUP_MAX : 4;
- for (let start = 0; start < rows.length; start += width) {
- await Promise.all(rows.slice(start, start + width).map(async (row, offset) => {
- try { prepared[start + offset] = { ok: await run.prepare(row) }; } catch (error) { prepared[start + offset] = { error }; }
- }));
+ const preparation = (async () => {
+ for (let start = 0; start < rows.length; start += width) {
+ await Promise.all(rows.slice(start, start + width).map(async (row, offset) => {
+ try { prepared[start + offset] = { ok: await run.prepare(row) }; } catch (error) { prepared[start + offset] = { error }; }
+ }));
+ }
+ return 'prepared' as const;
+ })();
+ const outcome = await Promise.race([preparation, claimLost.promise]);
+ preparing = false;
+ if (outcome === 'claim_lost') {
+ run.claim?.abandon?.(preparation, true);
+ for (const row of rows) await releaseUnpublishedClaim(engine, row, 'claim_lost');
+ return false;
}
// A put_pages batch is independent page writes: one page's failure never cancels its siblings.
const independent = publicationGroupKey(rows[0]!)?.startsWith('batch:') === true;
@@ -378,6 +403,6 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
} finally {
if (run.lane) laneFinished(run.lane, rows);
clearInterval(interval);
- await renewing;
+ if (renewing) run.claim?.abandon?.(renewing);
}
}
diff --git a/test/e2e/persistence-consumer-claim-loss.test.ts b/test/e2e/persistence-consumer-claim-loss.test.ts
new file mode 100644
index 0000000000..86d9ea6143
--- /dev/null
+++ b/test/e2e/persistence-consumer-claim-loss.test.ts
@@ -0,0 +1,176 @@
+/**
+ * #5373 on Postgres: a consumer that loses its claim during preparation lets
+ * go. Protects: claim lifetime and scheduling in the durable write path for
+ * the single route and the grouped (put_pages batch) route. Fails when: a lost
+ * claim keeps the consumer slot until an unbounded preparation finishes, a
+ * hung renewal blocks the task forever, the release resets a competing
+ * consumer's claim, or the abandoned preparation publishes after the loss.
+ * The renewal cadence is the committed `renewalIntervalMs` seam; takeover is
+ * modelled the way a competing consumer claims an expired lease (a new
+ * execution token on the row), and the hung renewal is a real row lock.
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import postgres from '#postgres';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { PersistenceConsumer } from '../../src/core/persistence/consumer.ts';
+import { admitWrite, getWriteRequestById } from '../../src/core/persistence/journal.ts';
+import { publishMutation, type PreparedMutation } from '../../src/core/persistence/coordinator.ts';
+import type { WriteRequest } from '../../src/core/persistence/model.ts';
+import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, type FixtureSource, type HarnessConfig } from '../../scripts/persistence/harness.ts';
+import { assertSafeE2eDatabaseUrl, hasDatabase } from './helpers.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { waitFor } from '../helpers/wait-for.ts';
+
+const DATABASE_URL = process.env.DATABASE_URL ?? '';
+
+async function withBrain(run: (ctx: { engine: PostgresEngine; config: HarnessConfig; sources: FixtureSource[]; url: string }) => Promise<void>) {
+ assertSafeE2eDatabaseUrl(DATABASE_URL);
+ const name = `gbrain_test_claim_loss_${randomUUID().replaceAll('-', '')}`;
+ const admin = postgres(DATABASE_URL, { max: 1, prepare: false, onnotice: () => {} });
+ await admin.unsafe(`CREATE DATABASE ${name}`);
+ const url = new URL(DATABASE_URL); url.pathname = `/${name}`;
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-claim-loss-'));
+ const config: HarnessConfig = { kind: 'postgres', root, dataDir: join(root, 'unused'), hostId: randomUUID(),
+ seed: 5373, schedules: 0, operations: 0, sourceIds: ['claim-loss', 'claim-loss-other'], principalIds: [randomUUID()] };
+ const engine = new PostgresEngine();
+ try {
+ await withEnv({ GBRAIN_HOME: root, GBRAIN_PERSISTENCE_FIXTURE_HOME: root }, async () => {
+ await engine.connect({ database_url: url.toString(), poolSize: 6 });
+ await engine.initSchema();
+ selectFixtureHost(config.hostId);
+ await initializeFixtures(engine, config);
+ await run({ engine, config, sources: await fixtures(engine, config), url: url.toString() });
+ });
+ } finally {
+ await engine.disconnect();
+ try { await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); } finally { await admin.end(); }
+ rmSync(root, { recursive: true, force: true });
+ }
+}
+
+const activeRoots = (consumer: PersistenceConsumer) => (consumer as unknown as { activeRoots: Set<string> }).activeRoots;
+const pageExists = async (engine: PostgresEngine, slug: string) =>
+ (await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1', [slug])).length > 0;
+
+describe.skipIf(!hasDatabase())('persistence consumer claim loss (Postgres)', () => {
+ test('competing takeover: the slot frees, the root waits, the takeover commits and the late preparation never publishes', () => withBrain(async ({ engine, config, sources }) => {
+ const first = await admitWrite(engine, admission(config, sources[0]!, 'claim-loss/first', 'first body'));
+ const other = await admitWrite(engine, admission(config, sources[1]!, 'claim-loss/other', 'other body'));
+ const late = Promise.withResolvers<PreparedMutation>();
+ const started: string[] = [];
+ const errors: unknown[] = [];
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async (_engine, row) => {
+ started.push(row.id);
+ return row.id === first.id ? late.promise : prepared(row, sources);
+ }, { hostId: config.hostId, concurrency: 1, pollMs: 60_000, renewalIntervalMs: 20, phaseMs: 2_000, onError: error => errors.push(error) });
+ try {
+ consumer.start();
+ await waitFor(() => started[0] === first.id, { timeoutMs: 10_000 });
+ const takeover = randomUUID();
+ await engine.executeRaw(`UPDATE persistence_requests SET execution_token=$2::uuid, claim_expires_at=now()+interval '30 seconds' WHERE id=$1::uuid`, [first.id, takeover]);
+ await waitFor(() => consumer.status().active_preparations === 0, { timeoutMs: 10_000, label: 'the lost claim frees the consumer slot' });
+ const held = await getWriteRequestById(engine, first.id);
+ expect({ state: held?.state, token: held?.execution_token }).toEqual({ state: 'running', token: takeover });
+ expect(activeRoots(consumer).has(first.worktree_id!)).toBe(true);
+
+ (consumer as unknown as { rootRetryAfter: Map<string, number> }).rootRetryAfter.set(first.worktree_id!, Date.now() + 60_000);
+ await consumer.tick();
+ await waitFor(async () => (await getWriteRequestById(engine, other.id))?.state === 'committed', { timeoutMs: 10_000, label: 'an unrelated root progresses' });
+
+ const committed = await publishMutation(engine, held!, prepared({ ...held!, intent: { ...held!.intent, content: 'takeover body' } }, sources), config.hostId);
+ expect(committed.state).toBe('committed');
+ late.resolve(prepared(first, sources));
+ await waitFor(() => !activeRoots(consumer).has(first.worktree_id!), { timeoutMs: 10_000, label: 'the root is released once the abandoned preparation settles' });
+ await consumer.stop();
+ expect((await getWriteRequestById(engine, first.id))?.state).toBe('committed');
+ const [page] = await engine.executeRaw<{ compiled_truth: string }>(`SELECT compiled_truth FROM pages WHERE slug='claim-loss/first'`);
+ expect(page?.compiled_truth).toBe('takeover body');
+ expect(errors).toEqual([]);
+ } finally {
+ late.resolve(prepared(first, sources));
+ await consumer.stop();
+ }
+ }), 90_000);
+
+ test('a renewal blocked by a row lock times out under its deadline, releases the claim and stop() drains it', () => withBrain(async ({ engine, config, sources, url }) => {
+ const row = await admitWrite(engine, admission(config, sources[0]!, 'claim-loss/locked', 'locked body'));
+ const late = Promise.withResolvers<PreparedMutation>();
+ let preparing = false;
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async () => { preparing = true; return late.promise; },
+ { hostId: config.hostId, concurrency: 1, pollMs: 60_000, renewalIntervalMs: 20, phaseMs: 300, onError: () => {} });
+ const locker = postgres(url, { max: 1, prepare: false, onnotice: () => {} });
+ const lockHeld = Promise.withResolvers<void>();
+ const unlock = Promise.withResolvers<void>();
+ let lockTx: Promise<unknown> | undefined;
+ try {
+ consumer.start();
+ await waitFor(() => preparing, { timeoutMs: 10_000 });
+ lockTx = locker.begin(async tx => {
+ await tx`SELECT id FROM persistence_requests WHERE id=${row.id}::uuid FOR UPDATE`;
+ lockHeld.resolve();
+ await unlock.promise;
+ });
+ await lockHeld.promise;
+ const waiting = (needle: string) => engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pg_stat_activity
+ WHERE datname = current_database() AND wait_event_type = 'Lock' AND query LIKE $1`, [`%${needle}%`]).then(([r]) => r!.n);
+ await waitFor(async () => await waiting(`SET state='queued'`) === 1, { timeoutMs: 10_000, label: 'the hung renewal loses the claim within its deadline and the release is next' });
+ expect(await waiting('claim_expires_at=now()+')).toBe(0);
+ unlock.resolve();
+ await lockTx;
+ await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'queued', { timeoutMs: 10_000, label: 'the unpublished claim is released' });
+ expect((await getWriteRequestById(engine, row.id))?.blocked_reason).toBe('claim_lost');
+ let stopped = false;
+ const stopping = consumer.stop().then(() => { stopped = true; });
+ await Bun.sleep(100);
+ expect(stopped).toBe(false);
+ late.resolve(prepared(row, sources));
+ await stopping;
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');
+ expect(await pageExists(engine, 'claim-loss/locked')).toBe(false);
+ } finally {
+ unlock.resolve();
+ await lockTx?.catch(() => {});
+ late.resolve(prepared(row, sources));
+ await consumer.stop();
+ await locker.end();
+ }
+ }), 90_000);
+
+ test('grouped route: a member taken over during preparation abandons the group; nothing publishes and only our claims are released', () => withBrain(async ({ engine, config, sources }) => {
+ const batch = randomUUID();
+ const rows: WriteRequest[] = [];
+ for (let i = 0; i < 3; i++) {
+ rows.push(await admitWrite(engine, admission(config, sources[0]!, `claim-loss/batch-${i}`, `batch body ${i}`, 0,
+ { intent: { content: `batch body ${i}`, page_batch: { id: batch, index: i, size: 3 } }, callerIntent: { content: `batch body ${i}` } })));
+ }
+ const late = Promise.withResolvers<PreparedMutation>();
+ const started: string[] = [];
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async (_engine, row) => {
+ started.push(row.id);
+ return row.id === rows[0]!.id ? late.promise : prepared(row, sources);
+ }, { hostId: config.hostId, concurrency: 1, pollMs: 60_000, renewalIntervalMs: 20, phaseMs: 2_000, onError: () => {} });
+ try {
+ consumer.start();
+ await waitFor(() => started.length === 3, { timeoutMs: 10_000, label: 'the batch is claimed as one group' });
+ const takeover = randomUUID();
+ await engine.executeRaw(`UPDATE persistence_requests SET execution_token=$2::uuid WHERE id=$1::uuid`, [rows[1]!.id, takeover]);
+ await waitFor(() => consumer.status().active_preparations === 0 && (consumer as unknown as { active: Set<unknown> }).active.size === 0,
+ { timeoutMs: 10_000, label: 'the group task ends after the member claim is lost' });
+ const states = await Promise.all(rows.map(row => getWriteRequestById(engine, row.id)));
+ expect(states.map(row => [row?.state, row?.blocked_reason ?? null])).toEqual([['queued', 'claim_lost'], ['running', null], ['queued', 'claim_lost']]);
+ expect(states[1]?.execution_token).toBe(takeover);
+ expect(activeRoots(consumer).has(rows[0]!.worktree_id!)).toBe(true);
+ late.resolve(prepared(rows[0]!, sources));
+ await waitFor(() => !activeRoots(consumer).has(rows[0]!.worktree_id!), { timeoutMs: 10_000 });
+ await consumer.stop();
+ for (let i = 0; i < 3; i++) expect(await pageExists(engine, `claim-loss/batch-${i}`)).toBe(false);
+ } finally {
+ late.resolve(prepared(rows[0]!, sources));
+ await consumer.stop();
+ }
+ }), 90_000);
+});
diff --git a/test/persistence-consumer-scheduling.test.ts b/test/persistence-consumer-scheduling.test.ts
index 96a1de7968..ff88b7b26d 100644
--- a/test/persistence-consumer-scheduling.test.ts
+++ b/test/persistence-consumer-scheduling.test.ts
@@ -534,6 +534,91 @@ test('a retryable root becomes eligible again after its backoff expires', async
}
}), 15_000);
+test('a hung claim renewal abandons pending preparation and frees the consumer slot', async () => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const first = await admitWrite(engine, admission(config, sources[0], 'renew-hang-first', 'first body'));
+ const second = await admitWrite(engine, admission(config, sources[1], 'renew-hang-second', 'second body'));
+ const preparation = Promise.withResolvers<ReturnType<typeof prepared>>();
+ const renewal = Promise.withResolvers<Record<string, never>[]>();
+ const started: string[] = [];
+ const errors: unknown[] = [];
+ const originalDirect = engine.executeRawDirect.bind(engine);
+ (engine as unknown as { executeRawDirect: unknown }).executeRawDirect = (sql: string, params?: unknown[]) => {
+ if (sql.includes('claim_expires_at=now()+') && params?.[0] === first.id) return renewal.promise;
+ return originalDirect(sql, params);
+ };
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_engine, row) => {
+ started.push(row.id);
+ if (row.id === first.id) return preparation.promise;
+ return prepared(row, sources);
+ }, { hostId: config.hostId, concurrency: 1, pollMs: 60_000, renewalIntervalMs: 5,
+ phaseMs: 30, onError: error => errors.push(error) });
+ try {
+ consumer.start();
+ await waitFor(() => started[0] === first.id, { timeoutMs: 5_000 });
+ await waitFor(async () => (await getWriteRequestById(engine, first.id))?.state === 'queued',
+ { timeoutMs: 5_000, label: 'timed-out renewal should release the pending request' });
+ await waitFor(() => consumer.status().active_preparations === 0, { timeoutMs: 5_000 });
+ expect(consumer.status().active_preparations).toBe(0);
+ expect((await getWriteRequestById(engine, first.id))?.state).toBe('queued');
+ // The abandoned preparation still runs, so its root stays busy: the next
+ // request on that worktree must not start preparing alongside it.
+ expect((consumer as unknown as { activeRoots: Set<string> }).activeRoots.has(first.worktree_id!)).toBe(true);
+ // Keep the released root in its retry backoff while advancing the consumer
+ // once to prove the other root can use the freed slot.
+ (consumer as unknown as { rootRetryAfter: Map<string, number> }).rootRetryAfter.set(first.worktree_id!, Date.now() + 60_000);
+ await consumer.tick();
+ await waitFor(async () => (await getWriteRequestById(engine, second.id))?.state === 'committed',
+ { timeoutMs: 5_000, label: 'the next independent root should use the freed slot' });
+ expect(started).toEqual([first.id, second.id]);
+ // stop() is the engine-close barrier: it must still drain the abandoned
+ // preparation and the hung renewal query before resolving.
+ let stopped = false;
+ const stopping = consumer.stop().then(() => { stopped = true; });
+ await Bun.sleep(50);
+ expect(stopped).toBe(false);
+ preparation.resolve(prepared(first, sources));
+ renewal.resolve([]);
+ await stopping;
+ expect(stopped).toBe(true);
+ expect((await getWriteRequestById(engine, first.id))?.state).toBe('queued');
+ await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, second.id))!);
+ await assertConservation(engine);
+ expect(errors).toEqual([]);
+ } finally {
+ preparation.resolve(prepared(first, sources));
+ renewal.resolve([]);
+ await consumer.stop();
+ (engine as unknown as { executeRawDirect: unknown }).executeRawDirect = originalDirect;
+ for (const row of [first, second]) await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);
+ }
+}), 15_000);
+
+test('ordinary claims still renew and commit while preparation continues', async () => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], 'renew-healthy', 'body'));
+ const originalDirect = engine.executeRawDirect.bind(engine);
+ let renewals = 0;
+ (engine as unknown as { executeRawDirect: unknown }).executeRawDirect = (sql: string, params?: unknown[]) => {
+ if (sql.includes('claim_expires_at=now()+')) renewals++;
+ return originalDirect(sql, params);
+ };
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_engine, current) => {
+ await Bun.sleep(30);
+ return prepared(current, sources);
+ }, { hostId: config.hostId, pollMs: 60_000, renewalIntervalMs: 5, phaseMs: 500 });
+ try {
+ consumer.start();
+ await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed', { timeoutMs: 5_000 });
+ expect(renewals).toBeGreaterThan(0);
+ await assertCommittedSnapshot(engine, (await getWriteRequestById(engine, row.id))!);
+ await assertConservation(engine);
+ } finally {
+ await consumer.stop();
+ (engine as unknown as { executeRawDirect: unknown }).executeRawDirect = originalDirect;
+ await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);
+ }
+}), 15_000);
test('a local waiter wakes an idle owner for a claim-only tick instead of waiting for the next poll', async () => withEnv(env, async () => {
const ticks: boolean[] = [];
const consumer = startPersistenceConsumer(engine, { engine: 'pglite' });