Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): a lock-blocked preparation read ends at the budget on the server, not at the ceiling (#6278 plan 1.4)

garrytan9c308da1d3a0
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 60788bac0d..3a166351df 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -2554,11 +2554,21 @@ export interface BrainEngine {
* by then get cancelled (Postgres: query.cancel(); PGLite: in-process,
* Promise.race against signal-rejection — documented gap because PGLite
* has no kernel-level cancellation).
+ *
+ * #6278: `opts.timeoutMs` runs an autocommit statement under a
+ * transaction-local `statement_timeout` of that many milliseconds (Postgres:
+ * a reserved connection runs `BEGIN; SET LOCAL statement_timeout`, the
+ * statement and `COMMIT` as one pipelined round trip, so the bound holds
+ * through a transaction-mode pooler that drops the session's startup
+ * parameters; a statement past it fails with SQLSTATE 57014). Inside a
+ * transaction the option is ignored (a `SET LOCAL` there would change the
+ * enclosing transaction). PGLite ignores it: one in-process connection has
+ * no other session to wait on.
*/
executeRaw<T = Record<string, unknown>>(
sql: string,
params?: unknown[],
- opts?: { signal?: AbortSignal },
+ opts?: { signal?: AbortSignal; timeoutMs?: number },
): Promise<T[]>;
/**
diff --git a/src/core/persistence/bounded-reads.ts b/src/core/persistence/bounded-reads.ts
new file mode 100644
index 0000000000..205f1c21f3
--- /dev/null
+++ b/src/core/persistence/bounded-reads.ts
@@ -0,0 +1,70 @@
+/**
+ * #6278 (plan item 1.4): a preparation read that can wait on a relation lock
+ * ends at the budget on the server, not only in this process.
+ *
+ * Preparation reads run outside the publication transaction, and through a
+ * transaction-mode pooler the session's `statement_timeout` startup parameter
+ * is dropped, so an `ACCESS EXCLUSIVE` lock on `pages` held in another
+ * session pinned the member's statement, and its connection, for as long as
+ * the lock lasted: the budget released the claim, but the statement kept
+ * running as a zombie and the root stayed blocked until the hard ceiling.
+ * `boundedReads` wraps the preparer's engine so every unmemoized raw
+ * statement runs with `executeRaw`'s `timeoutMs` set to the time the clock
+ * has left (`deadlineAt`), a transaction-local `statement_timeout` that holds
+ * through the pooler. A statement the server ends for it (57014 statement
+ * timeout, or a 55P03 lock timeout a shorter session `lock_timeout` raised)
+ * surfaces as the member's own `preparation_deadline`, so the consumer
+ * releases the claim charged instead of writing a `storage_error` receipt or
+ * an uncounted `database_contention` release.
+ *
+ * The memo rule stands: a read `preparationReads` answers once for a whole
+ * group never takes one member's bound or signal (group-publish.ts drops
+ * them), and a statement that already carries a caller's signal keeps the
+ * foreground path's cancellation instead of the bound. Engine helpers that bypass `executeRaw`
+ * (`readPageSnapshot` and the import pipeline) stay under the consumer's race
+ * and the ceiling. Without a deadline (switch off, a clock from an older
+ * caller) or on PGLite (one in-process connection, no other session to wait
+ * on) the engine is returned as it is.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { ClaimPhaseClock } from './claim-phase.ts';
+import { registerEngineView, viewedEngine } from './switches.ts';
+
+/** The SQLSTATEs a bounded read ends with when its server-side bound passes. */
+const DEADLINE_SQLSTATES = new Set(['57014', '55P03']);
+
+/** The error a bounded read rejects with at its bound; `code` is what `preparationAbortReason` reads. */
+export class PreparationDeadlineError extends Error {
+ readonly code = 'preparation_deadline';
+ constructor(readonly step: string | null, readonly sqlstate: string, cause: unknown) {
+ super(`The preparation read${step ? ` at step ${step}` : ''} did not finish within its budget (the server ended it, SQLSTATE ${sqlstate}).`, { cause });
+ this.name = 'PreparationDeadlineError';
+ }
+}
+
+/** Whether `error` is the server ending a statement at a timeout (ours, or a shorter session one). */
+export function isStatementTimeout(error: unknown): error is { code: string } {
+ const code = (error as { code?: unknown } | null)?.code;
+ return typeof code === 'string' && DEADLINE_SQLSTATES.has(code);
+}
+
+/** The engine a preparer reads through: raw statements bounded by the clock's remaining budget, everything else untouched. */
+export function boundedReads(engine: BrainEngine, clock: ClaimPhaseClock | undefined): BrainEngine {
+ const deadlineAt = clock?.deadlineAt;
+ if (deadlineAt === undefined || engine.kind !== 'postgres') return engine;
+ return registerEngineView(new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number }) => {
+ if (opts?.signal) return target.executeRaw(sql, params, opts);
+ try {
+ // The clock's signal ends only the wait for a free connection (a saturated pool); the statement itself ends at the bound.
+ return await target.executeRaw(sql, params, { ...opts, timeoutMs: Math.max(1, deadlineAt - Date.now()), ...(clock!.signal ? { signal: clock!.signal } : {}) });
+ } catch (error) {
+ if (!isStatementTimeout(error)) throw error;
+ if (clock!.signal?.aborted) throw clock!.signal.reason;
+ throw new PreparationDeadlineError(clock!.step, error.code, error);
+ }
+ };
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } }), viewedEngine(engine));
+}
diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.ts
index 22dfa97e95..78abdff319 100644
--- a/src/core/persistence/claim-phase.ts
+++ b/src/core/persistence/claim-phase.ts
@@ -50,12 +50,20 @@ export interface ClaimPhaseClock {
* (a signalled statement reserves its own connection and skips the memo).
*/
signal?: AbortSignal;
+ /**
+ * #6278: when the preparation's budget runs out (`claimedAt` plus the
+ * budget), so a read that can wait on a relation lock runs under a
+ * transaction-local `statement_timeout` of the time left (`boundedReads`).
+ * Absent with the deadlines switch off.
+ */
+ deadlineAt?: number;
}
/** The process that holds a claim, as the stamp records it. */
export interface ClaimOwner { kind: string; pid: number; version: string }
-export function startClaimPhase(now = Date.now(), signal?: AbortSignal): ClaimPhaseClock {
- return { phase: 'preparing', claimedAt: now, since: now, step: null, stepSince: now, waitingOn: 'unknown', ...(signal ? { signal } : {}) };
+export function startClaimPhase(now = Date.now(), signal?: AbortSignal, budgetMs?: number): ClaimPhaseClock {
+ return { phase: 'preparing', claimedAt: now, since: now, step: null, stepSince: now, waitingOn: 'unknown', ...(signal ? { signal } : {}),
+ ...(budgetMs !== undefined ? { deadlineAt: now + budgetMs } : {}) };
}
export function enterClaimPhase(clock: ClaimPhaseClock, phase: ClaimPhaseName, now = Date.now()): void {
if (clock.phase === phase) return;
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index d739f0c0ac..7a17031a8f 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -702,9 +702,10 @@ export class PersistenceConsumer {
// #6278: every kind has a budget with the switch on; off, only remember and intent-less put_page/edit_page (#5616) keep the 30 s one.
const foregroundMs = this.opts.preparationMs ?? 30_000;
const budget = policy.deadlines ? preparationBudgetMs(row, policy, foregroundMs) : preparationKind(row) === 'foreground' ? foregroundMs : undefined;
- // #6278: the clock carries the preparation's cancellation for `enterClaimStep`; a query takes the signal only on the foreground path (as before).
+ // #6278: the clock carries the preparation's cancellation for `enterClaimStep` and, with the switch on, its deadline for the
+ // server-side bound on lock-prone reads (boundedReads); a query takes the signal only on the foreground path (as before).
const cancel = new AbortController();
- const clock = startClaimPhase(Date.now(), cancel.signal);
+ const clock = startClaimPhase(Date.now(), cancel.signal, policy.deadlines ? budget : undefined);
// #6278: a request already at the attempt limit (a kill loop charged it at each reclaim) is finished without preparing again.
if (policy.deadlines && (row.preparation_attempts ?? 0) >= policy.maxAttempts) {
try {
@@ -730,6 +731,19 @@ export class PersistenceConsumer {
this.leaseTiming(), () => prep.abort({ code: 'claim_lost' }));
const releaseReason = () => !lease.held ? 'claim_lost' : observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping';
const stallInfo = () => ({ step: clock.step, waiting_on: clock.waitingOn, limit: policy.maxAttempts });
+ // The budget passed (on the timer, or reported by a bounded read the server ended): the claim is released now, charged,
+ // whether or not the preparer settles; its late result never publishes (#6278).
+ const deadline = async (): Promise<boolean> => {
+ root.until = this.abandonedRootBlock(row, clock, this.keepAbandoned(prep.work));
+ if (!lease.held || this.stopping) { await releaseUnpublishedClaim(this.engine, row, releaseReason()); return false; }
+ if ((row.preparation_attempts ?? 0) + 1 >= policy.maxAttempts) {
+ const done = await finishPreparationStalled(this.engine, row, stallInfo(), true);
+ this.log('preparation', 'preparation_stalled', failureLogText(done));
+ return this.settled(done);
+ }
+ await releaseUnpublishedClaim(this.engine, row, 'preparation_deadline', { charge: true });
+ return false;
+ };
try {
// With the switch on the budget wins the race even against a preparer that ignores its signal; off, the preparer's own settlement decides.
const raced = await lease.whileHeld(policy.deadlines ? prep.outcome : prep.work.then(result => ({ result })));
@@ -739,18 +753,7 @@ export class PersistenceConsumer {
await releaseUnpublishedClaim(this.engine, row, 'claim_lost');
return false;
}
- if ('deadline' in raced) {
- // The claim is released now, charged, whether or not the preparer settles; its late result never publishes (#6278).
- root.until = this.abandonedRootBlock(row, clock, this.keepAbandoned(prep.work));
- if (!lease.held || this.stopping) { await releaseUnpublishedClaim(this.engine, row, releaseReason()); return false; }
- if ((row.preparation_attempts ?? 0) + 1 >= policy.maxAttempts) {
- const done = await finishPreparationStalled(this.engine, row, stallInfo(), true);
- this.log('preparation', 'preparation_stalled', failureLogText(done));
- return this.settled(done);
- }
- await releaseUnpublishedClaim(this.engine, row, 'preparation_deadline', { charge: true });
- return false;
- }
+ if ('deadline' in raced) return deadline();
const prepared = raced.result;
if (budget !== undefined && !prep.signal.aborted && prep.late()) prep.expire();
if (!lease.held || this.stopping || prep.signal.aborted) {
@@ -768,6 +771,11 @@ export class PersistenceConsumer {
return settled ? isTerminal(done) : this.settled(done);
} catch (error) {
if (preparationActive && budget !== undefined && prep.late()) observation.deadline_exceeded = true;
+ // #6278: a bounded read the server ended inside the budget (a shorter session lock_timeout) reports the deadline itself.
+ if (preparationActive && policy.deadlines && !prep.signal.aborted && preparationAbortReason(error, prep.signal) === 'preparation_deadline') {
+ prep.expire();
+ return deadline();
+ }
// #6278: the preparer's rejection on our own abort (its reason, an AbortError, a cancelled statement) is a release, never a receipt.
if (preparationActive && (prep.signal.aborted || observation.deadline_exceeded || preparationAbortReason(error, prep.signal))) {
await releaseUnpublishedClaim(this.engine, row, releaseReason());
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index c8304c1247..48d15ba6b5 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -153,8 +153,11 @@ export function preparationReads(engine: BrainEngine): BrainEngine {
return value;
};
return new Proxy(engine, { get(target, key) {
- if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) =>
- STABLE_IN_PREPARATION.has(flat(sql)) && !opts?.signal ? once(JSON.stringify([flat(sql), params ?? null]), () => target.executeRaw(sql, params, opts)) : target.executeRaw(sql, params, opts);
+ // A shared read takes no member's signal: a caller's own signal bypasses the memo, and (#6278) a bounded preparation read
+ // (`timeoutMs`, whose signal only covers its connection wait) is answered once with the member's bound and signal dropped.
+ if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number }) =>
+ STABLE_IN_PREPARATION.has(flat(sql)) && (!opts?.signal || opts.timeoutMs !== undefined)
+ ? once(JSON.stringify([flat(sql), params ?? null]), () => target.executeRaw(sql, params)) : target.executeRaw(sql, params, opts);
if (key === 'getConfig') return (name: string) => once(`config:${name}`, () => target.getConfig(name));
if (key === 'getAllConfig') return () => once('config:*', () => target.getAllConfig()).then(all => ({ ...all }));
const value = Reflect.get(target, key, target);
@@ -554,11 +557,12 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
const wave = rows.slice(start, start + width);
const now = Date.now();
const cancels = wave.map(() => new AbortController());
- wave.forEach((_row, offset) => { clocks[start + offset] = startClaimPhase(now, cancels[offset]!.signal); });
+ const budgets = wave.map(row => policy.deadlines ? preparationBudgetMs(row, policy, foregroundMs) : undefined);
+ wave.forEach((_row, offset) => { clocks[start + offset] = startClaimPhase(now, cancels[offset]!.signal, budgets[offset]); });
if (policy.deadlines) await markDispatched(engine, wave.map((row, offset) => ({ row, stamp: stampOf(start + offset)! })));
const wavePreps = wave.map((row, offset) => {
const i = start + offset;
- const budget = policy.deadlines ? preparationBudgetMs(row, policy, foregroundMs) : undefined;
+ const budget = budgets[offset];
// The member's signal reaches its preparer through its clock (enterClaimStep), never as a blanket statement signal: see the memo rule.
const prep = startPreparation(async signal => {
signal.addEventListener('abort', () => cancels[offset]!.abort(signal.reason), { once: true });
@@ -580,6 +584,8 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
prepared[i] = 'deadline' in outcome ? { released: 'preparation_deadline' } : { ok: outcome.result };
} catch (error) {
const reason = preparationAbortReason(error, prep.signal);
+ // #6278: a bounded read the server ended inside the budget reports the deadline itself; it cuts the group like the timer would.
+ if (reason === 'preparation_deadline' && policy.deadlines) prep.expire();
prepared[i] = reason === 'preparation_deadline' || reason === 'group_member_waiting' || reason === 'claim_lost' ? { released: reason } : { error };
} finally { inFlight.delete(i); }
}));
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 1214dec574..e437cd8935 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -1,5 +1,6 @@
import { isEmbedSkipped } from '../embed-skip.ts';
import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';
+import { boundedReads } from './bounded-reads.ts';
import { isQuarantined, quarantineOutcome } from '../quarantine.ts';
import { existsSync, readFileSync } from 'node:fs';
import { join, relative, sep } from 'node:path';
@@ -254,12 +255,16 @@ async function pageDatabaseOnlyPublication(engine: SqlEngine, row: WriteRequest,
* `coordinated`: the caller publishes this mutation itself through the coordinator, whose
* page guard and revision check on `row.slug` cover this import (the put_page apply diet).
*/
-/** `options.clock` (#6278): the claim's phase clock; each await boundary names its step through `enterClaimStep`. */
-export async function preparePageMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig,
+/**
+ * `options.clock` (#6278): the claim's phase clock; each await boundary names its step through `enterClaimStep`, and the
+ * preparation's raw reads run bounded by its remaining budget (`boundedReads`; a statement carrying the foreground `signal` keeps it).
+ */
+export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig,
preparedIntent?: { content: string; expectedRevision: string; tags?: string[] }, signal?: AbortSignal,
options: { allowMissingFile?: boolean; coordinated?: boolean; clock?: ClaimPhaseClock } = {}): Promise<PreparedMutation> {
signal?.throwIfAborted();
const clock = options.clock;
+ const engine = boundedReads(unbounded, clock);
enterClaimStep(clock, 'page_snapshot', undefined, 'db');
if (!row.intent) throw pageRefusal('storage_error', 'A pending write lost its normalized intent.', row,
`The request has no stored intent for ${row.slug} (its payload was compacted or never recorded), so it cannot be published and wrote nothing.`);
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 843df8bfe3..f3065e4f93 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -1,5 +1,6 @@
import { realpathSync } from 'node:fs';
import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';
+import { boundedReads } from './bounded-reads.ts';
import { join } from 'node:path';
import type { BrainEngine, FactRow } from '../engine.ts';
import { loadConfig, type GBrainConfig } from '../config.ts';
@@ -305,8 +306,12 @@ export async function submitFactFenceAdoption(engine: BrainEngine, authority: Ma
}
}
-/** `clock` (#6278): the claim's phase clock; the adoption's await boundaries (read facts, parse, occupied rows, the page) name their step. */
-async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, clock?: ClaimPhaseClock): Promise<PreparedMutation> {
+/**
+ * `clock` (#6278): the claim's phase clock; the adoption's await boundaries (read facts, parse, occupied rows, the page) name
+ * their step, and its preparation reads of `facts` run bounded by the remaining budget (`boundedReads`).
+ */
+async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteRequest, config: GBrainConfig, clock?: ClaimPhaseClock): Promise<PreparedMutation> {
+ const engine = boundedReads(unbounded, clock);
const p = row.intent!;
const facts = p.facts as FactFenceAssignment[];
if (p.source_incarnation !== row.source_incarnation) throw opError('source_changed', 'The fact adoption source changed.',
@@ -350,7 +355,7 @@ async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest,
{ fix: receiptFix(row) });
};
await check(engine, false);
- const prepared = await preparePageMutation(engine, { ...row, intent: { kind: 'managed_maintenance_page', content: p.content,
+ const prepared = await preparePageMutation(unbounded, { ...row, intent: { kind: 'managed_maintenance_page', content: p.content,
expected_revision: p.expected_revision } }, config, undefined, undefined, { clock });
return { ...prepared, validate: async tx => { await prepared.validate?.(tx); await check(tx, true); }, apply: async tx => {
// Runs ahead of the page import and its canonical projection, so the
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 190ec3535a..9d867c49d5 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -1,5 +1,6 @@
import { realpathSync } from 'node:fs';
import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';
+import { boundedReads } from './bounded-reads.ts';
import { basename, join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
@@ -266,9 +267,12 @@ async function resolveSyncOrigin(engine: BrainEngine, row: WriteRequest, p: Sync
* `clock` (#6278): the claim's phase clock. Each await boundary below names its step and what it waits on
* (`enterClaimStep`), which also throws the preparation's abort reason once its budget cut it off. No
* statement here takes the member's signal: the reads a group memoizes (preparationReads) must stay shared,
- * and the step boundaries are where cancellation lands.
+ * and the step boundaries are where cancellation lands. The preparation's raw reads run through
+ * `boundedReads`: a relation lock held elsewhere ends the statement on the server at the budget (plan 1.4),
+ * so the member is released without a zombie statement pinning a connection until the ceiling.
*/
-export async function prepareManagedSyncMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock?: ClaimPhaseClock): Promise<PreparedMutation> {
+export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock?: ClaimPhaseClock): Promise<PreparedMutation> {
+ const engine = boundedReads(unbounded, clock);
const p = row.intent as SyncIntent | null;
if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw syncPublicationRefusal('invalid_params', 'Unsupported internal sync intent.', row, p,
'The request does not carry a managed sync intent this release can publish.');
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index c504e6e9f5..ed5b94ebe2 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -17,6 +17,7 @@ import { isImageFilePath } from '../sync.ts';
import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';
import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
import { prepareManagedSyncMutation, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';
+import { startClaimPhase } from './claim-phase.ts';
import { screeningRequest } from './noop-kernel.ts';
import { noopWaiversEnabled, raceSyncBudget, screenWaiver, syncPreparationBudgetMs, unfinishedPageRequestParams, UNFINISHED_PAGE_REQUEST_SQL, waiveNoopEntry, waiveNoopRun, waiverBatchEnabled, type NoopWaiver, type WaiverRunEntry } from './sync-waivers.ts';
import { resolve } from 'node:path';
@@ -695,8 +696,9 @@ async function sameContentAtOrigin(engine: BrainEngine, cursor: Cursor, entry: C
processingOptions: cursor.processingOptions, ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority,
cursorKey: key, runId: cursor.runId, slugMode: cursor.slugMode, index: cursor.index, total: cursor.entries.length, from: cursor.from, target: cursor.target, working: entry.working ?? false };
try {
+ const budgetMs = await syncPreparationBudgetMs(engine);
const prepared = await raceSyncBudget(prepareManagedSyncMutation(engine, screeningRequest({ source_id: cursor.sourceId, source_incarnation: cursor.incarnation, slug: snapshot.page.slug,
- page_id: snapshot.page.id, worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent }), { engine: engine.kind }), await syncPreparationBudgetMs(engine), signal);
+ page_id: snapshot.page.id, worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent }), { engine: engine.kind }, startClaimPhase(Date.now(), undefined, budgetMs)), budgetMs, signal);
return (prepared.contentUnchanged === true || prepared.noop === true) && !prepared.file && prepared.observedRevision === snapshot.revision;
} catch (error) {
if (signal?.aborted) throw error;
diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.ts
index ff8d94bc52..7d13731af5 100644
--- a/src/core/persistence/sync-waivers.ts
+++ b/src/core/persistence/sync-waivers.ts
@@ -9,6 +9,7 @@ import { join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { prepareManagedSyncMutation, type SyncIntent } from './sync-prepare.ts';
+import { startClaimPhase } from './claim-phase.ts';
import { inspectUnchanged, screeningRequest, type NoopKernelWaiver } from './noop-kernel.ts';
import { validateSyncAuthority, type SyncAuthority } from './sync-authority.ts';
import { readSyncFile } from './sync-discovery.ts';
@@ -239,7 +240,9 @@ export async function unchangedSyncImport(engine: BrainEngine, cursor: WaiverCur
const snapshot = await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });
const row = screeningRequest({ source_id: cursor.sourceId, source_incarnation: cursor.incarnation, slug: pending.slug, page_id: pending.pageId,
worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent, request_id: pending.requestId });
- const prepared = await raceSyncBudget(prepareManagedSyncMutation(engine, row, config), await syncPreparationBudgetMs(engine), signal);
+ // #6278 (1.4): the clock carries the budget, so the preparation's lock-prone reads end on the server at it (boundedReads).
+ const budgetMs = await syncPreparationBudgetMs(engine);
+ const prepared = await raceSyncBudget(prepareManagedSyncMutation(engine, row, config, startClaimPhase(Date.now(), undefined, budgetMs)), budgetMs, signal);
if (prepared.file || prepared.target === 'skill_bundle') return null;
const file = { root: cursor.root, path: join(cursor.root, intent.path), content: intent.content };
const inspected = await inspectUnchanged(engine, { prepared: { ...prepared, target: 'page', file }, snapshot, sourcePath: intent.sourcePath, databaseOnly: false,
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 765cfc9bb8..4fadccc380 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2746,16 +2746,48 @@ export class PostgresEngine implements BrainEngine {
})();
}
+ /**
+ * #6278: `executeRaw` with `timeoutMs`. The session's `statement_timeout` is a
+ * startup parameter a transaction-mode pooler drops, so a preparation read
+ * outside the publication transaction had no server-side bound and a
+ * relation lock held elsewhere pinned its connection for as long as the lock
+ * lasted. A reserved connection runs `BEGIN; SET LOCAL statement_timeout`,
+ * the statement and `COMMIT` as one pipelined round trip: the pooler pins
+ * the transaction to one server connection, `SET LOCAL` ends with it, and a
+ * statement past the bound ends server-side with 57014 (a lock wait counts
+ * toward it). `COMMIT` after a failed statement is a rollback, never an
+ * error of its own. `signal` covers only the wait for a free connection (a
+ * saturated pool must not hold the bound off); the statement itself ends at
+ * the bound, never by a cancel request.
+ */
+ private async runBounded<T>(conn: ReturnType<typeof postgres>, sql: string, params: unknown[] | undefined,
+ opts: { timeoutMs: number; signal?: AbortSignal }): Promise<T[]> {
+ const ms = Math.max(1, Math.ceil(opts.timeoutMs));
+ const reserved = opts.signal ? await reserveWithCancellation(reserve => conn.reserve(reserve), opts.signal) : await conn.reserve();
+ this.checkoutGauge.checkedOut();
+ try {
+ const open = reserved.unsafe(`BEGIN; SET LOCAL statement_timeout = ${ms}`).simple().execute();
+ const read = reserved.unsafe(sql, params as Parameters<typeof reserved.unsafe>[1], { prepare: true }).execute();
+ const close = reserved.unsafe('COMMIT').execute();
+ const settled = await Promise.allSettled([open, read, close]);
+ for (const outcome of settled) if (outcome.status === 'rejected') throw outcome.reason;
+ return (settled[1] as PromiseFulfilledResult<unknown>).value as T[];
+ } finally {
+ reserved.release();
+ }
+ }
+
async executeRaw<T = Record<string, unknown>>(
sql: string,
params?: unknown[],
- opts?: { signal?: AbortSignal },
+ opts?: { signal?: AbortSignal; timeoutMs?: number },
): Promise<T[]> {
// try/finally (not .finally on the promise): runUnsafe throws
// SYNCHRONOUSLY on a pre-aborted signal, which would skip a chained
// .finally and leak the counter.
this.checkoutGauge.acquire('raw');
try {
+ if (opts?.timeoutMs !== undefined && !this._pageTransaction) return await this.runBounded<T>(this.sql, sql, params, { ...opts, timeoutMs: opts.timeoutMs });
return await this.runUnsafe<T>(this.sql, sql, params, opts);
} finally {
this.checkoutGauge.release('raw');
diff --git a/test/e2e/persistence-group-deadline-postgres.test.ts b/test/e2e/persistence-group-deadline-postgres.test.ts
index ed7787cc46..1ea4e8e30b 100644
--- a/test/e2e/persistence-group-deadline-postgres.test.ts
+++ b/test/e2e/persistence-group-deadline-postgres.test.ts
@@ -23,6 +23,7 @@ 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 { PreparationDeadlineError } from '../../src/core/persistence/bounded-reads.ts';
import { admitWrite, getWriteRequestById } from '../../src/core/persistence/journal.ts';
import type { PreparedMutation } from '../../src/core/persistence/coordinator.ts';
import type { WriteRequest } from '../../src/core/persistence/model.ts';
@@ -128,6 +129,34 @@ describe.skipIf(!hasDatabase())('grouped preparation deadlines (Postgres, #6278)
}), 90_000);
}
+ // #6278 (plan item 1.4): a bounded read the server ended inside the budget reports the deadline itself and cuts the group like the timer.
+ test('a member whose read the server ended inside the budget is released charged, the later members uncharged, and the prefix publishes', () => withBrain(async ({ engine, config, sources }) => {
+ const rows = await admitGroup(engine, config, sources[0]!, 'server-ended', 6, 'ordered');
+ const k = 2;
+ const attempts = new Map<string, number>();
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async (_engine: unknown, row: WriteRequest): Promise<PreparedMutation> => {
+ attempts.set(row.id, (attempts.get(row.id) ?? 0) + 1);
+ if (row.id === rows[k]!.id && attempts.get(row.id) === 1) throw new PreparationDeadlineError('origin_check', '57014', Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' }));
+ return prepared(row, sources);
+ }, { hostId: config.hostId, concurrency: 1, pollMs: 50, renewalIntervalMs: 20, phaseMs: 2_000, preparationMs: 5_000,
+ preparationBudgets: { maxAttempts: 5, ceilingMs: 60_000 }, onError: () => {} });
+ try {
+ consumer.start();
+ await waitFor(async () => (await getWriteRequestById(engine, rows[k]!.id))?.blocked_reason === 'preparation_deadline', { timeoutMs: 15_000, label: `member ${k} is released` });
+ // The suffix is cut exactly as a timer deadline cuts it: released uncharged, never published ahead of k.
+ await waitFor(async () => (await stateOf(engine, rows.slice(k + 1))).every(s => s.state === 'queued' && s.reason === 'group_member_waiting'), { timeoutMs: 15_000, label: 'the suffix is released waiting' });
+ for (let i = 0; i < k; i++) await waitFor(async () => (await getWriteRequestById(engine, rows[i]!.id))?.state === 'committed', { timeoutMs: 15_000, label: `prefix member ${i} commits` });
+ // No terminal receipt was written from the raw error.
+ const states = await stateOf(engine, rows);
+ expect(states.every(s => s.error === null)).toBe(true);
+ expect(states[k]).toMatchObject({ reason: 'preparation_deadline', attempts: 1 });
+ expect(states.slice(0, k).map(s => s.state)).toEqual(['committed', 'committed']);
+ for (const row of rows) await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed', { timeoutMs: 20_000, label: `${row.slug} commits after the retry` });
+ expect(attempts.get(rows[k]!.id)).toBe(2);
+ expect((await stateOf(engine, rows)).map(s => s.attempts)).toEqual(rows.map(() => 0));
+ } finally { await consumer.stop(); }
+ }), 90_000);
+
test('an independent batch group releases only the expired member; its siblings publish', () => withBrain(async ({ engine, config, sources }) => {
const rows = await admitGroup(engine, config, sources[0]!, 'batch', 4, 'batch');
const release = Promise.withResolvers<void>();
diff --git a/test/e2e/persistence-preparation-lock-wait-postgres.test.ts b/test/e2e/persistence-preparation-lock-wait-postgres.test.ts
new file mode 100644
index 0000000000..bcad2a3a78
--- /dev/null
+++ b/test/e2e/persistence-preparation-lock-wait-postgres.test.ts
@@ -0,0 +1,226 @@
+/**
+ * #6278 (plan item 1.4) on Postgres: a preparation read blocked by a relation
+ * lock ends at the budget on the server, not only in this process. Phase 0
+ * (docs/eval/managed-sync-stall-repro.md) reproduced the reporter's signature
+ * by holding `LOCK TABLE pages IN ACCESS EXCLUSIVE MODE` in another session
+ * through a transaction-mode pooler, which drops the session's
+ * `statement_timeout`: the member's origin check (`SELECT id,slug,source_path
+ * FROM pages ...`, step `origin_check`) waited for as long as the lock was
+ * held, and with the budget alone the released member's statement kept
+ * running as a zombie that pinned its connection and its root until the
+ * ceiling. Here another connection holds that lock in an open transaction
+ * while a 200-page managed source drains through the real `performSync`
+ * (budget 2 s, one lane: the grouped route in the first variant, the single
+ * route in the second). Protects: the member is released `preparation_deadline` within
+ * the budget plus slack, with its last step `origin_check`; no statement of
+ * the sync remains active on the server after the release (the bound ended
+ * it) while nothing new is issued, so the pool's active count is back at
+ * zero; the root is free, so once the lock is dropped the same member and
+ * every page behind it commit (the counter resets on commit). The second
+ * variant holds the lock past both attempts: the member finishes
+ * `failed`/`preparation_stalled` and the run ends blocked instead of waiting
+ * for the watchdog. Before the server-side bound, the first variant failed:
+ * the statement outlived the release (still `active`, waiting on the lock) and
+ * the member was re-claimed only after the ceiling. Fails again if the bound
+ * stops reaching the origin check or a 57014 at the budget is written as a
+ * `storage_error` receipt instead of a charged release.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import postgres from '#postgres';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { performSync } from '../../src/commands/sync/perform.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { resetWriteSwitches } from '../../src/core/persistence/switches.ts';
+import { hasDatabase } from './helpers.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { waitFor } from '../helpers/wait-for.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-prep-lock-wait-e2e-'));
+let engine: BrainEngine | undefined;
+let databaseUrl = '';
+let closePostgres: (() => Promise<void>) | undefined;
+const sources: string[] = [];
+const BUDGET_MS = 2_000;
+/** How long past the budget the release may land (the server's timeout fires at the budget; the release statement follows). */
+const SLACK_MS = 3_000;
+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
+const pad = (i: number) => String(i).padStart(3, '0');
+async function fixture(e: BrainEngine, count: number) {
+ const id = `lockwait-${randomUUID().replace(/-/g, '').slice(0, 16)}`; sources.push(id);
+ const root = join(home, id); mkdirSync(root); git(root, 'init', '-q');
+ for (let i = 0; i < count; i++) {
+ const full = join(root, 'notes', `n${pad(i)}.md`); mkdirSync(join(full, '..'), { recursive: true });
+ writeFileSync(full, `---\ntitle: Note ${i}\n---\nA durable observation number ${i}, see [[notes/n${pad((i + 7) % count)}]].\n`);
+ }
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+ await e.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await e.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
+ await claimWorktree(e, id, root);
+ await e.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root };
+}
+type ImportRow = { slug: string; state: string; blocked_reason: string | null; error_code: string | null; preparation_attempts: number; error_message: string | null };
+const imports = (e: BrainEngine, source: string) => e.executeRaw<ImportRow>(
+ `SELECT slug,state,blocked_reason,error_code,preparation_attempts,error_message FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence`, [source]);
+const ORIGIN_CHECK_SQL = 'SELECT id,slug,source_path FROM pages WHERE source_id=$1 AND ';
+
+/** The lock holder: another session holding `pages` ACCESS EXCLUSIVE in an open transaction until `drop()`. */
+async function holdPagesLock(url: string) {
+ // Two connections: one holds the lock's transaction, the other reads the server state while it is held.
+ const holder = postgres(url, { max: 2, prepare: false, onnotice: () => {} });
+ const dropped = Promise.withResolvers<void>();
+ const acquired = Promise.withResolvers<void>();
+ const transaction = holder.begin(async sql => {
+ // NOWAIT, retried: a queued ACCESS EXCLUSIVE request would make every later reader wait behind it while a publication
+ // transaction still holds the table, so the holder takes the lock only at a moment nothing holds `pages`.
+ for (;;) {
+ await sql.unsafe('SAVEPOINT lock_attempt');
+ try { await sql.unsafe('LOCK TABLE pages IN ACCESS EXCLUSIVE MODE NOWAIT'); break; }
+ catch (error) {
+ if ((error as { code?: string }).code !== '55P03') throw error;
+ await sql.unsafe('ROLLBACK TO SAVEPOINT lock_attempt');
+ await Bun.sleep(20);
+ }
+ }
+ acquired.resolve();
+ await dropped.promise;
+ }).catch(error => { acquired.reject(error); throw error; });
+ await acquired.promise;
+ // The holder's own connection reads the server state: while the lock is held the engine's pool may be saturated by reads waiting on it.
+ /** The sync's origin-check statements still running on the server (every one of them waits on this lock). */
+ const activeOriginChecks = async () => Array.from(await holder.unsafe(
+ `SELECT pid,state,wait_event_type,left(query,80) AS query FROM pg_stat_activity WHERE datname=current_database() AND pid<>pg_backend_pid() AND state<>'idle' AND query LIKE $1`,
+ [`${ORIGIN_CHECK_SQL}%`])) as Array<Record<string, unknown>>;
+ const request = async (sourceId: string, slug: string) => (Array.from(await holder.unsafe(
+ `SELECT slug,state,blocked_reason,error_code,preparation_attempts,error_message FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND intent->>'kind'='managed_sync_import'`,
+ [sourceId, slug])) as ImportRow[])[0];
+ return { activeOriginChecks, request, drop: async () => { dropped.resolve(); await transaction.catch(() => undefined); await holder.end(); } };
+}
+
+/**
+ * Intercepts the consumer's origin check of `path` (the claimed request's, never the feeder's screen): `onFirst` runs before the
+ * statement the first time (it takes the lock), and while `gate` is closed every later origin check of this source waits in
+ * process, so a statement seen active on the server after the release can only be a statement the release left behind.
+ */
+function interceptOriginChecks(e: BrainEngine, sourceId: string, path: string, slug: string, onFirst: () => Promise<void>) {
+ const original = e.executeRaw;
+ let gate: Promise<void> = Promise.resolve();
+ let holds = 0;
+ (e as { executeRaw: unknown }).executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[], opts?: unknown) {
+ if (typeof sql === 'string' && sql.startsWith(ORIGIN_CHECK_SQL) && params?.[0] === sourceId) {
+ const target = Array.isArray(params?.[1]) && (params![1] as string[]).includes(path);
+ const [claimed] = target ? await original.call(this, "SELECT 1 FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND state='running' AND intent->>'kind'='managed_sync_import'", [sourceId, slug]) : [];
+ if (claimed && ++holds === 1) await onFirst();
+ else await gate;
+ }
+ return original.call(this, sql, params, opts as never);
+ };
+ return { restore: () => { (e as { executeRaw: unknown }).executeRaw = original; }, holds: () => holds,
+ close: () => { const opened = Promise.withResolvers<void>(); gate = opened.promise; return () => opened.resolve(); } };
+}
+
+beforeAll(async () => {
+ if (!hasDatabase()) return;
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!, 'instance', 12); engine = pg.engine; closePostgres = pg.close; databaseUrl = pg.databaseUrl;
+ await engine.setConfig('persistence.sync_preparation_ms', String(BUDGET_MS));
+ await engine.setConfig('persistence.preparation_ceiling_ms', '60000');
+ resetWriteSwitches();
+}, 120_000);
+afterAll(async () => {
+ if (engine) await withEnv({ GBRAIN_HOME: home }, async () => {
+ await disposePersistenceConsumer(engine!); await engine!.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const id of sources) await engine!.executeRaw('DELETE FROM sources WHERE id=$1', [id]);
+ });
+ resetWriteSwitches();
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe.skipIf(!hasDatabase())('a lock-blocked preparation read ends at the budget (Postgres, #6278 plan 1.4)', () => {
+ test('the member is released preparation_deadline at the budget with no statement left on the server, and commits once the lock is dropped', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
+ if (!engine) return;
+ const f = await fixture(engine, 200);
+ const stuckSlug = 'notes/n052', stuckPath = 'notes/n052.md';
+ let lock: Awaited<ReturnType<typeof holdPagesLock>> | undefined;
+ let lockedAt = 0;
+ const observed: { releasedAt?: number; released?: ImportRow; leftover?: Array<Record<string, unknown>>; clearedAfterMs?: number } = {};
+ const intercept = interceptOriginChecks(engine, f.id, stuckPath, stuckSlug, async () => {
+ lock = await holdPagesLock(databaseUrl);
+ lockedAt = performance.now();
+ // The watcher: once the member is released, nothing new reaches the server, the leftover statements are counted, then the lock drops.
+ void (async () => {
+ const open = intercept.close();
+ try {
+ await waitFor(async () => { const row = await lock!.request(f.id, stuckSlug); if (row?.state === 'queued' && row.blocked_reason === 'preparation_deadline') { observed.released = row; return true; } return false; },
+ { timeoutMs: BUDGET_MS + SLACK_MS + 5_000, intervalMs: 50, label: 'the member is released at the budget' });
+ observed.releasedAt = performance.now();
+ // The wave's other members share its deadline; nothing of this wave may stay active on the server past the slack.
+ await waitFor(async () => (await lock!.activeOriginChecks()).length === 0, { timeoutMs: SLACK_MS, intervalMs: 50, label: 'no origin check stays active on the server' })
+ .catch(async () => { observed.leftover = await lock!.activeOriginChecks(); });
+ observed.clearedAfterMs = performance.now() - observed.releasedAt;
+ } finally { await lock!.drop(); open(); }
+ })();
+ });
+ await engine.setConfig('sync.holds', 'fail');
+ let result;
+ try {
+ result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 1 });
+ } finally { intercept.restore(); await lock?.drop().catch(() => undefined); await engine.unsetConfig('sync.holds'); }
+ expect(intercept.holds()).toBeGreaterThanOrEqual(1);
+ // Released at the budget, charged once (the step reaches the stamp only on a renewal; the stalled receipt in the second variant names it).
+ expect(observed.released).toMatchObject({ state: 'queued', blocked_reason: 'preparation_deadline', preparation_attempts: 1 });
+ expect(observed.releasedAt! - lockedAt).toBeLessThan(BUDGET_MS + SLACK_MS);
+ expect(observed.releasedAt! - lockedAt).toBeGreaterThanOrEqual(BUDGET_MS * 0.9);
+ // The server ended the statements: no origin check of the sync is active while the lock is still held and nothing new is issued,
+ // so the released member pins no connection (before the bound, the statement stayed active, waiting on the lock, until it dropped).
+ expect(observed.leftover ?? []).toEqual([]);
+ expect(observed.clearedAfterMs).toBeLessThan(SLACK_MS);
+ // The root was free: the same member and every page committed once the lock dropped, and the counter reset on commit.
+ expect(result.drain).toMatchObject({ outcome: 'synced' });
+ const rows = await imports(engine, f.id);
+ expect(rows.find(row => row.slug === stuckSlug)).toMatchObject({ state: 'committed', preparation_attempts: 0 });
+ expect(rows.every(row => row.state === 'committed')).toBe(true);
+ expect(rows.filter(row => row.blocked_reason === 'claim_lost')).toEqual([]);
+ expect(await engine.getPage(stuckSlug, { sourceId: f.id })).not.toBeNull();
+ }), 300_000);
+
+ test('a lock held past both attempts finishes the member preparation_stalled and the run ends blocked instead of waiting for the watchdog', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SYNC_BULK_SIZE: '1' }, async () => {
+ if (!engine) return;
+ const f = await fixture(engine, 60);
+ const stuckSlug = 'notes/n024', stuckPath = 'notes/n024.md';
+ let lock: Awaited<ReturnType<typeof holdPagesLock>> | undefined;
+ let lockedAt = 0;
+ const intercept = interceptOriginChecks(engine, f.id, stuckPath, stuckSlug, async () => {
+ lock = await holdPagesLock(databaseUrl);
+ lockedAt = performance.now();
+ // Dropped only after the terminal receipt lands, so the second attempt also waits on the lock.
+ void waitFor(async () => (await lock!.request(f.id, stuckSlug))?.state === 'failed',
+ { timeoutMs: BUDGET_MS * 2 + SLACK_MS * 2 + 10_000, intervalMs: 50, label: 'the member finishes preparation_stalled' }).finally(() => lock!.drop());
+ });
+ await engine.setConfig('sync.holds', 'fail');
+ let result;
+ try {
+ result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 1 });
+ } finally { intercept.restore(); await lock?.drop().catch(() => undefined); await engine.unsetConfig('sync.holds'); }
+ const ended = performance.now();
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'blocked_by_failures' });
+ expect(result.managedWrite?.slug).toBe(stuckSlug);
+ const rows = await imports(engine, f.id);
+ const stuck = rows.find(row => row.slug === stuckSlug)!;
+ expect(stuck).toMatchObject({ state: 'failed', error_code: 'preparation_stalled', preparation_attempts: 2 });
+ expect(stuck.error_message).toContain('step origin_check (waiting on db)');
+ // Two budgets, each ended by the server, then the receipt: well inside the ceiling.
+ expect(ended - lockedAt).toBeLessThan(BUDGET_MS * 2 + SLACK_MS * 2 + 10_000);
+ const stuckAt = rows.findIndex(row => row.slug === stuckSlug);
+ expect(rows.slice(0, stuckAt).every(row => row.state === 'committed')).toBe(true);
+ expect(await engine.getPage(stuckSlug, { sourceId: f.id })).toBeNull();
+ expect(rows.filter(row => row.blocked_reason === 'claim_lost')).toEqual([]);
+ }), 300_000);
+});
diff --git a/test/persistence-bounded-reads.test.ts b/test/persistence-bounded-reads.test.ts
new file mode 100644
index 0000000000..0c65c95318
--- /dev/null
+++ b/test/persistence-bounded-reads.test.ts
@@ -0,0 +1,95 @@
+/**
+ * #6278 (plan item 1.4): `boundedReads`, the engine view a preparer reads
+ * through. Protects: a raw statement runs with `timeoutMs` set to the clock's
+ * remaining budget and the clock's signal (which ends only the wait for a
+ * connection); a caller's own signal keeps its statement unbounded; the view
+ * is the engine itself without a deadline or on PGLite; a statement the
+ * server ends at the bound (57014, or a 55P03 lock timeout) surfaces as the
+ * member's `preparation_deadline` (the signal's reason once it aborted, the
+ * typed error naming the step before that), which `preparationAbortReason`
+ * classifies as the deadline, never a terminal failure; any other error
+ * passes through; and a group's shared read (`preparationReads`) answers a
+ * bounded read once with the bound and signal dropped. Fails when the bound
+ * stops reaching the statement, when a server timeout is left as a raw
+ * Postgres error (a `storage_error` receipt), or when a member's bound leaks
+ * into a sibling's shared read.
+ */
+import { expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { boundedReads, isStatementTimeout, PreparationDeadlineError } from '../src/core/persistence/bounded-reads.ts';
+import { startClaimPhase, enterClaimStep } from '../src/core/persistence/claim-phase.ts';
+import { preparationAbortReason } from '../src/core/persistence/coordinator.ts';
+import { preparationReads } from '../src/core/persistence/group-publish.ts';
+
+type Call = { sql: string; opts?: { signal?: AbortSignal; timeoutMs?: number } };
+function fakeEngine(kind: 'postgres' | 'pglite', respond: (call: Call) => Promise<unknown[]>) {
+ const calls: Call[] = [];
+ const engine = { kind, executeRaw: (sql: string, _params?: unknown[], opts?: Call['opts']) => { const call = { sql, opts }; calls.push(call); return respond(call); },
+ getConfig: async () => null } as unknown as BrainEngine;
+ return { engine, calls };
+}
+const pgError = (code: string, message: string) => Object.assign(new Error(message), { code });
+
+test('a raw statement runs with the remaining budget and the clock\'s signal; a caller\'s signal keeps it unbounded', async () => {
+ const { engine, calls } = fakeEngine('postgres', async () => [{ ok: true }]);
+ const cancel = new AbortController();
+ const clock = startClaimPhase(Date.now(), cancel.signal, 10_000);
+ const reads = boundedReads(engine, clock);
+ expect(await reads.executeRaw('SELECT 1 FROM pages')).toEqual([{ ok: true }]);
+ expect(calls[0]!.opts!.timeoutMs).toBeGreaterThan(9_000);
+ expect(calls[0]!.opts!.timeoutMs).toBeLessThanOrEqual(10_000);
+ expect(calls[0]!.opts!.signal).toBe(cancel.signal);
+ const own = new AbortController();
+ await reads.executeRaw('SELECT 1 FROM pages', [], { signal: own.signal });
+ expect(calls[1]!.opts).toEqual({ signal: own.signal });
+ // Other members are the engine's own.
+ expect(typeof reads.getConfig).toBe('function');
+});
+
+test('without a deadline, or on PGLite, the view is the engine itself', () => {
+ const { engine } = fakeEngine('postgres', async () => []);
+ expect(boundedReads(engine, undefined)).toBe(engine);
+ expect(boundedReads(engine, startClaimPhase(Date.now(), new AbortController().signal))).toBe(engine);
+ const pglite = fakeEngine('pglite', async () => []).engine;
+ expect(boundedReads(pglite, startClaimPhase(Date.now(), undefined, 5_000))).toBe(pglite);
+});
+
+test('a statement the server ends at the bound is the member\'s preparation_deadline; the signal\'s reason once it aborted; other errors pass through', async () => {
+ let fail: unknown = pgError('57014', 'canceling statement due to statement timeout');
+ const { engine } = fakeEngine('postgres', async () => { throw fail; });
+ const cancel = new AbortController();
+ const clock = startClaimPhase(Date.now(), cancel.signal, 10_000);
+ enterClaimStep(clock, 'origin_check', undefined, 'db');
+ const reads = boundedReads(engine, clock);
+ const error = await reads.executeRaw('SELECT id FROM pages').catch(e => e);
+ expect(error).toBeInstanceOf(PreparationDeadlineError);
+ expect(error).toMatchObject({ code: 'preparation_deadline', step: 'origin_check', sqlstate: '57014' });
+ expect(error.message).toContain('step origin_check');
+ expect(preparationAbortReason(error, cancel.signal)).toBe('preparation_deadline');
+ // A shorter session lock_timeout raised by the same lock wait is the same deadline.
+ fail = pgError('55P03', 'canceling statement due to lock timeout');
+ expect(await reads.executeRaw('SELECT id FROM pages').catch(e => e)).toMatchObject({ code: 'preparation_deadline', sqlstate: '55P03' });
+ // Any other failure is the preparer's own.
+ fail = pgError('42P01', 'relation "pages" does not exist');
+ expect(await reads.executeRaw('SELECT id FROM pages').catch(e => e)).toBe(fail);
+ expect(isStatementTimeout(fail)).toBe(false);
+ // The budget passed on this side first: the error is the abort reason the consumer already knows.
+ fail = pgError('57014', 'canceling statement due to statement timeout');
+ cancel.abort({ code: 'group_member_waiting' });
+ expect(await reads.executeRaw('SELECT id FROM pages').catch(e => e)).toEqual({ code: 'group_member_waiting' });
+});
+
+test('a group\'s shared read answers a bounded read once, with the member\'s bound and signal dropped', async () => {
+ const STABLE = 'SELECT local_path FROM sources WHERE id=$1';
+ const { engine, calls } = fakeEngine('postgres', async () => [{ local_path: '/brain' }]);
+ const shared = preparationReads(engine);
+ const a = startClaimPhase(Date.now(), new AbortController().signal, 10_000), b = startClaimPhase(Date.now(), new AbortController().signal, 10_000);
+ const [readA, readB] = await Promise.all([boundedReads(shared, a).executeRaw(STABLE, ['default']), boundedReads(shared, b).executeRaw(STABLE, ['default'])]);
+ expect(readA).toEqual([{ local_path: '/brain' }]);
+ expect(readB).toEqual([{ local_path: '/brain' }]);
+ expect(calls).toEqual([{ sql: STABLE, opts: undefined }]);
+ // An unmemoized read keeps its own bound.
+ await boundedReads(shared, a).executeRaw('SELECT id FROM pages WHERE source_id=$1', ['default']);
+ expect(calls[1]!.opts!.timeoutMs).toBeGreaterThan(0);
+ expect(calls[1]!.opts!.signal).toBe(a.signal);
+});
diff --git a/test/persistence-consumer-scheduling.test.ts b/test/persistence-consumer-scheduling.test.ts
index 66b102db27..ae6dd01103 100644
--- a/test/persistence-consumer-scheduling.test.ts
+++ b/test/persistence-consumer-scheduling.test.ts
@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { ABANDONED_STOP_GRACE_MS, PersistenceConsumer } from '../src/core/persistence/consumer.ts';
+import { PreparationDeadlineError } from '../src/core/persistence/bounded-reads.ts';
import { resetWriteSwitches } from '../src/core/persistence/switches.ts';
import { admitWrite, getWriteRequestById, WRITE_PROGRESS_SQL } from '../src/core/persistence/journal.ts';
import { cancelWriteRequest } from '../src/core/persistence/control.ts';
@@ -349,6 +350,39 @@ test('the release that brings the counter to the limit finishes the request fail
} finally { await disposePersistenceConsumer(engine); await consumer.stop(); }
}), 10_000);
+/**
+ * #6278 (plan item 1.4): a bounded read the server ended inside the budget (a session `lock_timeout` shorter than the budget)
+ * reports the deadline itself. Protects: the consumer handles it as the deadline, never as the preparer's own failure: the
+ * claim is released `preparation_deadline` and charged, the release that reaches the limit finishes the request
+ * `failed`/`preparation_stalled`, and no `storage_error` receipt is written. Fails when the catch path releases it uncharged
+ * (`consumer_stopping`) or writes a terminal receipt from the raw error.
+ */
+test('a server-reported deadline inside the budget is a charged preparation_deadline release, then preparation_stalled at the limit (#6278)', async () => withEnv(env, async () => {
+ const sources = await fixtures(engine, config);
+ const row = await admitWrite(engine, admission(config, sources[0], 'server-deadline/foreground', 'bounded body'));
+ let attempts = 0;
+ const second = Promise.withResolvers<void>();
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_e, _current, _c, _signal, clock) => {
+ if (++attempts === 2) await second.promise;
+ if (clock) clock.step = 'origin_check';
+ throw new PreparationDeadlineError('origin_check', '55P03', Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' }));
+ }, { hostId: config.hostId, pollMs: 20, preparationMs: 5_000, preparationBudgets: { maxAttempts: 2 }, onError: () => {} });
+ try {
+ consumer.start();
+ // The first attempt's release was charged (inside the budget, so only the error could have reported the deadline).
+ await waitFor(() => attempts === 2, { timeoutMs: 3_000 });
+ expect(await getWriteRequestById(engine, row.id)).toMatchObject({ state: 'running', preparation_attempts: 1 });
+ second.resolve();
+ const waited = await awaitWrite(engine, row, { engine: 'pglite' }, { waitMs: 5_000 });
+ expect(waited.kind).toBe('terminal');
+ expect(waited.row).toMatchObject({ state: 'failed', error_code: 'preparation_stalled', preparation_attempts: 2 });
+ expect(waited.row.error_message).toContain('step origin_check');
+ expect(attempts).toBe(2);
+ expect(await engine.readPageSnapshot(row.slug, { sourceId: row.source_id })).toBeNull();
+ await assertConservation(engine);
+ } finally { second.resolve(); await disposePersistenceConsumer(engine); await consumer.stop(); }
+}), 10_000);
+
test('a stopping consumer gives abandoned preparations a bounded grace instead of waiting forever (#6278)', async () => withEnv(env, async () => {
const sources = await fixtures(engine, config);
const row = await admitWrite(engine, admission(config, sources[0], 'stop/abandoned', 'abandoned body'));