Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): a bounded read issued past its preparation deadline is refused before it is sent

garrytane7908c3027bd
diff --git a/src/core/persistence/bounded-reads.ts b/src/core/persistence/bounded-reads.ts
index 18d1c097d1..e3a5f388e7 100644
--- a/src/core/persistence/bounded-reads.ts
+++ b/src/core/persistence/bounded-reads.ts
@@ -38,11 +38,16 @@ 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. */
+/**
+ * The error a bounded read rejects with at its bound; `code` is what `preparationAbortReason` reads. `sqlstate` is
+ * null when the read was refused before it was sent because the budget had already run out.
+ */
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 });
+ constructor(readonly step: string | null, readonly sqlstate: string | null, cause?: unknown) {
+ super(sqlstate
+ ? `The preparation read${step ? ` at step ${step}` : ''} did not finish within its budget (the server ended it, SQLSTATE ${sqlstate}).`
+ : `The preparation read${step ? ` at step ${step}` : ''} was not sent: its budget had already run out.`, { cause });
this.name = 'PreparationDeadlineError';
}
}
@@ -67,6 +72,11 @@ export function boundedReads(engine: BrainEngine, clock: ClaimPhaseClock | undef
if (key === 'executeRaw') return async (sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number }) => {
recordClaimSql(clock, sql);
if (opts?.signal) return target.executeRaw(sql, params, opts);
+ // A read issued past the deadline is refused here: sent with the 1 ms floor, a fast one would finish and the deadline would go unseen.
+ if (Date.now() >= deadlineAt) {
+ if (clock!.signal?.aborted) throw clock!.signal.reason;
+ throw new PreparationDeadlineError(clock!.step, null);
+ }
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 } : {}) });
diff --git a/test/page-purge-journal-timeout-6511.test.ts b/test/page-purge-journal-timeout-6511.test.ts
index bd6147bd1a..809212b3ea 100644
--- a/test/page-purge-journal-timeout-6511.test.ts
+++ b/test/page-purge-journal-timeout-6511.test.ts
@@ -240,17 +240,25 @@ for (const backend of backends) describe(`[${backend}] #6511 page purge journal
if (backend === 'postgres') test('[R1 b] on Postgres a bounded chunk read the server ends is the same deadline', async () => {
await seed('bounded');
- await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,intent,authority,state,
- intent_bytes,terminal_reservation,outcome,completed_at)
- SELECT 'local_cli','seed-bounded',gen_random_uuid(),'put_page','default',(SELECT incarnation FROM sources WHERE id='default'),'bounded/row-'||g,'d',
- jsonb_build_object('content',repeat('filler text ',200)),'{}'::jsonb,'committed',0,0,'{}'::jsonb,now() FROM generate_series(1,4000) g`);
- const clock = startClaimPhase(Date.now(), undefined, 1);
- const bounded = boundedReads(engine, clock);
- const error = await sweepRequestsCarrying(bounded, 'default', [CLAIM], { now: () => 0 }).then(() => null, (e: unknown) => e);
+ // Another session holds the journal, so the chunk read is sent inside its budget and waits until the server ends
+ // it at the bound. (A budget that has already run out is refused before the read is sent: the next test.)
+ const error = await engine.transaction(async tx => {
+ await tx.executeRaw('LOCK TABLE persistence_requests IN ACCESS EXCLUSIVE MODE');
+ const bounded = boundedReads(engine, startClaimPhase(Date.now(), undefined, 300));
+ return sweepRequestsCarrying(bounded, 'default', [CLAIM], { now: () => 0 }).then(() => null, (e: unknown) => e);
+ });
expect(error).toBeInstanceOf(PreparationDeadlineError);
expect((error as PreparationDeadlineError).code).toBe('preparation_deadline');
expect((error as PreparationDeadlineError).sqlstate).toBe('57014');
- await engine.executeRaw("DELETE FROM persistence_requests WHERE principal_id='seed-bounded'");
+ }, 60_000);
+
+ if (backend === 'postgres') test('[R1 b] on Postgres a chunk read issued after the deadline is the deadline, however fast the read would be', async () => {
+ await seed('late');
+ const bounded = boundedReads(engine, startClaimPhase(Date.now() - 5_000, undefined, 1_000));
+ const error = await sweepRequestsCarrying(bounded, 'default', [CLAIM], { now: () => 0 }).then(() => null, (e: unknown) => e);
+ expect(error).toBeInstanceOf(PreparationDeadlineError);
+ expect((error as PreparationDeadlineError).code).toBe('preparation_deadline');
+ expect((error as PreparationDeadlineError).sqlstate).toBeNull();
}, 60_000);
test('[R2] a carrying request admitted and cancelled after the preparation scan is redacted by the tail re-check; one still queued is left in place', async () => {
diff --git a/test/persistence-bounded-reads.test.ts b/test/persistence-bounded-reads.test.ts
index 0c65c95318..4de45cc710 100644
--- a/test/persistence-bounded-reads.test.ts
+++ b/test/persistence-bounded-reads.test.ts
@@ -46,6 +46,23 @@ test('a raw statement runs with the remaining budget and the clock\'s signal; a
expect(typeof reads.getConfig).toBe('function');
});
+test('a read issued after the deadline is refused before it is sent: the deadline, never a fast read that finished inside the 1 ms floor', async () => {
+ const { engine, calls } = fakeEngine('postgres', async () => [{ ok: true }]);
+ const clock = startClaimPhase(Date.now() - 5_000, undefined, 1_000);
+ enterClaimStep(clock, 'journal_sweep');
+ const error = await boundedReads(engine, clock).executeRaw('SELECT 1 FROM persistence_requests').then(() => null, (e: unknown) => e);
+ expect(error).toBeInstanceOf(PreparationDeadlineError);
+ expect(preparationAbortReason(error)).toBe('preparation_deadline');
+ expect((error as PreparationDeadlineError).sqlstate).toBeNull();
+ expect((error as PreparationDeadlineError).message).toContain('at step journal_sweep was not sent');
+ expect(calls).toHaveLength(0);
+ const cancel = new AbortController();
+ const aborted = startClaimPhase(Date.now() - 5_000, cancel.signal, 1_000);
+ cancel.abort(new Error('claim released'));
+ await expect(boundedReads(engine, aborted).executeRaw('SELECT 1 FROM persistence_requests')).rejects.toThrow('claim released');
+ expect(calls).toHaveLength(0);
+});
+
test('without a deadline, or on PGLite, the view is the engine itself', () => {
const { engine } = fakeEngine('postgres', async () => []);
expect(boundedReads(engine, undefined)).toBe(engine);