Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): publication deadline aborts the publish transaction via #6443's signal (#6288)
time-attack741122b43ee9
diff --git a/src/core/persistence/publication-deadline.ts b/src/core/persistence/publication-deadline.tsindex 44650cf95b..24aa94f3ba 100644--- a/src/core/persistence/publication-deadline.ts+++ b/src/core/persistence/publication-deadline.ts@@ -9,12 +9,12 @@* transaction-scoped, so they hold behind a transaction pooler that drops startup parameters.* - `boundPublication` never settles before the publish does, so nothing releases or reports a request or group while* its transaction can still commit. At the ceiling it marks the publication overdue (the claim stamp reads- * `waiting_on: publication_deadline`); a grace later it aborts the publication's signal, which reaches the transaction- * only on an engine whose `transaction(fn, { signal })` accepts one (GBRA-76's primitive; ignored until then); if the- * publish still has not settled shortly after, the owner reports `restart_required`. The root stays held: restarting+ * `waiting_on: publication_deadline`); a grace later it aborts the publication's signal, passed to `transaction(fn, { signal })`:+ * on Postgres that discards the transaction's connection and the publish rejects with an AbortError (nothing commits);+ * if the publish still has not settled shortly after, the owner reports `restart_required`. The root stays held: restarting* the owner process is the only honest recovery, never a promised reclaim.- * - On PGLite nothing below the publish can be cancelled: the ceiling only marks the publication overdue and, past the- * grace, `restart_required`.+ * - On PGLite a running transaction cannot be cancelled (the signal is checked only before BEGIN): the ceiling only marks+ * the publication overdue and, past the grace, `restart_required`.** The wave 9 yield between groups is outside any one `boundPublication` call, so it never counts against a group.*/@@ -57,11 +57,25 @@ export async function bindPublicationTimeouts(tx: BrainEngine): Promise<void> {await tx.executeRaw("SELECT set_config('idle_in_transaction_session_timeout',$1,true)", [`${publicationIdleTimeoutMs()}ms`]);}-/** `engine.transaction`, passing the current publication's signal on as `{ signal }` (an engine without the option ignores it). */-export function publicationTransaction<T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {+/**+ * `engine.transaction`, passing the current publication's signal on as `{ signal }`. An aborted transaction rejects+ * while its body may still be parked, so a rejection waits for the body to settle first: nothing (recovery included)+ * acts on the publication while the body can still rename a file.+ */+export async function publicationTransaction<T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {const signal = signals.getStore();- const run = engine.transaction as (this: BrainEngine, fn: (tx: BrainEngine) => Promise<T>, opts?: { signal?: AbortSignal }) => Promise<T>;- return run.call(engine, fn, signal ? { signal } : undefined);+ if (!signal) return engine.transaction(fn);+ let body: Promise<unknown> = Promise.resolve();+ try {+ return await engine.transaction(tx => { const run = fn(tx); body = run; return run; }, { signal });+ } catch (error) {+ await body.then(() => undefined, () => undefined);+ const closed = (error as { cause?: { code?: unknown } })?.cause?.code;+ // The deadline discarded the connection: report it as the closed connection it is, which callers already retry.+ if (!signal.aborted || typeof closed !== 'string') throw error;+ throw Object.assign(new Error(`publication_deadline: the publish transaction passed the ceiling and its connection was discarded (${closed})`),+ { name: 'PublicationDeadlineError', code: closed, cause: error });+ }}export interface PublicationBound {diff --git a/test/persistence-publication-deadline.test.ts b/test/persistence-publication-deadline.test.tsindex 3ad05dbe9e..35c7d7a1ab 100644--- a/test/persistence-publication-deadline.test.ts+++ b/test/persistence-publication-deadline.test.ts@@ -112,23 +112,36 @@ for (const kind of testBackends()) {return { row, binding, prepared: await preparePageMutation(engine, row, context().config) };}for (const boundary of ['before_publication', 'after_publication', 'before_commit'] as const) {- test(`a publish held at ${boundary} past the ceiling is reported overdue and stuck, never settled early; released, it commits once`, async () => withEnv({ GBRAIN_HOME: home }, async () => {+ test(`a publish held at ${boundary} past the ceiling is reported overdue and stuck, never settled early; released, it commits once (on Postgres after the aborted attempt is requeued)`, async () => withEnv({ GBRAIN_HOME: home }, async () => {const slug = `notes/held-${boundary.replaceAll('_', '-')}`;const { row, prepared } = await claimedPut(slug);let open!: () => void;const barrier = new Promise<void>(resolve => { open = resolve; });+ let reached!: () => void;+ const atBarrier = new Promise<void>(resolve => { reached = resolve; });const events: string[] = [];- const work = boundPublication(() => publishMutation(engine, row, prepared, localHostId(), { boundary: async name => { if (name === boundary) await barrier; } }),- { ceilingMs: 30, graceMs: 30, settleMs: 30, onOverdue: () => events.push('overdue'), onStuck: () => events.push('stuck') });+ // The ceiling leaves the publish time to reach its barrier, so the abort always lands on a body parked there.+ const work = boundPublication(() => publishMutation(engine, row, prepared, localHostId(), { boundary: async name => { if (name === boundary) { reached(); await barrier; } } }),+ { ceilingMs: 1500, graceMs: 30, settleMs: 30, onOverdue: () => events.push('overdue'), onStuck: () => events.push('stuck') });let settled = false;void work.then(() => { settled = true; }, () => { settled = true; });- await tick(150);+ await atBarrier;+ expect(events).toEqual([]);+ await tick(1700);expect(events).toEqual(['overdue', 'stuck']);expect(settled).toBe(false);// PGLite has one connection, held by the open publish transaction: a read there would wait behind it.if (kind === 'postgres') expect((await getWriteRequestById(engine, row.id))?.state).toBe('running');open();- const done = await work;+ let done = await work;+ if (kind === 'postgres') {+ // The signal discarded the transaction's connection: nothing committed, and the claim went back to the queue.+ expect(done.state).toBe('queued');+ expect(await engine.getPage(slug, { sourceId: 'default' })).toBeNull();+ const again = (await claimNextWrite(engine, localHostId()))!;+ expect(again.id).toBe(row.id);+ done = await publishMutation(engine, again, await preparePageMutation(engine, again, context().config), localHostId());+ }expect(done.state).toBe('committed');const [count] = await engine.executeRaw<{ n: number | string }>("SELECT count(*) AS n FROM persistence_requests WHERE id=$1::uuid AND state='committed'", [row.id]);expect(Number(count!.n)).toBe(1);