Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): idle probe lane uses the ordinary pool; log the redacted error (#5233)
garrytaneb809b0f2285
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 4c25404c4c..32b533e4e8 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -577,6 +577,19 @@ checkpoint did not advance. The message names both errors (redacted, at most200 characters each). Fix the cause they name, then run`gbrain backfill <kind> --resume`.+<a id="persistence-consumer-log"></a>**`[persistence] phase=<phase> reason=<code>`**+(stderr). The resident write consumer could not finish a phase. `reason` is+the SQLSTATE (for example `53300` when a pooler's client limit is reached),+a write-error code, `storage_error`, or `deadline_exceeded` when the phase+overran its five-second budget. `message` is the redacted error text, one line,+at most 200 characters. Unfinished work stays tracked and is retried; nothing+is lost. Run `gbrain sources writer status --json` to see what is waiting. The+line is rate-limited (one per second, one per phase and code every 30 seconds).+An idle consumer keeps one ordinary-pool connection for its work probe and+never holds a direct or session-pooler connection, so a+`GBRAIN_DIRECT_DATABASE_URL` that points at a session pooler is not pinned by+idle `gbrain serve` processes.+## JSONB writes: never double-encodeWriting a JS value into a `jsonb` column has exactly two correct forms. Get thisdiff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 77e36089e9..650311398c 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -37,7 +37,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget.- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.-- `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. 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 (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. 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, 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`, `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`.+- `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. 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, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`). 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, 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`.- `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/engine.ts b/src/core/engine.tsindex 0a2378553c..9f96baf528 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -766,9 +766,9 @@ export interface BrainEngine {/*** Run `fn` with a dedicated connection (Postgres: reserved backend;* PGLite: pass-through). See `ReservedConnection` for semantics and- * usage constraints. Release is automatic.+ * usage constraints. Release is automatic. `route: 'ordinary'` skips the direct route.*/- withReservedConnection<T>(fn: (conn: ReservedConnection) => Promise<T>): Promise<T>;+ withReservedConnection<T>(fn: (conn: ReservedConnection) => Promise<T>, opts?: { route?: 'ordinary' }): Promise<T>;// Pages CRUD/**diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex d99307321c..9546705db2 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -10,6 +10,14 @@ import { publicationConcurrency } from './pool-capacity.ts';import { runPersistenceEffects } from './effects.ts';import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { isWriteErrorCode } from './types.ts';+import { redactConnectionInfo } from '../audit/redact-connection-info.ts';++/** #5233: one-line, redacted, length-capped error text for the consumer's stderr line. */+function errorDetail(error: unknown): string | undefined {+ const message = (error as { message?: unknown } | null)?.message;+ if (typeof message !== 'string' || !message.trim()) return undefined;+ return redactConnectionInfo(message).replace(/\s+/g, ' ').replaceAll('"', "'").trim().slice(0, 200);+}/*** #5401: one resident projection invocation takes up to this many pages and@@ -142,7 +150,8 @@ export class PersistenceConsumer {* probe every few seconds would keep ceil(idle_timeout / interval) sockets* alive. Idle probes therefore share one reserved connection; the rest of* the pool drains through idle_timeout. Pools too small to spare a long-hold- * permit fall back to pooled probes.+ * permit fall back to pooled probes. The lane always comes from the ordinary+ * pool, never the direct/session route, whose clients are scarcer (#5233).*/private async acquireIdleLane(signal?: AbortSignal): Promise<ReservedConnection | undefined> {if (this.idleLane) return this.idleLane.conn;@@ -152,7 +161,7 @@ export class PersistenceConsumer {if (!pool?.poolMax || pool.poolMax < 3 || Object.values(pool.tracked).some(count => count > 0)) return undefined;const held = Promise.withResolvers<void>();const reserved = Promise.withResolvers<ReservedConnection>();- const done = this.engine.withReservedConnection(async conn => { reserved.resolve(conn); await held.promise; })+ const done = this.engine.withReservedConnection(async conn => { reserved.resolve(conn); await held.promise; }, { route: 'ordinary' }).catch(error => { reserved.reject(error); });const aborted = Promise.withResolvers<undefined>();const onAbort = () => aborted.resolve(undefined);@@ -364,14 +373,15 @@ export class PersistenceConsumer {this.lastError = { code: typeof code === 'string' && (/^[A-Z0-9]{5}$/.test(code) || isWriteErrorCode(code)) ? code : 'storage_error', at: new Date().toISOString(),...(this.lastPhaseError ? { phase: this.lastPhaseError } : {}) };if (this.opts.onError) this.opts.onError(error);- else this.log(this.lastPhaseError ?? 'execution', this.lastError.code);+ else this.log(this.lastPhaseError ?? 'execution', this.lastError.code, errorDetail(error));this.lastPhaseError = undefined;}- private log(phase: string, code: string): void {+ private log(phase: string, code: string, detail?: string): void {const key = `${phase}:${code}`, at = Date.now();if (this.lastLog && (at - this.lastLog.at < 1000 || this.lastLog.key === key && at - this.lastLog.at < 30_000)) return;this.lastLog = { key, at };- if (!this.opts.onError) process.stderr.write(`[persistence] phase=${phase} reason=${code}; unfinished work remains tracked; inspect writer status.\n`);+ if (!this.opts.onError) process.stderr.write(`[persistence] phase=${phase} reason=${code}${detail ? ` message="${detail}"` : ''}`+ + '; unfinished work remains tracked; fix: gbrain sources writer status --json; docs: docs/ENGINES.md#persistence-consumer-log\n');}private async execute(row: WriteRequest): Promise<boolean> {let renewing: Promise<unknown> | undefined;diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 274a37f5c4..a199c9dd86 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -617,10 +617,10 @@ export class PostgresEngine implements BrainEngine {}/** Long holds share a budget across every engine that uses the same physical pool. */- async withReservedConnection<T>(fn: (conn: ReservedConnection) => Promise<T>): Promise<T> {+ async withReservedConnection<T>(fn: (conn: ReservedConnection) => Promise<T>, opts?: { route?: 'ordinary' }): Promise<T> {let pool = this.sql;let releasePermit: (() => void) | null = null;- if (!this._pageTransaction && this.connectionManager?.isDualPoolActive()) {+ if (!this._pageTransaction && opts?.route !== 'ordinary' && this.connectionManager?.isDualPoolActive()) {try {const direct = await this.connectionManager.ddl();releasePermit = tryAcquirePoolLongHold(direct, this.connectionManager.describeMode().direct_pool_size ?? DEFAULT_DIRECT_POOL_SIZE);diff --git a/test/e2e/persistence-idle-pool.test.ts b/test/e2e/persistence-idle-pool.test.tsindex 694b633765..7f25ee96a8 100644--- a/test/e2e/persistence-idle-pool.test.ts+++ b/test/e2e/persistence-idle-pool.test.ts@@ -125,6 +125,46 @@ describe.skipIf(!direct)('idle persistence consumer on PostgreSQL', () => {}, 120_000);});+describe.skipIf(!direct)('#5233 idle lane with a direct/session route configured', () => {+ test('an idle consumer holds an ordinary-pool connection and opens no direct-route connection', async () => {+ const db = await scratchDatabase(direct!, direct!);+ const directRoute = new URL(db.url);+ directRoute.searchParams.set('application_name', 'gbrain_5233_direct_route');+ try {+ await withEnv({ GBRAIN_DIRECT_DATABASE_URL: directRoute.toString() }, () => withConsumer(db.url, async engine => {+ expect(engine.connectionManager?.isDualPoolActive()).toBe(true);+ await Bun.sleep(IDLE_DRAIN_MS);+ const rows = await db.admin.unsafe<{ direct: number; total: number }[]>(`SELECT+ count(*) FILTER (WHERE application_name = 'gbrain_5233_direct_route')::int AS direct, count(*)::int AS total+ FROM pg_stat_activity WHERE datname = $1`, [db.name]);+ expect(rows[0]).toEqual({ direct: 0, total: 1 });+ }));+ } finally { await db.drop(); }+ }, 120_000);++ test('a partly busy pool skips the idle reservation and still publishes writes', async () => {+ const db = await scratchDatabase(direct!, direct!);+ try {+ await withConsumer(db.url, async (engine, consumer, config) => {+ const sources = await fixtures(engine, config);+ const release = Promise.withResolvers<void>();+ let held = 0;+ const holding = Array.from({ length: 2 }, () => engine.transaction(async tx => {+ await tx.executeRaw('SELECT 1'); held++; await release.promise;+ }));+ try {+ await waitFor(() => held === 2);+ await consumer.tick();+ const write = await admitWrite(engine, admission(config, sources[0], 'idle/busy-pool', 'busy body'));+ consumer.wake();+ await waitFor(async () => (await getWriteRequestById(engine, write.id))?.state === 'committed', { timeoutMs: 10_000 });+ expect(engine.getPoolDiagnostics()?.tracked.reserved).toBe(0);+ } finally { release.resolve(); await Promise.all(holding); }+ });+ } finally { await db.drop(); }+ }, 120_000);+});+describe.skipIf(!(pooled && pooledAdmin) || !existsSync('/proc/self/net/tcp'))('idle persistence consumer behind transaction-mode PgBouncer', () => {test('an idle consumer drains its pooler client pool to one connection without LISTEN', async () => {const db = await scratchDatabase(pooledAdmin!, pooled!);diff --git a/test/persistence-consumer-log.test.ts b/test/persistence-consumer-log.test.tsnew file mode 100644index 0000000000..c76209948b--- /dev/null+++ b/test/persistence-consumer-log.test.ts@@ -0,0 +1,54 @@+/**+ * The resident consumer's stderr line is the only trace an operator gets when+ * a phase fails or overruns. #5233: the line carried only an error code, so a+ * pooler's "max clients reached" was invisible. It now carries a redacted,+ * one-line, length-capped message, a fix command and a docs anchor.+ *+ * Regression that fails it: dropping the message (or the redaction) from the+ * line. Existing coverage asserts consumer state, not this line.+ */+import { afterEach, describe, expect, spyOn, test } from 'bun:test';+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';+import type { BrainEngine } from '../src/core/engine.ts';++const stderr: string[] = [];+let spy: ReturnType<typeof spyOn> | undefined;+afterEach(() => { spy?.mockRestore(); spy = undefined; stderr.length = 0; });++function captureStderr() {+ spy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => {+ stderr.push(String(chunk));+ return true;+ }) as typeof process.stderr.write);+}++function failingEngine(error: Error): BrainEngine {+ return new Proxy({ kind: 'pglite' } as Record<string, unknown>, {+ get(target, prop) {+ if (prop in target) return target[prop as string];+ if (prop === 'then') return undefined;+ return async () => { throw error; };+ },+ }) as unknown as BrainEngine;+}++describe('persistence consumer stderr line', () => {+ test('#5233: carries the SQLSTATE and a redacted, capped, one-line message', async () => {+ const error = Object.assign(new Error(+ '(EMAXCONNSESSION) max clients reached in session mode\n - pool_size: 15 for postgresql://writer:[email protected]:5432/postgres '+ + 'x'.repeat(400)), { code: '53300' });+ captureStderr();+ const consumer = new PersistenceConsumer(failingEngine(error), { engine: 'pglite' }, async () => { throw error; }, { hostId: crypto.randomUUID() });+ try { await consumer.tick(); } finally { await consumer.stop(); }+ const line = stderr.find(entry => entry.startsWith('[persistence] phase='));+ expect(line).toBeDefined();+ expect(line).toContain('reason=53300');+ expect(line).toContain('message="(EMAXCONNSESSION) max clients reached in session mode - pool_size: 15 for ');+ expect(line).not.toContain('secret-pw');+ expect(line).toContain('fix: gbrain sources writer status --json');+ expect(line).toContain('docs: docs/ENGINES.md#persistence-consumer-log');+ const message = /message="([^"]*)"/.exec(line!)![1];+ expect(message.length).toBeLessThanOrEqual(200);+ expect(line!.trimEnd().includes('\n')).toBe(false);+ });+});