Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(db): our own implementation of the #5945 fix (#5945)
time-attack01087fc975c2
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex c4fe9f4cf2..b493e760a5 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`. `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/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`. `resolveUrlConnectTimeout(url)` supplies `connect_timeout` to the same four call sites from each pool's own URL query (postgres.js lets the explicit option win over the URL, so the URL value is honoured only through this resolver): whole seconds, capped at the runtime's 2^31-1 ms timer limit; `0`, junk or no parameter means 10s. 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 4c2d789b88..5b4f0069ba 100644--- a/src/commands/engine-status.ts+++ b/src/commands/engine-status.ts@@ -10,8 +10,9 @@* status call when its DB is down anyway.** Zero round-trips without --probe. With --probe: a SINGLE bounded connect- * (the pool's `connect_timeout`, 10s unless `database_url` sets one — never- * a custom race) + SELECT 1; failures come back as a classified PgAccessDiagnosis,+ * (bounded by the pool's own connect timer: `connect_timeout` from+ * `database_url`, else 10s; 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 de3d41b810..e12550448f 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, resolveConnectTimeoutSeconds, endPoolBounded } from './db.ts';+import { resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, 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: resolveConnectTimeoutSeconds(this.opts.url),+ connect_timeout: resolveUrlConnectTimeout(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: resolveConnectTimeoutSeconds(this._directUrl),+ connect_timeout: resolveUrlConnectTimeout(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 a418f3b4f8..366aa9e49f 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -107,32 +107,43 @@ export function resolvePrepare(url: string): boolean | undefined {return undefined;}-const DEFAULT_CONNECT_TIMEOUT_SECONDS = 10;+/**+ * Seconds a pool waits for a connection before giving up with CONNECT_TIMEOUT+ * when its URL names no `connect_timeout` of its own.+ */+const FALLBACK_CONNECT_TIMEOUT_S = 10;++/**+ * Upper bound for a URL-supplied `connect_timeout`. postgres.js arms the+ * connect timer with `setTimeout(seconds * 1000)`, and a delay past 2^31-1 ms+ * does not fit the runtime's timer: Bun and Node replace it with 1 ms, so a+ * "wait practically forever" value would fail every connect at once.+ */+const MAX_CONNECT_TIMEOUT_S = Math.floor(0x7fffffff / 1000);/**- * Client connect timeout, in seconds, for every postgres() call site (module- * singleton, engine instance pool, ConnectionManager read + direct pools).+ * The `connect_timeout` each postgres() pool is built with, read from that+ * pool's own URL.*- * 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.+ * Every call site has to pass the option explicitly (an unset option would+ * drop to postgres.js's 30s default), and postgres.js lets an explicit option+ * override the URL query. So the URL's value is honoured only if we read it+ * here and hand it back. The query is located the way the driver's `new URL()`+ * does (after the first `?`, before any `#`), so userinfo and host text are+ * never consulted. Accepted: whole seconds, surrounding blanks allowed, capped+ * at MAX_CONNECT_TIMEOUT_S. Everything else, including `0` (no timer at all in+ * postgres.js), keeps the fallback so no gbrain connect waits unbounded.*/-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 resolveUrlConnectTimeout(url: string): number {+ const [beforeFragment = ''] = url.split('#', 1);+ const queryAt = beforeFragment.indexOf('?');+ if (queryAt < 0) return FALLBACK_CONNECT_TIMEOUT_S;++ const requested = new URLSearchParams(beforeFragment.slice(queryAt + 1)).get('connect_timeout');+ const digits = requested?.match(/^\s*(\d+)\s*$/)?.[1];+ const seconds = digits === undefined ? 0 : parseInt(digits, 10);+ if (seconds < 1) return FALLBACK_CONNECT_TIMEOUT_S;+ return Math.min(seconds, MAX_CONNECT_TIMEOUT_S);}export function resolvePoolSize(explicit?: number): number {@@ -318,7 +329,7 @@ export async function connect(config: EngineConfig, hooks: { onpoisoned?: (statuconst opts: Record<string, unknown> = {max: resolvePoolSize(),idle_timeout: 20,- connect_timeout: resolveConnectTimeoutSeconds(url),+ connect_timeout: resolveUrlConnectTimeout(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 8614123818..3e0d7f13b9 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -362,7 +362,7 @@ export class PostgresEngine implements BrainEngine {const opts: Record<string, unknown> = {max: size,idle_timeout: 20,- connect_timeout: db.resolveConnectTimeoutSeconds(url),+ connect_timeout: db.resolveUrlConnectTimeout(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.tsindex 7d4519ae67..da44334b65 100644--- a/test/db-connect-timeout.test.ts+++ b/test/db-connect-timeout.test.ts@@ -1,182 +1,163 @@/**- * `?connect_timeout=N` in `database_url` reaches postgres.js at every- * postgres() call site.+ * Protects: a `connect_timeout` written into a pool's URL is the timer that+ * pool connects under, for all four postgres() pools (module singleton,+ * PostgresEngine instance pool, ConnectionManager read and direct pools).*- * 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`.+ * Regression it catches: a call site passing a fixed `connect_timeout`+ * again. postgres.js lets an explicit option beat the URL query, so the URL+ * value silently stops mattering and a slow-to-wake server fails at 10s.*- * 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.+ * Why not covered elsewhere: test/db-pool-max-lifetime.test.ts pins a+ * different option and reads no URL.+ *+ * DB-free. Pools dial a local "tarpit" that accepts TCP and never speaks the+ * Postgres protocol, so a connect can only end by its own timer or by the+ * test closing the socket. Postgres-side coverage:+ * test/e2e/db-connect-timeout.test.ts.*/import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';-import { createServer, type AddressInfo, type Socket } from 'net';+import { createServer, type AddressInfo, type Server, 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';-import { withEnv } from './helpers/with-env.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);- });+const CREDENTIALED = 'postgres://reader:[email protected]:5432/brain';+const TIMER_CEILING_S = 2147483;- 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);+describe('resolveUrlConnectTimeout', () => {+ test.each([+ ['no query at all', CREDENTIALED, 10],+ ['other parameters only', `${CREDENTIALED}?sslmode=require&application_name=x`, 10],+ ['a plain value', `${CREDENTIALED}?connect_timeout=30`, 30],+ ['a value among other parameters', `${CREDENTIALED}?sslmode=require&connect_timeout=45&prepare=false`, 45],+ ['the postgresql scheme', 'postgresql://[email protected]/brain?connect_timeout=4', 4],+ ['a multi-host URL', 'postgres://[email protected]:5432,pg-b.example.invalid:5433/brain?connect_timeout=12', 12],+ ['surrounding blanks', `${CREDENTIALED}?connect_timeout=%2020%20`, 20],+ ['a value past the runtime timer limit is capped', `${CREDENTIALED}?connect_timeout=99999999`, TIMER_CEILING_S],+ ['exactly the timer limit', `${CREDENTIALED}?connect_timeout=${TIMER_CEILING_S}`, TIMER_CEILING_S],+ ])('%s', (_label, url, expected) => {+ expect(db.resolveUrlConnectTimeout(url)).toBe(expected);});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);+ ['zero (postgres.js would arm no timer)', '0'],+ ['negative', '-3'],+ ['fractional', '1.5'],+ ['exponent notation', '3e1'],+ ['hex', '0x1e'],+ ['words', 'soon'],+ ['empty', ''],+ ])('%s keeps the 10s fallback', (_label, raw) => {+ expect(db.resolveUrlConnectTimeout(`${CREDENTIALED}?connect_timeout=${raw}`)).toBe(10);});- test('an unparseable URL falls back to the default', () => {- expect(db.resolveConnectTimeoutSeconds('not a url')).toBe(10);+ test('text outside the query is never read as the parameter', () => {+ expect(db.resolveUrlConnectTimeout('postgres://reader:connect_timeout%[email protected]/brain')).toBe(10);+ expect(db.resolveUrlConnectTimeout(`${CREDENTIALED}#connect_timeout=3`)).toBe(10);+ expect(db.resolveUrlConnectTimeout(`${CREDENTIALED}?sslmode=disable#connect_timeout=3`)).toBe(10);+ expect(db.resolveUrlConnectTimeout('definitely 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]);-}+interface Tarpit { url: string; shut(): Promise<void> }-async function openSilentEndpoint() {- const held: Socket[] = [];- let refusing = false;- let accepted = 0;- const server = createServer(socket => {- accepted += 1;- held.push(socket);- socket.on('data', () => { if (refusing && !socket.writableEnded) socket.end(fatal()); });+async function openTarpit(): Promise<Tarpit> {+ const sockets = new Set<Socket>();+ const server: Server = createServer(socket => {+ sockets.add(socket);+ socket.on('close', () => sockets.delete(socket));+ socket.on('error', () => {});});await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ const { port } = server.address() as AddressInfo;return {- url: `postgres://[email protected]:${(server.address() as AddressInfo).port}/gbrain`,- get accepted() { return accepted; },- refuse() { refusing = true; for (const socket of held.splice(0)) socket.end(fatal()); },- close() { server.close(); },+ url: `postgres://[email protected]:${port}/brain`,+ async shut() {+ for (const socket of sockets) socket.destroy();+ await new Promise<void>(resolve => server.close(() => resolve()));+ },};}-const connectTimeoutOf = (pool: unknown) =>- (pool as { options: { connect_timeout: unknown } }).options.connect_timeout;+const timerOf = (pool: unknown): unknown => (pool as { options: Record<string, unknown> }).options.connect_timeout;+const outcomeWithin = (work: Promise<unknown>, ms: number) =>+ Promise.race([+ work.then(() => 'resolved', (err: unknown) => `rejected: ${err instanceof Error ? err.message : String(err)}`),+ new Promise<string>(resolve => setTimeout(resolve, ms, 'still waiting')),+ ]);-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; };+let tarpit: Tarpit;+let inFlight: Promise<unknown>[];+let teardown: (() => Promise<unknown>)[];+let stderr: ReturnType<typeof spyOn<Console, 'error'>>;+const track = <T>(work: Promise<T>): Promise<T> => { inFlight.push(work.catch(() => undefined)); return work; };beforeEach(async () => {- endpoint = await openSilentEndpoint();+ tarpit = await openTarpit();+ inFlight = [];+ teardown = [];+ stderr = spyOn(console, 'error').mockImplementation(() => {});});afterEach(async () => {- endpoint.refuse();- await Promise.all(pending);- pending = [];- for (const cleanup of cleanups.splice(0)) await cleanup();+ await tarpit.shut();+ for (const step of teardown.reverse()) await step();await db.disconnect();- endpoint.close();+ await Promise.all(inFlight);+ stderr.mockRestore();});-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);+describe('each pool connects under its own URL timer', () => {+ test('module singleton: a 1s URL timer ends the connect with CONNECT_TIMEOUT', async () => {+ const started = Date.now();+ const outcome = await outcomeWithin(track(db.connect({ database_url: `${tarpit.url}?connect_timeout=1` })), 6_000);+ expect(outcome).toContain('CONNECT_TIMEOUT');+ expect(Date.now() - started).toBeLessThan(6_000);});- 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('module singleton without the parameter is still waiting when the 1s case has long given up', async () => {+ const outcome = await outcomeWithin(track(db.connect({ database_url: tarpit.url })), 2_500);+ expect(outcome).toBe('still waiting');+ expect(timerOf(db.getConnection())).toBe(10);});- 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('PostgresEngine instance pool', async () => {+ const engine = new PostgresEngine();+ teardown.push(() => engine.disconnect());+ track(engine.connect({ database_url: `${tarpit.url}?connect_timeout=41`, poolSize: 1 }));+ expect(timerOf(engine.sql)).toBe(41);});- 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 read pool takes its URL value; a bare URL keeps 10s', async () => {+ const tuned = new ConnectionManager({ url: `${tarpit.url}?connect_timeout=41` });+ const bare = new ConnectionManager({ url: tarpit.url });+ teardown.push(() => tuned.disconnect(), () => bare.disconnect());+ expect(timerOf(await tuned.getReadPool())).toBe(41);+ expect(timerOf(await bare.getReadPool())).toBe(10);});- 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(' ')); });+ test('ConnectionManager direct pool gives up on its own URL timer and falls back to the read pool', async () => {const cm = new ConnectionManager({- url: 'postgresql://[email protected]:5/never-connected',- directUrl: `${endpoint.url}?connect_timeout=1`,+ url: `${tarpit.url}?connect_timeout=41`,+ directUrl: `${tarpit.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();- }+ teardown.push(() => cm.disconnect());+ const started = Date.now();+ const pool = await track(cm.ddl());+ expect(Date.now() - started).toBeLessThan(6_000);+ expect(cm.isKillSwitchActive()).toBe(true);+ expect(timerOf(pool)).toBe(41);+ expect(stderr.mock.calls.flat().join(' ')).toContain('CONNECT_TIMEOUT');});-});--describe('worker connect retry composes with the URL connect_timeout (#5946)', () => {- const quietly = async <T>(fn: () => Promise<T>) => {- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});- try { return await fn(); } finally { warnSpy.mockRestore(); }- };- test('each retried worker connect gives up at the URL value and dials again', async () => {- const engine = new PostgresEngine();- cleanups.push(() => engine.disconnect());- const started = Date.now();- const error = await quietly(() => withEnv({ GBRAIN_NO_RETRY_CONNECT: undefined }, () =>- db.connectWorkerEngine(engine, { database_url: `${endpoint.url}?connect_timeout=1`, poolSize: 1 }).catch(e => e)));- const elapsed = Date.now() - started;- expect((error as { code?: string }).code).toBe('CONNECT_TIMEOUT');- expect(endpoint.accepted).toBe(3);- expect(elapsed).toBeGreaterThanOrEqual(5_000);- expect(elapsed).toBeLessThan(9_500);- }, 20_000);-- test('GBRAIN_NO_RETRY_CONNECT=1 makes the worker connect a single attempt', async () => {- const engine = new PostgresEngine();- cleanups.push(() => engine.disconnect());- const error = await quietly(() => withEnv({ GBRAIN_NO_RETRY_CONNECT: '1' }, () =>- db.connectWorkerEngine(engine, { database_url: `${endpoint.url}?connect_timeout=1`, poolSize: 1 }).catch(e => e)));- expect((error as { code?: string }).code).toBe('CONNECT_TIMEOUT');- expect(endpoint.accepted).toBe(1);- }, 20_000);+ test('the read pool\'s short timer does not leak into the direct pool', async () => {+ const cm = new ConnectionManager({+ url: `${tarpit.url}?connect_timeout=1`,+ directUrl: tarpit.url,+ });+ teardown.push(() => cm.disconnect());+ expect(timerOf(await cm.getReadPool())).toBe(1);+ expect(await outcomeWithin(track(cm.ddl()), 2_500)).toBe('still waiting');+ });});diff --git a/test/e2e/db-connect-timeout.test.ts b/test/e2e/db-connect-timeout.test.tsindex a92eb5bc2a..31057981a7 100644--- a/test/e2e/db-connect-timeout.test.ts+++ b/test/e2e/db-connect-timeout.test.ts@@ -17,7 +17,7 @@ const withTimeout = (seconds: number) => {url.searchParams.set('connect_timeout', String(seconds));return url.toString();};-const connectTimeoutOf = (pool: unknown) => (pool as { options: { connect_timeout: unknown } }).options.connect_timeout;+const timerOf = (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>> = [];@@ -27,13 +27,13 @@ describe.skipIf(!hasDatabase())('connect_timeout from database_url (Postgres)',assertSafeE2eDatabaseUrl(base);await db.connect({ database_url: withTimeout(17) });const singleton = db.getConnection();- expect(connectTimeoutOf(singleton)).toBe(17);+ expect(timerOf(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(timerOf(engine.sql)).toBe(23);expect((await engine.executeRaw<{ ok: number }>('SELECT 1 AS ok'))[0].ok).toBe(1);}, 60_000);@@ -42,12 +42,12 @@ describe.skipIf(!hasDatabase())('connect_timeout from database_url (Postgres)',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(timerOf(read)).toBe(19);+ expect(timerOf(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);+ expect(timerOf(await plain.getReadPool())).toBe(10);}, 60_000);});