Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(db): honour connect_timeout from database_url (#5945)
time-attackb453863086b2
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex 89aec6de2d..aeb23980ce 100644--- a/docs/architecture/key-files/engines-1.md+++ b/docs/architecture/key-files/engines-1.md@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/db-repair-receipts.ts` — the shared seam between `gbrain db-repair` (writer) and doctor's `db_repair_recurrence` check (reader — it must run in doctor's dead-DB filesystem lane, exactly when repairs are repeating). JSONL at `~/.gbrain/db-repair-receipts.jsonl`; row shape `{ts, brain_id, reason, action, outcome: 'applied'|'refused'|'diagnose'}` — only `applied` rows count toward the recurrence threshold (3+ same-reason per brain in 7 days). Redacted before write (the classifier redacts its own copy; actions are fixed strings), fail-open (a receipts problem never blocks a repair), capped at 200 rows ON EVERY WRITE (the recurrence check reads the file on every doctor run — it must not grow unbounded on exactly the machines having chronic problems) — EXCEPT `applied` rows inside an 8-day retention window, which are exempt from the flat cap (separately bounded at 200): a diagnose flood from an agent loop must never evict the cooldown/recurrence memory. The reader is per-line tolerant (one torn row never discards every other receipt). Also owns `rewriteCooldownBlocked` (24h per (reason, action), rewrite tier only).-- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect(config, { onpoisoned })` passes the owner engine's poisoned-discard hook to the singleton pool and returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the CLI teardown contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`.+- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect(config, { onpoisoned })` passes the owner engine's poisoned-discard hook to the singleton pool and returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the CLI teardown contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`. `resolveConnectTimeoutSeconds(url)` — `connect_timeout` for the same four call sites, read from each pool's own URL: a positive integer `?connect_timeout=N` wins, else 10s (an explicit postgres.js option shadows the URL query, so a hardcoded value would discard it). Pinned by `test/db-connect-timeout.test.ts`.- `src/core/degraded-engine.ts` + `src/core/degraded-marker.ts` — degraded-mode serve, STARTUP-SCOPED by design: when Postgres is unreachable at `gbrain serve` startup, serve boots on `createDegradedEngine` (a concrete object whose method set is enumerated from PostgresEngine's prototype at construction — no dynamic `get` trap; `kind` is an explicit getter, read synchronously at ~29 branch sites; `disconnect()` is a no-op while dead so shutdown never triggers a reconnect) instead of dying. Every tool call attempts ONE reconnect (single-flight across concurrent callers, min-interval gated ~5s — no connect storms against a dying pooler); calls inside the window throw the STORED original error (stale-but-honest, refreshed on every real attempt) so MCP dispatch classifies the REAL error shape into the `database_error` envelope + marker. The `reconnect` callback is the FULL deferred connectEngine (config merge, gateway, migrations — guarded in cli.ts: a vanished config.json throws instead of connectEngine's process.exit killing the live server); first success swaps in the live engine permanently and fires recovery callbacks (serve re-runs deferred boot + sends `tools/list_changed` — clients that handshook degraded hold the reduced gate-hidden catalog and must refresh; the callback is a no-op once shutdown has started) — but the TRIGGERING call gets `DegradedRecoveredRetryError`, never a result: its source scope was resolved under the degraded fallback, so one client retry buys scope correctness (no call ever executes under the fallback scope against a live engine). Callers waiting on an in-flight attempt are latency-capped (`callerWaitMs`, default 2s — they get the stored error while the attempt finishes in the background, so a timeout-class failure can't stall the MCP handshake). Prototype GETTERS delegate too (throw the stored error while dead — never a silent `undefined`); `DEGRADED_LAST_ERROR` is a read-only accessor for the stored diagnosis (drives the HTTP `/health` degraded reason without consuming a reconnect). Serve-side degraded posture: source scope honors a validated `GBRAIN_SOURCE` (tier `env`) before seed_default, and `stdioVisibleTools` fail-closes every gated op WITHOUT touching the engine. The degraded gate keys on the RESOLVED brain's engine (a PGLite mount on a postgres host keeps die-on-startup). Mid-session outages ride `PostgresEngine.reconnect()` + per-call classified envelopes — degraded mode adds no mid-session state; PGLite startup failures keep die-on-startup (single-writer lock makes a lazy proxy wrong there; that lane's repair is pglite-repair). Kill switch `GBRAIN_SERVE_DEGRADED=0` (or `false`); structured `[gbrain-serve] DEGRADED/RECOVERED` stderr lines. `degraded-marker.ts` is the dependency-free seam (`Symbol.for`-registered markers + `isEngineDegraded`/`onEngineRecovered`/`degradedLastError`) so server.ts/serve.ts/http-transport.ts can ask about degraded state without importing the heavy Postgres engine module.diff --git a/src/commands/engine-status.ts b/src/commands/engine-status.tsindex 9e4297eac6..4c2d789b88 100644--- a/src/commands/engine-status.ts+++ b/src/commands/engine-status.ts@@ -10,8 +10,8 @@* status call when its DB is down anyway.** Zero round-trips without --probe. With --probe: a SINGLE bounded connect- * (the driver's built-in `connect_timeout: 10` in db.ts — never a custom- * race) + SELECT 1; failures come back as a classified PgAccessDiagnosis,+ * (the pool's `connect_timeout`, 10s unless `database_url` sets one — never+ * a custom race) + SELECT 1; failures come back as a classified PgAccessDiagnosis,* not a raw error. On PGLite the probe is LOCK-AWARE: a live `gbrain serve`* holding the single-writer lock reports `locked_by_serve` (healthy-with-* note) instead of hanging ~30s on the lock and misreporting a broken brain.diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.tsindex 028b4a264c..de3d41b810 100644--- a/src/core/connection-manager.ts+++ b/src/core/connection-manager.ts@@ -38,7 +38,7 @@import postgres from '#postgres'import { traceSqlOptions } from './sql-trace.ts';-import { resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, endPoolBounded } from './db.ts';+import { resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveConnectTimeoutSeconds, endPoolBounded } from './db.ts';import { redactPgUrl } from './url-redact.ts';import { logConnectionEvent } from './connection-audit.ts';@@ -347,7 +347,7 @@ export class ConnectionManager {const opts: Record<string, unknown> = {max: resolvePoolSize(this.opts.readPoolSize),idle_timeout: 20,- connect_timeout: 10,+ connect_timeout: resolveConnectTimeoutSeconds(this.opts.url),// Explicit (matches the postgres.js implicit default; GBRAIN_POOL_MAX_LIFETIME_S overrides).max_lifetime: resolveMaxLifetimeSeconds(),types: { bigint: postgres.BigInt },@@ -495,7 +495,7 @@ export class ConnectionManager {const opts: Record<string, unknown> = {max: size,idle_timeout: 20,- connect_timeout: 10,+ connect_timeout: resolveConnectTimeoutSeconds(this._directUrl),// Explicit (matches the postgres.js implicit default; GBRAIN_POOL_MAX_LIFETIME_S overrides).max_lifetime: resolveMaxLifetimeSeconds(),types: { bigint: postgres.BigInt },diff --git a/src/core/db.ts b/src/core/db.tsindex 72b4c9ba45..d03e4d4376 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -110,6 +110,34 @@ export function resolvePrepare(url: string): boolean | undefined {return undefined;}+const DEFAULT_CONNECT_TIMEOUT_SECONDS = 10;++/**+ * Client connect timeout, in seconds, for every postgres() call site (module+ * singleton, engine instance pool, ConnectionManager read + direct pools).+ *+ * postgres.js resolves each option as `k in opts ? opts[k] : k in url.query ? ...`+ * (`parseOptions`), so an explicit `connect_timeout` in the options object+ * shadows a `?connect_timeout=N` in the URL; a hardcoded value would silently+ * discard the URL's. A positive integer in the URL wins (whole seconds, as+ * libpq defines the parameter); anything else keeps the 10s default. `0` is+ * not honoured: postgres.js reads it as "no timer at all", and every gbrain+ * connect stays bounded.+ */+export function resolveConnectTimeoutSeconds(url: string): number {+ try {+ const parsed = new URL(url.replace(/^postgres(ql)?:\/\//, 'http://'));+ const raw = parsed.searchParams.get('connect_timeout')?.trim();+ if (raw && /^\d+$/.test(raw)) {+ const seconds = Number(raw);+ if (seconds > 0) return seconds;+ }+ } catch {+ // URL parse failure — fall through to default+ }+ return DEFAULT_CONNECT_TIMEOUT_SECONDS;+}+export function resolvePoolSize(explicit?: number): number {if (typeof explicit === 'number' && explicit > 0) return explicit;const raw = process.env.GBRAIN_POOL_SIZE;@@ -293,7 +321,7 @@ export async function connect(config: EngineConfig, hooks: { onpoisoned?: (statuconst opts: Record<string, unknown> = {max: resolvePoolSize(),idle_timeout: 20,- connect_timeout: 10,+ connect_timeout: resolveConnectTimeoutSeconds(url),// Explicit (matches the postgres.js implicit default; GBRAIN_POOL_MAX_LIFETIME_S overrides).max_lifetime: resolveMaxLifetimeSeconds(),types: {diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 55039f1eac..cac87aedd7 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -361,7 +361,7 @@ export class PostgresEngine implements BrainEngine {const opts: Record<string, unknown> = {max: size,idle_timeout: 20,- connect_timeout: 10,+ connect_timeout: db.resolveConnectTimeoutSeconds(url),// Explicit (matches the postgres.js implicit default; GBRAIN_POOL_MAX_LIFETIME_S overrides).max_lifetime: db.resolveMaxLifetimeSeconds(),types: { bigint: postgres.BigInt },diff --git a/test/db-connect-timeout.test.ts b/test/db-connect-timeout.test.tsnew file mode 100644index 0000000000..809a3f0006--- /dev/null+++ b/test/db-connect-timeout.test.ts@@ -0,0 +1,149 @@+/**+ * `?connect_timeout=N` in `database_url` reaches postgres.js at every+ * postgres() call site.+ *+ * postgres.js gives an explicit option precedence over the URL query+ * (`parseOptions`: `k in o ? o[k] : k in query ? ...`), so the bare+ * `connect_timeout: 10` each pool passed silently discarded the URL's value:+ * a brain whose URL asked for 30s still gave up at 10s with+ * `write CONNECT_TIMEOUT`.+ *+ * DB-free. The resolver cases are pure. The wiring cases build REAL pools that+ * dial a local TCP endpoint which accepts connections and never answers the+ * Postgres handshake (the seam test/postgres-engine-singleton-lifecycle.test.ts+ * uses), so a connect stays in flight until the endpoint refuses it or the+ * connect timer fires.+ */++import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { createServer, type AddressInfo, type Socket } from 'net';+import * as db from '../src/core/db.ts';+import { ConnectionManager } from '../src/core/connection-manager.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';++const BASE = 'postgres://user:[email protected]:5432/gbrain';++describe('resolveConnectTimeoutSeconds', () => {+ test('a URL without the parameter keeps the 10s default', () => {+ expect(db.resolveConnectTimeoutSeconds(BASE)).toBe(10);+ expect(db.resolveConnectTimeoutSeconds(`${BASE}?sslmode=require`)).toBe(10);+ });++ test('a positive integer in the URL wins, beside other parameters and on either scheme', () => {+ expect(db.resolveConnectTimeoutSeconds(`${BASE}?sslmode=require&connect_timeout=30`)).toBe(30);+ expect(db.resolveConnectTimeoutSeconds(`${BASE}?connect_timeout=45&prepare=false`)).toBe(45);+ expect(db.resolveConnectTimeoutSeconds('postgresql://u:p@h:6543/d?connect_timeout=3')).toBe(3);+ });++ test.each([+ ['0', 'postgres.js reads 0 as no connect timer at all'],+ ['-5', 'not a duration'],+ ['2.5', 'libpq defines the parameter in whole seconds'],+ ['abc', 'not a number'],+ ['', 'empty'],+ ])('connect_timeout=%p falls back to the default (%s)', (raw) => {+ expect(db.resolveConnectTimeoutSeconds(`${BASE}?connect_timeout=${raw}`)).toBe(10);+ });++ test('an unparseable URL falls back to the default', () => {+ expect(db.resolveConnectTimeoutSeconds('not a url')).toBe(10);+ });+});++function fatal(): Buffer {+ const body = Buffer.from('SFATAL\0C57P01\0Mtest endpoint refused\0\0');+ const head = Buffer.alloc(5);+ head.write('E', 0);+ head.writeInt32BE(body.length + 4, 1);+ return Buffer.concat([head, body]);+}++async function openSilentEndpoint() {+ const held: Socket[] = [];+ let refusing = false;+ const server = createServer(socket => {+ held.push(socket);+ socket.on('data', () => { if (refusing && !socket.writableEnded) socket.end(fatal()); });+ });+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ return {+ url: `postgres://[email protected]:${(server.address() as AddressInfo).port}/gbrain`,+ refuse() { refusing = true; for (const socket of held.splice(0)) socket.end(fatal()); },+ close() { server.close(); },+ };+}++const connectTimeoutOf = (pool: unknown) =>+ (pool as { options: { connect_timeout: unknown } }).options.connect_timeout;++let endpoint: Awaited<ReturnType<typeof openSilentEndpoint>>;+let pending: Promise<unknown>[] = [];+let cleanups: (() => Promise<void>)[] = [];+const settle = <T>(p: Promise<T>) => { const s = p.catch(e => e); pending.push(s); return s; };++beforeEach(async () => {+ endpoint = await openSilentEndpoint();+});++afterEach(async () => {+ endpoint.refuse();+ await Promise.all(pending);+ pending = [];+ for (const cleanup of cleanups.splice(0)) await cleanup();+ await db.disconnect();+ endpoint.close();+});++describe('the URL connect_timeout reaches every pool', () => {+ test('module singleton (db.connect)', async () => {+ settle(db.connect({ database_url: `${endpoint.url}?connect_timeout=37` }));+ expect(connectTimeoutOf(db.getConnection())).toBe(37);+ });++ test('engine instance pool (the per-worker pool import and sync open)', async () => {+ const engine = new PostgresEngine();+ cleanups.push(() => engine.disconnect());+ settle(engine.connect({ database_url: `${endpoint.url}?connect_timeout=37`, poolSize: 1 }));+ expect(connectTimeoutOf(engine.sql)).toBe(37);+ });++ test('ConnectionManager read pool, and the 10s default when the URL has none', async () => {+ const tuned = await new ConnectionManager({ url: `${endpoint.url}?connect_timeout=37` }).getReadPool();+ const plain = await new ConnectionManager({ url: endpoint.url }).getReadPool();+ cleanups.push(() => db.endPoolBounded(tuned), () => db.endPoolBounded(plain));+ expect(connectTimeoutOf(tuned)).toBe(37);+ expect(connectTimeoutOf(plain)).toBe(10);+ });++ test('a sibling pool never inherits the other pool\'s URL parameter', async () => {+ const cm = new ConnectionManager({ url: `${endpoint.url}?connect_timeout=1`, directUrl: endpoint.url });+ cleanups.push(() => cm.disconnect());+ expect(connectTimeoutOf(await cm.getReadPool())).toBe(1);+ const outcome = await Promise.race([+ settle(cm.ddl()).then(() => 'direct pool gave up'),+ new Promise(resolve => setTimeout(resolve, 3_000, 'direct pool still connecting')),+ ]);+ expect(outcome).toBe('direct pool still connecting');+ });++ test('ConnectionManager direct pool gives up at the URL value, not at 10s', async () => {+ const errors: string[] = [];+ const errSpy = spyOn(console, 'error').mockImplementation((...args: unknown[]) => { errors.push(args.join(' ')); });+ const cm = new ConnectionManager({+ url: 'postgresql://[email protected]:5/never-connected',+ directUrl: `${endpoint.url}?connect_timeout=1`,+ });+ cleanups.push(() => cm.disconnect());+ try {+ const started = Date.now();+ // The direct probe never completes; its connect timer is the only way out,+ // and the unreachable-direct fallback then hands back the read pool.+ await cm.ddl();+ expect(Date.now() - started).toBeLessThan(5_000);+ expect(cm.isKillSwitchActive()).toBe(true);+ expect(errors.join('\n')).toContain('CONNECT_TIMEOUT');+ } finally {+ errSpy.mockRestore();+ }+ });+});diff --git a/test/e2e/db-connect-timeout.test.ts b/test/e2e/db-connect-timeout.test.tsnew file mode 100644index 0000000000..a92eb5bc2a--- /dev/null+++ b/test/e2e/db-connect-timeout.test.ts@@ -0,0 +1,53 @@+/**+ * #5945 on a real server. Protects: a `database_url` carrying+ * `?connect_timeout=N` connects, and every pool (module singleton, engine+ * instance pool, ConnectionManager read and direct pools) runs with that+ * value. Fails when: a pool hardcodes 10s again, or the parameter leaks into+ * the startup packet as an unknown server setting (Postgres would refuse it).+ */+import { afterAll, describe, expect, test } from 'bun:test';+import * as db from '../../src/core/db.ts';+import { ConnectionManager } from '../../src/core/connection-manager.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { assertSafeE2eDatabaseUrl, hasDatabase } from './helpers.ts';++const base = process.env.DATABASE_URL ?? '';+const withTimeout = (seconds: number) => {+ const url = new URL(base);+ url.searchParams.set('connect_timeout', String(seconds));+ return url.toString();+};+const connectTimeoutOf = (pool: unknown) => (pool as { options: { connect_timeout: unknown } }).options.connect_timeout;++describe.skipIf(!hasDatabase())('connect_timeout from database_url (Postgres)', () => {+ const cleanups: Array<() => Promise<void>> = [];+ afterAll(async () => { for (const cleanup of cleanups.splice(0)) await cleanup(); await db.disconnect(); });++ test('module singleton and engine instance pool connect and carry the URL value', async () => {+ assertSafeE2eDatabaseUrl(base);+ await db.connect({ database_url: withTimeout(17) });+ const singleton = db.getConnection();+ expect(connectTimeoutOf(singleton)).toBe(17);+ expect((await singleton`SELECT 1 AS ok`)[0].ok).toBe(1);++ const engine = new PostgresEngine();+ cleanups.push(() => engine.disconnect());+ await engine.connect({ database_url: withTimeout(23), poolSize: 2 });+ expect(connectTimeoutOf(engine.sql)).toBe(23);+ expect((await engine.executeRaw<{ ok: number }>('SELECT 1 AS ok'))[0].ok).toBe(1);+ }, 60_000);++ test('ConnectionManager read and direct pools each use their own URL', async () => {+ const cm = new ConnectionManager({ url: withTimeout(19), directUrl: withTimeout(29) });+ cleanups.push(() => cm.disconnect());+ const read = await cm.getReadPool();+ const ddl = await cm.ddl();+ expect(connectTimeoutOf(read)).toBe(19);+ expect(connectTimeoutOf(ddl)).toBe(29);+ expect((await ddl`SELECT 1 AS ok`)[0].ok).toBe(1);++ const plain = new ConnectionManager({ url: base });+ cleanups.push(() => plain.disconnect());+ expect(connectTimeoutOf(await plain.getReadPool())).toBe(10);+ }, 60_000);+});