Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): await the publication timeout bind; PgBouncer twin (#6288, GBRA-75 review)
time-attacke89e276612a5
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 7697a479a2..8242ae3c3b 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -345,7 +345,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prawait hooks.boundary?.('prepared', row);}const done = await publicationTransaction(engine, async tx => {- bindPublicationTimeouts(tx);+ await bindPublicationTimeouts(tx);await declareDurablePersistence(tx);const liveBinding = await guardOwnership(tx, row, hostId);if (prepared.sourceExclusive && !prepared.exclusiveSources?.length) await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [row.source_id]);diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex 1b0c104af5..c8d14f1cfe 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -262,7 +262,6 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr}if (lane) await awaitLaneBegin(lane, rows);const done = await transaction(async opened => {- bindPublicationTimeouts(opened);timed.apply?.end(rows.length);if (lane) timed.apply = laneApplyBegin(lane);const tx = groupReads(opened);@@ -273,6 +272,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prconst keys = rows.flatMap((row, i) => [{ sourceId: row.source_id, slug: row.slug, incarnation: row.source_incarnation },...(prepared[i]!.additionalPageKeys ?? []).map(key => key.sourceId === row.source_id ? { ...key, incarnation: row.source_incarnation } : key)]);const ready = pipelined(tx, [+ () => bindPublicationTimeouts(opened),() => declareDurablePersistence(tx),() => guardOwnership(tx, head, hostId),// A published file needs recovery even if this transaction rolls back; claims are verified first.@@ -284,7 +284,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr() => prepared.some(member => member.file && !member.noop) ? tx.executeRaw(HOST_BINDING_SQL, [head.worktree_id]) : Promise.resolve([]),...storedAuthorizationReads(tx, rows, true),]).then(results => {- const [, live, started, readOnly] = results as [unknown, Awaited<ReturnType<typeof guardOwnership>>, unknown[], boolean];+ const [, , live, started, readOnly] = results as [unknown, unknown, Awaited<ReturnType<typeof guardOwnership>>, unknown[], boolean];if (String(live?.owner_epoch) !== String(binding.owner_epoch)) throw new OperationError('owner_unavailable', 'Owner epoch changed before publication.', 'Inspect the source owner with gbrain sources writer status; do not claim or transfer the source to push this write.');if (started.length !== members.length) throw new OperationError('write_claim_lost', 'Execution claim changed before publication.', 'Another worker holds the request; inspect it rather than resubmitting.');// A file target prepared before the source became a read-only mirror is never published (as in publishMutation, noop included).diff --git a/src/core/persistence/publication-deadline.ts b/src/core/persistence/publication-deadline.tsindex 863d495ca3..44650cf95b 100644--- a/src/core/persistence/publication-deadline.ts+++ b/src/core/persistence/publication-deadline.ts@@ -48,14 +48,13 @@ export function publicationIdleTimeoutMs(ceilingMs = ceiling.value): number {}/**- * Sets the transaction-local idle bound as the transaction's first statement. Not awaited: postgres.js sends it ahead of- * the caller's next statement on the same connection (the `pipelined` contract), so it costs no round trip; a failure- * surfaces on the statements after it. Skipped on PGLite: it would enforce the bound, and a transaction it ends there- * wedges the engine's only connection.+ * Sets the transaction-local idle bound. Callers await it (or send it first in their `pipelined` batch), so a refused SET+ * fails this publication's transaction with its own error. Skipped on PGLite: it would enforce the bound, and a+ * transaction it ends there wedges the engine's only connection.*/-export function bindPublicationTimeouts(tx: BrainEngine): void {+export async function bindPublicationTimeouts(tx: BrainEngine): Promise<void> {if (tx.kind !== 'postgres') return;- tx.executeRaw("SELECT set_config('idle_in_transaction_session_timeout',$1,true)", [`${publicationIdleTimeoutMs()}ms`]).catch(() => undefined);+ 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). */diff --git a/test/e2e/publication-deadline-pgbouncer.test.ts b/test/e2e/publication-deadline-pgbouncer.test.tsnew file mode 100644index 0000000000..184792e342--- /dev/null+++ b/test/e2e/publication-deadline-pgbouncer.test.ts@@ -0,0 +1,70 @@+/**+ * #6288 / #6352 (P2.3) behind transaction-mode PgBouncer, the pooler that drops gbrain's startup+ * `idle_in_transaction_session_timeout` (docker-compose.ci.yml IGNORE_STARTUP_PARAMETERS). The publish transaction's own+ * transaction-local bound still applies there: a publisher idle past it is ended by the server, nothing it wrote commits,+ * and because Postgres ends the whole session (the pooler's server connection), the transaction promise rejects even+ * while the body is still parked, the pool reconnects, and the next transaction runs. Skipped without the CI PgBouncer fixture (GBRAIN_PGBOUNCER_URL / GBRAIN_PGBOUNCER_DIRECT_URL).+ */+import { afterAll, beforeAll, 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 { bindPublicationTimeouts, publicationTransaction } from '../../src/core/persistence/publication-deadline.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { withEnv } from '../helpers/with-env.ts';++const pooled = process.env.GBRAIN_PGBOUNCER_URL;+const direct = process.env.GBRAIN_PGBOUNCER_DIRECT_URL;+const available = Boolean(pooled && direct);+if (process.env.GBRAIN_CI_REQUIRE_PGBOUNCER === '1' && !available) throw new Error('The publication deadline twin requires the configured CI PgBouncer fixture.');+let home: string, database: string;+let admin: ReturnType<typeof postgres> | undefined;+let engine: PostgresEngine | undefined;++beforeAll(async () => {+ if (!available) return;+ assertSafeE2eDatabaseUrl(direct!);+ home = mkdtempSync(join(tmpdir(), 'gbrain-pub-deadline-pooled-'));+ database = `gbrain_test_pub_deadline_${randomUUID().replaceAll('-', '')}`;+ admin = postgres(direct!, { max: 1, prepare: false });+ await admin.unsafe(`CREATE DATABASE ${database}`);+ const url = new URL(pooled!);+ url.pathname = `/${database}`;+ engine = new PostgresEngine();+ await withEnv({ GBRAIN_HOME: home }, async () => { await engine!.connect({ database_url: url.toString(), poolSize: 2 }); await engine!.initSchema(); });+}, 120_000);++afterAll(async () => {+ if (engine) await withEnv({ GBRAIN_HOME: home }, () => engine!.disconnect());+ if (admin) { try { if (database) await admin.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`); } finally { await admin.end(); } }+ if (home) rmSync(home, { recursive: true, force: true });+});++test.skipIf(!available)('the transaction-local idle bound holds behind the pooler; the ended session is replaced and nothing commits', async () => {+ const db = engine!;+ const steps: string[] = [];+ const attempt = publicationTransaction(db, async tx => {+ await bindPublicationTimeouts(tx);+ const [shown] = await tx.executeRaw<{ v: string }>("SELECT current_setting('idle_in_transaction_session_timeout') AS v");+ steps.push(`bound=${shown!.v}`);+ await tx.executeRaw("SELECT set_config('idle_in_transaction_session_timeout','300ms',true)");+ await tx.executeRaw("INSERT INTO config(key,value) VALUES('p23.pooled','x')");+ steps.push('inserted');+ await new Promise(r => setTimeout(r, 1500));+ steps.push('woke');+ await tx.executeRaw('SELECT 1');+ steps.push('after');+ return 'committed';+ });+ const started = Date.now();+ await expect(attempt).rejects.toBeDefined();+ // The driver rejects the transaction when the server ends the session, while the body is still parked in its sleep.+ expect(Date.now() - started).toBeLessThan(1500);+ expect(steps).toEqual(['bound=5min', 'inserted']);+ const rows = await db.executeRaw<{ n: number | string }>("SELECT count(*) AS n FROM config WHERE key='p23.pooled'");+ expect(Number(rows[0]!.n)).toBe(0);+ expect(await db.transaction(async tx => (await tx.executeRaw<{ one: number }>('SELECT 1 AS one'))[0]!.one)).toBe(1);+}, 60_000);diff --git a/test/persistence-publication-deadline.test.ts b/test/persistence-publication-deadline.test.tsindex b0976d2a4f..3ad05dbe9e 100644--- a/test/persistence-publication-deadline.test.ts+++ b/test/persistence-publication-deadline.test.ts@@ -22,6 +22,7 @@ import { localHostId } from '../src/core/persistence/identity.ts';import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';import { preparePageMutation } from '../src/core/persistence/page-prepare.ts';import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { publishSingleWrite } from '../src/core/persistence/group-publish.ts';import { bindPublicationTimeouts, boundPublication, publicationIdleTimeoutMs, publicationTransaction, PUBLICATION_CEILING_DEFAULT_MS } from '../src/core/persistence/publication-deadline.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';@@ -156,10 +157,36 @@ for (const kind of testBackends()) {expect(signals.some(signal => signal instanceof AbortSignal)).toBe(true);}), 120_000);+ for (const path of kind === 'postgres' ? ['publishMutation', 'publishSingleWrite'] as const : ['publishMutation'] as const)+ test(`a refused timeout bind fails the publication inside its own transaction, with no unhandled rejection, and leaves no page (${path})`, async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const slug = `notes/bind-refused-${path.toLowerCase()}`;+ const { row, prepared } = await claimedPut(slug);+ const unhandled: unknown[] = [];+ const onUnhandled = (reason: unknown) => { unhandled.push(reason); };+ process.on('unhandledRejection', onUnhandled);+ try {+ const refusing = new Proxy(engine, { get(target, key) {+ if (key === 'transaction') return <T>(fn: (tx: BrainEngine) => Promise<T>) => target.transaction(tx => fn(new Proxy(tx, { get(t, k) {+ if (k === 'kind') return 'postgres';+ if (k === 'executeRaw') return (sql: string, ...rest: unknown[]) => sql.includes('idle_in_transaction_session_timeout')+ ? Promise.reject(Object.assign(new Error('SET refused by the pooler'), { code: '0A000' })) : (t.executeRaw as (...a: unknown[]) => unknown)(sql, ...rest);+ const member = Reflect.get(t, k, t); return typeof member === 'function' ? member.bind(t) : member;+ } })));+ const member = Reflect.get(target, key, target); return typeof member === 'function' ? member.bind(target) : member;+ } }) as BrainEngine;+ const outcome = await (path === 'publishMutation' ? publishMutation(refusing, row, prepared, localHostId()) : publishSingleWrite(refusing, row, prepared, localHostId())).then(done => ({ done }), error => ({ error }));+ await tick(50);+ expect(unhandled).toEqual([]);+ if ('done' in outcome) expect(outcome.done.state).not.toBe('committed');+ else expect(String((outcome.error as Error).message)).toContain('SET refused');+ expect(await engine.getPage(slug, { sourceId: 'default' })).toBeNull();+ } finally { process.off('unhandledRejection', onUnhandled); }+ }), 120_000);+test(kind === 'postgres' ? 'a publish transaction idle past its bound is ended by the server and commits nothing' : 'PGLite: the idle bound is never applied (an ended idle transaction would wedge its only connection)', async () => {const before = await engine.executeRaw<{ n: number | string }>("SELECT count(*) AS n FROM config WHERE key='p23.probe'");const attempt = publicationTransaction(engine, async tx => {- bindPublicationTimeouts(tx);+ await bindPublicationTimeouts(tx);const [shown] = await tx.executeRaw<{ v: string }>("SELECT current_setting('idle_in_transaction_session_timeout') AS v");// PGLite would enforce the bound too, and an idle transaction it ends wedges its only connection, so it is never set there.expect(shown!.v === '0').toBe(kind !== 'postgres');