Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(postgres): a statement that fails to build never desyncs its connection; retire a connection whose statement outlives statement_timeout; live pool numbers and /health?deep=1 (#6383)

garrytan1613751d3417
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2422dfd979..d39d963314 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,26 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.148.0] - 2026-10-10
+
+**On Postgres, one statement with an `undefined` parameter could wedge a pooled connection for good: the statement in flight ahead of it got its error, it stayed queued with nothing on the wire, every later reply arrived one statement late, and the backend sat `active / ClientRead` while `/health` answered 200 (#6383, the driver desync behind #6352). The vendored driver now builds a statement before it joins the queue, so only the culprit fails; a connection whose statement waits past `statement_timeout` plus 30 s with nothing coming back is retired and replaced; the pool numbers are live; and `/health?deep=1` probes through the same pool the handlers use.**
+
+GBRA-76. Reproduced on master against Postgres 16 with `max: 1, prepare: false, shared_types: true`: a head statement, a statement binding `undefined`, and a describe-first follower issued together. Head rejects with `UNDEFINED_VALUE`, the culprit with `null is not an object (evaluating 'query.statement.types')`, the follower and everything after it never settle, and `pg_stat_activity` shows the backend `active / Client:ClientRead` on the follower. With the fix the head and the follower resolve with their own rows, only the culprit rejects, and the backend is idle.
+
+### Itemized changes
+
+- **A statement that fails to build never touches its connection** (`vendor/postgres/src/connection.js`, the `cjs` and `cf` copies, `patches/[email protected]`). `execute()` builds and serializes the statement first and enqueues it only once its bytes exist. A build failure (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) rejects that statement alone; a head statement on an idle connection still owns the `Sync` round trip the stock driver wrote, so the reservation and transaction state machines are unchanged. The pool reports each failure through `onbuilderror(code, statement)` with the statement's text and `$n` placeholders, never values; the engine logs it as `[gbrain] warn code=pg_statement_build_failed error=UNDEFINED_VALUE pool=read sql=INSERT_mcp_request_log` (first keyword and table), so the call site that binds `undefined`, which nobody has found yet, names itself the first time it happens.
+- **A connection whose statement never answers is retired, not kept** (`connection.js`, `index.js`, `src/core/db.ts`, `connection-manager.ts`, `postgres-engine.ts`, `pool-gauge.ts`). New pool option `inflight_timeout`: a clock on the head statement that starts when it becomes the head, restarts on every byte the server sends and stops at `ReadyForQuery`. Past it the statement and everything queued behind it reject with `CONNECTION_STUCK`, the pool parks the connection out of rotation before its socket closes, `onstuck({ age_ms, queued, statement })` fires once, the socket is ended and destroyed, and the pool reconnects. gbrain sets it to each pool's own `statement_timeout` plus `GBRAIN_PG_STUCK_GRACE_MS` (default 30 000 ms; `0`/`off` disables it; a pool without a statement timeout has no watchdog), so a legitimate statement, which the server ends first, is never retired, while a desynced pipeline, a transaction-mode pooler that swallowed a `CancelRequest`, or a dead peer costs one budget instead of a restart. Each retirement logs `pg_connection_stuck` with the pool, age, queue depth and the statement's keyword and table, and counts in `getPoolDiagnostics().stuckDiscards`.
+- **The pool numbers are live** (`index.js`, `postgres-engine/pool-stats.ts`, `persistence/consumer-heartbeat.ts`). `sql.pool` (#6317) was defined inside `Object.assign`, which reads a getter once and copies the value, so every reader saw the construction-time snapshot (`checked_out: 0`, `waiters: 0`) for the life of the pool. It is a property getter now and adds `inflight_oldest_ms` (the oldest head statement's age) and `completed` (statements settled). The persistence heartbeat row carries both, so `gbrain sources writer status --json` shows them for the owner process.
+- **`/health?deep=1`** (`serve-http-metrics.ts`). Plain `/health` is unchanged and still fast. It answered 200 through the whole incident because its `SELECT 1` runs on a reserved connection, and `reserve()` only ever claims an idle one; the wedged connections sat in the busy queue where handler statements are routed. `/health?deep=1` runs `SELECT 1` through that ordinary pooled dispatch with the 3 s budget, returns the pool block (`checked_out`, `max`, `waiters`, `inflight_oldest_ms`, `completed`, `poisoned_discards`, `stuck_discards`, `build_failures`) and answers 503 when the probe times out, when a statement is past the read pool's in-flight budget, or while an earlier deep probe is still pending (one at a time per engine).
+- **The pool stall line** (`postgres-engine/pool-stall-watch.ts`, `commands/serve.ts`). `gbrain serve` reads its pool every 30 s. Connections checked out or statements waiting across two ticks with nothing completed in between logs `[gbrain] warn code=pg_pool_stalled checked_out=… waiters=… inflight_oldest_ms=… stalled_ms=…` once per tick and `info code=pg_pool_recovered` when statements complete again. One slow statement is one quiet tick and is not reported. The incident's fifty silent minutes become a line a minute in.
+- `gbrain errors pg_connection_stuck | pg_statement_build_failed | pg_pool_stalled` resolve offline; [docs/ENGINES.md](docs/ENGINES.md#pg-connection-stuck) has the entries and the `/health?deep=1` contract; `docs/mcp/DEPLOY.md` names the deep probe for supervisors.
+- Not in this release: forwarding an HTTP client's abort into the MCP handler (serve never did; the cancel in the #6383 timeline was coincidental, the retries fed the wedged connection) and a deadline on publication transactions (#6352's second ask).
+- Tests:
+ - `test/e2e/postgres-pipelined-build-failure-postgres.test.ts` (5 cases: the pipelined culprit, a culprit as head on an idle and on a reserved connection, a transaction with a bad member, `MAX_PARAMETERS_EXCEEDED`, the CommonJS build). On master 5 of 5 fail: the follower and later statements hang and the backend stays `active`.
+ - `test/e2e/postgres-stuck-connection-postgres.test.ts` (5 cases: live pool numbers, a stuck head and its queued follower, a stuck reserved connection, no false positive within budget and with the watchdog off, the engine's counter and warn line). On master 4 of 5 fail: `busy` reads 0 during `pg_sleep` and the stuck statements hang.
+ - `test/pool-health-6383.test.ts` (18 cases, no database): the budget derivation and its `0`/`off` switch, the three warn lines, the stall watch's two-tick rule and single recovery line, and `/health?deep=1`'s 200, budget-exceeded 503, timeout 503, pending 503 and PGLite paths.
+
## [0.60.147.0] - 2026-10-10
**A write that arrives while a brain folder with the Git durability hook is committing a backlog of Git effects now publishes after the group in flight, inside its 5 s wait. Before, it waited out the whole backlog and came back pending. On Postgres, a first sync of an already-imported source now issues 40 statements per unchanged file instead of 82.**
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 080509d28d..ee922d5d5a 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -697,6 +697,71 @@ the operations that preceded them. A pool created with `max: 1` keeps the
driver's documented single-connection idiom (`BEGIN` as an ordinary query)
for unreserved statements.
+<a id="pg-connection-stuck"></a>**`pg_connection_stuck`** (warn). A pooled
+statement waited past the pool's `statement_timeout` plus a grace with nothing
+coming back from the server, so the vendored driver retired that connection:
+the statement and every statement queued behind it failed with the driver error
+`CONNECTION_STUCK`, the connection left the pool before its socket closed, and
+the pool reconnected on its own (#6383). A legitimate statement cannot outlive
+the server-side timeout, so only a wedged connection reaches the budget: a
+pipeline the client and server no longer agree on, a transaction-mode pooler
+that swallowed a `CancelRequest` and left the backend in `ClientRead`, or a
+dead peer. The budget is the pool's own startup `statement_timeout` (5 min on
+the read pool, 30 min on the direct pool, `GBRAIN_STATEMENT_TIMEOUT` for the
+read pool) plus `GBRAIN_PG_STUCK_GRACE_MS` (default `30000`); it follows the
+configured timeout even through a pooler that drops the startup parameter, so a
+statement that must run longer raises `GBRAIN_STATEMENT_TIMEOUT`, and
+`GBRAIN_PG_STUCK_GRACE_MS=0` or `off` disables the watchdog. The clock restarts
+on every byte the server sends, so a long result set or a `COPY` is never cut
+short. The line names the pool, `age_ms`, `queued` (statements that failed with
+it) and the statement by first keyword and table (`sql=SELECT_pages`), never its
+text or parameters. `getPoolDiagnostics().stuckDiscards` counts retirements per
+engine; `/health?deep=1` reports them as `stuck_discards`. Retry the failed
+call; if the line repeats, run `gbrain doctor --json` and report the warn lines
+with the operations that preceded them.
+
+<a id="pg-statement-build-failed"></a>**`pg_statement_build_failed`** (warn). A
+statement could not be built from its parameters (`error=UNDEFINED_VALUE`: a
+parameter was `undefined`; `error=MAX_PARAMETERS_EXCEEDED`: more than 65534
+parameters) and was rejected before it reached the connection. No other
+statement was affected: before #6383 the same failure, when the statement was
+pipelined behind another on its connection, rejected that other statement with
+its error, left the culprit queued with nothing on the wire, and delivered every
+later reply one statement late until the process restarted (the
+`null is not an object (evaluating 'query.statement.types')` line and a backend
+stuck `active / ClientRead` were that desync). The line names the pool and the
+statement by first keyword and table; the call site that bound `undefined` is a
+gbrain bug, so report the line. `getPoolDiagnostics().buildFailures` counts
+them.
+
+<a id="pg-pool-stalled"></a>**`pg_pool_stalled`** (warn, resident processes).
+`gbrain serve` reads its pool every 30 s; when connections are checked out or
+statements are waiting for one across two ticks in a row and the pool completed
+no statement in between, it logs this line once per tick with `checked_out`,
+`max`, `waiters`, `inflight_oldest_ms` and `stalled_ms`, and one
+`[gbrain] info code=pg_pool_recovered` line when statements complete again.
+One slow statement is one quiet tick and is never reported. With the in-flight
+watchdog on, a stall ends within `statement_timeout` plus grace and
+`pg_connection_stuck` names the connection; with the watchdog off this line is
+the only trace a wedged pool leaves. A line that keeps repeating with no
+recovery means the database or pooler is unreachable from the process:
+`gbrain doctor --json` from a fresh process, then restart the stalled one.
+
+**`/health?deep=1`** (`gbrain serve --http`). Plain `/health` stays the fast
+liveness probe, and it runs its `SELECT 1` on a reserved connection, which the
+driver only ever claims from idle connections; a wedged connection sits in the
+busy queue where handler statements are routed, so `/health` answered 200
+through the whole #6383 incident. `/health?deep=1` runs `SELECT 1` through the
+ordinary pooled dispatch (no reservation, 3 s budget) and answers 503 when the
+probe does not return in time, when `inflight_oldest_ms` is past the read
+pool's in-flight budget, or when an earlier deep probe is still pending (one
+deep probe per engine at a time). Its body carries the pool block:
+`{ checked_out, max, waiters, inflight_oldest_ms, completed, poisoned_discards,
+stuck_discards, build_failures }`. It is cheap enough for a two-minute cron. The
+same pool numbers ride the persistence consumer's heartbeat row, so
+`gbrain sources writer status --json` shows `pool.inflight_oldest_ms` for the
+owner process.
+
<a id="backfill-rollback-failed"></a>**`backfill_rollback_failed`** (error).
A `gbrain backfill` batch failed, and its `ROLLBACK` failed too. The run stops
rather than retrying on a connection whose transaction state is unknown; the
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index eb01803137..147087c235 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1960,6 +1960,36 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
More: [docs/guides/troubleshooting.md#persistence-write-stall](../../docs/guides/troubleshooting.md#persistence-write-stall)
+### pg_connection_stuck
+
+<a id="pg_connection_stuck"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A pooled Postgres statement waited past the pool's statement_timeout plus grace with nothing coming back from the server, so the driver retired that connection; the statement and everything queued behind it failed with CONNECTION_STUCK. | A legitimate statement cannot outlive the server-side statement_timeout, so a connection that is still waiting past it is wedged: a pipeline the server and client no longer agree on, a transaction-mode pooler that swallowed a CancelRequest and left the backend in ClientRead, or a dead peer. Before #6383 such a connection held its queue forever while /health answered 200. The pool reconnects on its own; the warn line names the pool, the age, the queue depth and the statement by keyword and table. | Retry the failed call. If the line repeats, run gbrain doctor --json and report the warn lines with the operations that preceded them; GBRAIN_PG_STUCK_GRACE_MS raises the grace, and off disables the watchdog. Run: gbrain doctor --json | agent | `repeat the read that failed` | 1 | yes |
+
+More: [docs/ENGINES.md#pg-connection-stuck](../../docs/ENGINES.md#pg-connection-stuck)
+
+### pg_pool_stalled
+
+<a id="pg_pool_stalled"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The Postgres pool of a resident gbrain process has had connections checked out or statements waiting for one across two 30 s ticks without completing a single statement. | One slow statement is one quiet tick; two in a row with nothing settled means every checked-out connection is waiting on the server at once, which is what a wedged pool or an unreachable database looks like from inside the process. With the in-flight watchdog on, the stall ends within statement_timeout plus grace and a pg_pool_recovered line follows; with it off this line is the only trace. | Wait one more tick for pg_pool_recovered or pg_connection_stuck; if the line keeps repeating, check the database and pooler (gbrain doctor --json) and restart the process if the pool never recovers. Run: gbrain doctor --json | agent | `repeat the read that failed` | 1 | yes |
+
+More: [docs/ENGINES.md#pg-pool-stalled](../../docs/ENGINES.md#pg-pool-stalled)
+
+### pg_statement_build_failed
+
+<a id="pg_statement_build_failed"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A Postgres statement could not be built from its parameters (UNDEFINED_VALUE: a parameter was undefined; MAX_PARAMETERS_EXCEEDED: more than 65534 parameters) and was rejected before it reached the connection; no other statement was affected. | This is a gbrain programming error at the call site the warn line names by keyword and table. Before #6383 the same failure, when it happened behind another statement on the connection, rejected that other statement, desynced the connection and left every later statement on it hanging; the driver now rejects only the culprit. | The call that got this error failed cleanly and can be retried with corrected input; report the warn line (it names the statement) as a gbrain bug so the call site gets a null where it bound undefined. | host_admin | `gbrain doctor --json` | 1 | no |
+
+More: [docs/ENGINES.md#pg-statement-build-failed](../../docs/ENGINES.md#pg-statement-build-failed)
+
### pglite_busy
<a id="pglite_busy"></a>
diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.md
index ff9a8a9215..8534cafa49 100644
--- a/docs/mcp/DEPLOY.md
+++ b/docs/mcp/DEPLOY.md
@@ -678,6 +678,13 @@ Retry-After: 5
- Container health checks that probe `/health` treat the `503` as unhealthy and
restart the container. Pass `--fail-fast` (or set `GBRAIN_SERVE_FAIL_FAST=1`)
there so the process exits non-zero with the classified envelope on stderr.
+- A supervisor that should also catch a pool that accepts TCP but answers no
+ real request probes `/health?deep=1` instead: it runs `SELECT 1` through the
+ same pooled dispatch the MCP handlers use, returns the pool block
+ (`checked_out`, `waiters`, `inflight_oldest_ms`, `stuck_discards`, …) and
+ answers 503 when the probe times out or a statement is past the pool's
+ in-flight budget ([pool diagnostics](../ENGINES.md#pg-connection-stuck)). A
+ two-minute interval is fine; one deep probe runs at a time.
- A second `gbrain serve --http` on a port another server already holds exits
with `serve_port_in_use`. A Postgres connect failure keeps the degraded-engine
path (`GBRAIN_DB_ACCESS` marker, `gbrain db-repair`).
diff --git a/src/commands/serve-http-metrics.ts b/src/commands/serve-http-metrics.ts
index d1aadb52dd..577fcfd431 100644
--- a/src/commands/serve-http-metrics.ts
+++ b/src/commands/serve-http-metrics.ts
@@ -20,6 +20,8 @@
*/
import type { Express, NextFunction, Request, RequestHandler, Response } from 'express';
import type { BrainEngine } from '../core/engine.ts';
+import { resolveInflightTimeoutSeconds, resolveSessionTimeouts } from '../core/db.ts';
+import { poolHealthSnapshot, type PoolHealthSnapshot } from '../core/postgres-engine/pool-stats.ts';
import { VERSION } from '../version.ts';
import type { ServeHttpContext } from './serve-http.ts';
@@ -209,15 +211,76 @@ export async function probeLiveness(
}
}
-/** GET /health: liveness only (full stats are the admin-only /admin/api/full-stats). */
+/**
+ * #6383: why `/health` answered 200 through a 50-minute wedge: `probeLiveness`
+ * runs its `SELECT 1` on a reserved connection, and `reserve()` only ever
+ * claims an idle one, while the wedged connections sat in the driver's busy
+ * queue where ordinary handler statements are routed. `/health?deep=1` runs
+ * the probe through that ordinary pooled dispatch (no reservation) and reads
+ * the pool's own numbers; it answers 503 when the probe does not return within
+ * its budget, when a statement has waited past the read pool's in-flight
+ * budget, or when the previous deep probe is still pending. One deep probe is
+ * in flight per engine at a time, so a stuck one is never joined by a pile.
+ */
+export type DeepHealthResult =
+ | { ok: true; status: 200; body: { status: 'ok'; deep: true; version: string; engine: string; probe_ms: number; pool: PoolHealthSnapshot | null } }
+ | { ok: false; status: 503; body: { error: 'service_unavailable'; error_description: string; deep: true; pool: PoolHealthSnapshot | null } };
+
+const pendingDeepProbes = new WeakMap<object, Promise<unknown>>();
+
+/** The read pool's in-flight budget in ms (statement_timeout + grace), or null when the watchdog is off. */
+export function readPoolInflightBudgetMs(): number | null {
+ const seconds = resolveInflightTimeoutSeconds(resolveSessionTimeouts().statement_timeout);
+ return seconds === null ? null : seconds * 1000;
+}
+
+export async function probeDeepHealth(
+ engine: BrainEngine,
+ engineName: string,
+ version: string,
+ timeoutMs: number = HEALTH_TIMEOUT_MS,
+ budgetMs: number | null = readPoolInflightBudgetMs(),
+): Promise<DeepHealthResult> {
+ const pool = () => poolHealthSnapshot(engine);
+ const unavailable = (why: string): DeepHealthResult => ({ ok: false, status: 503, body: { error: 'service_unavailable', error_description: why, deep: true, pool: pool() } });
+ if (pendingDeepProbes.has(engine)) return unavailable('Deep health probe still pending from an earlier request (a pooled SELECT 1 has not answered)');
+ const started = Date.now();
+ const probe = engine.executeRaw('SELECT 1');
+ pendingDeepProbes.set(engine, probe);
+ probe.then(() => pendingDeepProbes.delete(engine), () => pendingDeepProbes.delete(engine));
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ try {
+ await Promise.race([
+ probe,
+ new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('health_timeout')), timeoutMs); }),
+ ]);
+ } catch (e: unknown) {
+ const msg = e instanceof Error ? e.message : 'unknown';
+ return unavailable(msg === 'health_timeout'
+ ? `Deep health probe timed out: a pooled SELECT 1 did not answer within ${timeoutMs} ms`
+ : `Deep health probe failed: ${msg}`);
+ } finally {
+ if (timer !== null) clearTimeout(timer);
+ }
+ const snapshot = pool();
+ if (snapshot && budgetMs !== null && snapshot.inflight_oldest_ms > budgetMs) {
+ return unavailable(`A pooled statement has waited ${snapshot.inflight_oldest_ms} ms for the server, past the pool budget of ${budgetMs} ms`);
+ }
+ return { ok: true, status: 200, body: { status: 'ok', deep: true, version, engine: engineName, probe_ms: Date.now() - started, pool: snapshot } };
+}
+
+/** GET /health: liveness only (full stats are the admin-only /admin/api/full-stats); `?deep=1` probes through the ordinary pool. */
export function mountHealth(app: Express, ctx: ServeHttpContext): void {
const { engine, config } = ctx;
// ---------------------------------------------------------------------------
// Health check — liveness only. Full engine stats live at
// /admin/api/full-stats (requireAdmin). See probeLiveness above for the why.
// ---------------------------------------------------------------------------
- app.get('/health', async (_req, res) => {
- const result = await probeLiveness(engine, config.engine || 'pglite', VERSION);
+ app.get('/health', async (req, res) => {
+ const deep = req.query.deep;
+ const result = deep === '1' || deep === 'true'
+ ? await probeDeepHealth(engine, config.engine || 'pglite', VERSION)
+ : await probeLiveness(engine, config.engine || 'pglite', VERSION);
res.status(result.status).json(result.body);
});
}
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 860b1789d8..99cbbaac7c 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -1,4 +1,5 @@
import { spawnSync } from 'node:child_process';
+import { PoolStallWatch } from '../core/postgres-engine/pool-stall-watch.ts';
import type { BrainEngine } from '../core/engine.ts';
// C10: `--fail-fast` / GBRAIN_SERVE_FAIL_FAST=1 — exit with the classified envelope instead of status-only/degraded mode (decided in src/cli.ts's connect path; F4's status mode consults it too).
export { serveFailFastRequested, writeServeFailFastEnvelope } from '../core/serve-fail-fast.ts';
@@ -245,6 +246,8 @@ export async function runServe(
console.error(`[gbrain serve] ignoring GBRAIN_SURFACE="${resolved.invalidEnv}" (use verbs | starter | full)`);
}
console.error(`[gbrain serve] surface=${surface} (source: ${SURFACE_SOURCE_LABEL[resolved.source]})`);
+ // #6383: the pool stall line (Postgres only; the watch reports nothing for an engine without pool numbers).
+ if (engine.kind === 'postgres') new PoolStallWatch(engine, (line) => console.error(line)).start();
// #4768: stdio read-only access ceiling. HTTP refuses it: per-token grants
// (auth rescope-token --operations / rescope-client) are its operation control.
const access = parseAccessFlag(args);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 3d867075a0..05406a09f8 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -369,6 +369,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.141.0', text: 'On Postgres, the first search of a process whose planner statistics on `pages` or `content_chunks` are absent (after pg_upgrade or a deleted pg_statistic, which autovacuum does not restore) now collects them in the background with the bounded refresh import already runs; without them a search on 5,000 pages took 50 to 60 s. Doctor `planner_stats_stale` names the absent columns and `gbrain repair planner-stats --apply` collects them. On PGLite, writes through the engine\'s SQL helpers now pass the same WAL checkpoint guard as other writes, so `gbrain extract` no longer wedges at 50,000 pages.' },
// Wave 8 perf (GBRA-75).
{ since: '0.60.146.0', text: 'On PGLite, a vector index build now sizes its memory to the index and finishes at 50,000 pages (248,802 chunks: 11 minutes, then vector search in about 27 ms instead of 1.7 s); a brain too large for the index to fit in PGLite\'s 2 GiB memory (about 300,000 1024-dimension chunks) gets `pglite_vector_index_too_large` with a read-only move-to-Postgres preview instead of running out of memory, and search keeps working unindexed. PGLite now starts with no parallel maintenance workers and `max_wal_size=8GB`, so a single large statement no longer wedges on its own checkpoint; between statements WAL is still checkpointed at 256 MB. In a brain folder without the Git durability hook, the Git effects a write leaves now finish in batches, so a 50,000-page import no longer leaves about 30,000 of them for `gbrain serve` to drain, and a first sync of already-imported files waives them in batched transactions.' },
+ { since: '0.60.148.0', text: 'On Postgres, a pooled statement that waits past the pool\'s statement_timeout plus 30 s (GBRAIN_PG_STUCK_GRACE_MS) with nothing coming back now fails with CONNECTION_STUCK and its connection is replaced, instead of holding the pool until a restart; `GBRAIN_PG_STUCK_GRACE_MS=off` keeps the old behavior. A statement with an undefined parameter now fails alone (`pg_statement_build_failed` names it) instead of desyncing its connection. `gbrain serve --http` answers `/health?deep=1` with a pooled probe and the pool numbers.' },
{ since: '0.60.147.0', text: 'In a brain folder with the Git durability hook, a write that arrives while the effect worker commits a backlog of Git effects now publishes after the group in flight, inside its 5 s wait, instead of returning pending after the whole backlog; Git effects still commit in order. A write waiting on a busy worktree is reported as `writer_busy` without a stale preparing phase.' },
];
diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.ts
index 999ae44d15..b142b3cd1d 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 { gbrainApplicationName, resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, resolveSharedTypes, endPoolBounded } from './db.ts';
+import { gbrainApplicationName, resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, resolveSharedTypes, endPoolBounded, poolHealthOptions, type PoolHealthHooks } from './db.ts';
import { redactPgUrl } from './url-redact.ts';
import { logConnectionEvent } from './connection-audit.ts';
@@ -74,6 +74,8 @@ export interface ConnectionManagerOpts {
readPoolOwnedExternally?: boolean;
/** #5730: told when the driver discards a pooled connection left inside a transaction. */
onpoisoned?: (pool: 'read' | 'direct', status: string) => void;
+ /** #6383: the driver's stuck-connection and build-failure reports, per pool (`onpoisoned` stays separate for its callers). */
+ health?: (pool: 'read' | 'direct') => Omit<PoolHealthHooks, 'onpoisoned'>;
}
/** Default direct-pool size (P1 raised from 2 to 3). Override via env. */
@@ -352,10 +354,10 @@ export class ConnectionManager {
max_lifetime: resolveMaxLifetimeSeconds(),
types: { bigint: postgres.BigInt },
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
- onpoisoned: (status: string) => this.opts.onpoisoned?.('read', status),
shared_types: resolveSharedTypes(this.opts.url),
};
const timeouts = resolveSessionTimeouts();
+ Object.assign(opts, poolHealthOptions({ ...this.opts.health?.('read'), onpoisoned: (status: string) => this.opts.onpoisoned?.('read', status) }, timeouts.statement_timeout));
if (Object.keys(timeouts).length > 0) opts.connection = timeouts;
const prepare = resolvePrepare(this.opts.url);
if (typeof prepare === 'boolean') opts.prepare = prepare;
@@ -504,7 +506,7 @@ export class ConnectionManager {
// here, so the prepare-cache invalidation issue doesn't apply.
prepare: true,
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
- onpoisoned: (status: string) => this.opts.onpoisoned?.('direct', status),
+ ...poolHealthOptions({ ...this.opts.health?.('direct'), onpoisoned: (status: string) => this.opts.onpoisoned?.('direct', status) }, String(DDL_STMT_TIMEOUT_MS)),
shared_types: resolveSharedTypes(this._directUrl),
// Apply DDL session GUCs as connection startup parameters (durable
// through any intermediary pooling layer, same trick as
diff --git a/src/core/db.ts b/src/core/db.ts
index 9c6e7c6f3d..2f90fbc38c 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -296,6 +296,61 @@ export function gbrainApplicationName(): string {
return `gbrain ${owner.kind}:${owner.pid}:${(owner.nonce ?? '').slice(0, 8)}`.slice(0, 63);
}
+/**
+ * #6383: the driver's pool-health hooks and the in-flight watchdog budget, one
+ * set per pool. `PoolHealthHooks` is what an engine passes to every pool it
+ * opens; `poolHealthOptions` turns it into postgres.js options.
+ */
+export interface StuckConnectionInfo { age_ms: number; queued: number; statement: string }
+export interface PoolHealthHooks {
+ /** #5730: a connection came back to the pool inside a transaction and was discarded. */
+ onpoisoned?: (status: string) => void;
+ /** #6383: the in-flight watchdog retired a connection whose statement never answered. */
+ onstuck?: (info: StuckConnectionInfo) => void;
+ /** #6383: a statement failed to build (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) and was rejected alone. */
+ onbuilderror?: (code: string, statement: string) => void;
+}
+
+const DEFAULT_STUCK_GRACE_MS = 30_000;
+
+/** A `statement_timeout` GUC value in milliseconds (a bare number is milliseconds), or null when unset or 0. */
+export function gucMilliseconds(value: string | undefined): number | null {
+ if (value === undefined) return null;
+ const m = /^\s*(\d+(?:\.\d+)?)\s*(us|ms|s|min|h|d)?\s*$/i.exec(value);
+ if (!m) return null;
+ const n = Number(m[1]);
+ const unit = (m[2] ?? 'ms').toLowerCase();
+ const ms = unit === 'us' ? n / 1000 : unit === 'ms' ? n : unit === 's' ? n * 1000 : unit === 'min' ? n * 60_000 : unit === 'h' ? n * 3_600_000 : n * 86_400_000;
+ return ms > 0 ? ms : null;
+}
+
+/**
+ * #6383: seconds a head statement may wait with nothing coming back before the
+ * driver retires its connection: the pool's `statement_timeout` plus
+ * `GBRAIN_PG_STUCK_GRACE_MS` (default 30000). A legitimate statement cannot
+ * outlive the server-side timeout, so only a wedged connection (a desynced
+ * pipeline, a pooler that swallowed a CancelRequest, a dead peer) reaches it.
+ * Null, which disables the watchdog, when the statement timeout is off or the
+ * grace is `0`/`off`.
+ */
+export function resolveInflightTimeoutSeconds(statementTimeout: string | undefined): number | null {
+ const raw = process.env.GBRAIN_PG_STUCK_GRACE_MS;
+ if (raw === '0' || raw === 'off') return null;
+ const grace = raw !== undefined && Number.isFinite(Number(raw)) && Number(raw) > 0 ? Number(raw) : DEFAULT_STUCK_GRACE_MS;
+ const budget = gucMilliseconds(statementTimeout);
+ return budget === null ? null : Math.ceil((budget + grace) / 1000);
+}
+
+/** The postgres.js options for `PoolHealthHooks` on a pool whose connections start with `connection.statement_timeout`. */
+export function poolHealthOptions(hooks: PoolHealthHooks | undefined, statementTimeout: string | undefined): Record<string, unknown> {
+ return {
+ onpoisoned: hooks?.onpoisoned,
+ onstuck: hooks?.onstuck,
+ onbuilderror: hooks?.onbuilderror,
+ inflight_timeout: resolveInflightTimeoutSeconds(statementTimeout),
+ };
+}
+
export function resolveSessionTimeouts(): Record<string, string> {
const out: Record<string, string> = {};
const add = (envKey: string, gucKey: string, defaultVal: string) => {
@@ -353,7 +408,7 @@ export function getConnection(): ReturnType<typeof postgres> {
*
* Back-compat: callers that ignore the return value are unaffected.
*/
-export async function connect(config: EngineConfig, hooks: { onpoisoned?: (status: string) => void } = {}): Promise<boolean> {
+export async function connect(config: EngineConfig, hooks: PoolHealthHooks = {}): Promise<boolean> {
if (sql) {
// Warn if a different URL is passed — the old connection is still in use
if (config.database_url && connectedUrl && config.database_url !== connectedUrl) {
@@ -389,7 +444,7 @@ export async function connect(config: EngineConfig, hooks: { onpoisoned?: (statu
// during migrations + initSchema, and breaks stdout-parsing callers like
// `gbrain jobs submit --json | ...`). Opt back in with GBRAIN_PG_NOTICES=1.
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
- onpoisoned: hooks.onpoisoned,
+ ...poolHealthOptions(hooks, timeouts.statement_timeout),
shared_types: resolveSharedTypes(url),
};
opts.connection = { ...timeouts, application_name: gbrainApplicationName() };
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 23d5409da9..808f25aa16 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -307,6 +307,9 @@ export const CODES = {
pending_writes: { class: 'retryable', summary: "A pending source write prevents verified completion." },
permission_denied: { class: 'host_only', summary: "This caller is not authorized for the operation." },
persistence_write_stall: { class: 'host_only', summary: "A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it.", why: "The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own.", docs: 'docs/guides/troubleshooting.md#persistence-write-stall', suggestion: 'Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the owner, the stuck request's claim phase and the writes waiting behind it, read-only.", requires_exclusive: false } },
+ pg_connection_stuck: { class: 'retryable', summary: "A pooled Postgres statement waited past the pool's statement_timeout plus grace with nothing coming back from the server, so the driver retired that connection; the statement and everything queued behind it failed with CONNECTION_STUCK.", why: "A legitimate statement cannot outlive the server-side statement_timeout, so a connection that is still waiting past it is wedged: a pipeline the server and client no longer agree on, a transaction-mode pooler that swallowed a CancelRequest and left the backend in ClientRead, or a dead peer. Before #6383 such a connection held its queue forever while /health answered 200. The pool reconnects on its own; the warn line names the pool, the age, the queue depth and the statement by keyword and table.", docs: 'docs/ENGINES.md#pg-connection-stuck', suggestion: 'Retry the failed call. If the line repeats, run gbrain doctor --json and report the warn lines with the operations that preceded them; GBRAIN_PG_STUCK_GRACE_MS raises the grace, and off disables the watchdog.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports pool pressure, the pooler mode and the recent persistence hold lines beside this warning.', requires_exclusive: false } },
+ pg_pool_stalled: { class: 'retryable', summary: "The Postgres pool of a resident gbrain process has had connections checked out or statements waiting for one across two 30 s ticks without completing a single statement.", why: "One slow statement is one quiet tick; two in a row with nothing settled means every checked-out connection is waiting on the server at once, which is what a wedged pool or an unreachable database looks like from inside the process. With the in-flight watchdog on, the stall ends within statement_timeout plus grace and a pg_pool_recovered line follows; with it off this line is the only trace.", docs: 'docs/ENGINES.md#pg-pool-stalled', suggestion: 'Wait one more tick for pg_pool_recovered or pg_connection_stuck; if the line keeps repeating, check the database and pooler (gbrain doctor --json) and restart the process if the pool never recovers.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: checks the database and pooler from a fresh process beside the stalled one.', requires_exclusive: false } },
+ pg_statement_build_failed: { class: 'server', summary: "A Postgres statement could not be built from its parameters (UNDEFINED_VALUE: a parameter was undefined; MAX_PARAMETERS_EXCEEDED: more than 65534 parameters) and was rejected before it reached the connection; no other statement was affected.", why: "This is a gbrain programming error at the call site the warn line names by keyword and table. Before #6383 the same failure, when it happened behind another statement on the connection, rejected that other statement, desynced the connection and left every later statement on it hanging; the driver now rejects only the culprit.", docs: 'docs/ENGINES.md#pg-statement-build-failed', suggestion: 'The call that got this error failed cleanly and can be retried with corrected input; report the warn line (it names the statement) as a gbrain bug so the call site gets a null where it bound undefined.' },
pglite_busy: { class: 'retryable', summary: "Another gbrain process holds this PGLite brain's single-writer lock.", reasons: ['timeout', 'live_serve'], suggestion: 'Wait for the current command or server to close, then retry. Do not remove a live lock.' },
pglite_vector_index_too_large: { class: 'unavailable', summary: "A PGLite vector (HNSW) index build was refused before it started because its in-memory graph would not fit PGLite's WebAssembly heap.", why: "pglite.wasm caps memory at 2 GiB and pgvector keeps the whole HNSW graph in memory while it builds; a build past the budget used to run out of memory or fall back to hours of on-disk inserts. Vector search keeps working with exact scans.", docs: 'docs/ENGINES.md#pglite-vector-index-ceiling', suggestion: 'Preview a move to Postgres (read-only): gbrain migrate --to postgres --plan --json', fix: { argv: ['gbrain', 'migrate', '--to', 'postgres', '--plan', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists what moves to Postgres, the blockers and the exact run command.', requires_exclusive: false } },
plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },
diff --git a/src/core/persistence/consumer-heartbeat.ts b/src/core/persistence/consumer-heartbeat.ts
index 91791366ba..e0801248ed 100644
--- a/src/core/persistence/consumer-heartbeat.ts
+++ b/src/core/persistence/consumer-heartbeat.ts
@@ -50,7 +50,8 @@ export const CONSUMER_DEADLINE_MS = 5_000;
export type ConsumerRowMode = 'probing' | 'full' | 'waiter_only' | 'promoted';
/** Process identity: `{ pid, nonce, pid_ns }`; `kind` names the gbrain command. */
export interface ConsumerProcessIdentity { pid: number; nonce: string; pid_ns: string | null }
-export interface ConsumerPool { checked_out: number; max: number; waiters: number }
+/** The pool numbers a heartbeat row carries; `inflight_oldest_ms` and `completed` (#6383) are absent from rows an older owner wrote. */
+export interface ConsumerPool { checked_out: number; max: number; waiters: number; inflight_oldest_ms?: number; completed?: number }
export interface ConsumerRow {
host_id: string;
pid: number;
diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.ts
index 45b542ac97..dee14bda18 100644
--- a/src/core/persistence/diagnostics.ts
+++ b/src/core/persistence/diagnostics.ts
@@ -6,8 +6,8 @@ import { WRITER_INSPECTION_HINT } from './admin-intent.ts';
import { writeHealth } from './health.ts';
import { claimStall, claimStateOf, isOwnerThisProcess, sqlLabel, type ClaimRow, type ClaimState, type ClaimStall } from './claim-phase.ts';
import { cliRenderContext, renderAction, type Action, type RenderedAction } from '../agent-output.ts';
-import { enginePoolStats, type DriverPoolStats } from '../postgres-engine/pool-stats.ts';
-import { listHostConsumers, type ListedConsumer } from './consumer-heartbeat.ts';
+import { enginePoolStats } from '../postgres-engine/pool-stats.ts';
+import { listHostConsumers, type ConsumerPool, type ListedConsumer } from './consumer-heartbeat.ts';
import type { WriteRequestState } from './types.ts';
import { preparationBudgetMs } from './preparation-budget.ts';
import { readWriteSwitchSnapshot } from './switches.ts';
@@ -109,7 +109,7 @@ export async function readOwnerBackends(engine: BrainEngine, owners: Array<Pick<
}
}
/** #6317 (C1): the pool numbers for a running claim: this process's driver when it owns the claim, else the owner's heartbeat row. */
-function claimPool(engine: BrainEngine, claim: ClaimState, row: ListedConsumer | null): { pool: DriverPoolStats | null; pool_source: 'driver' | 'heartbeat' | null } {
+function claimPool(engine: BrainEngine, claim: ClaimState, row: ListedConsumer | null): { pool: ConsumerPool | null; pool_source: 'driver' | 'heartbeat' | null } {
if (isOwnerThisProcess(claim.owner)) return { pool: enginePoolStats(engine), pool_source: enginePoolStats(engine) ? 'driver' : null };
return { pool: row?.pool ?? null, pool_source: row?.pool ? 'heartbeat' : null };
}
diff --git a/src/core/pool-gauge.ts b/src/core/pool-gauge.ts
index 42ae42d820..6b0b257230 100644
--- a/src/core/pool-gauge.ts
+++ b/src/core/pool-gauge.ts
@@ -17,6 +17,8 @@
* at zero so a missed acquire can never underflow into negative counts.
*/
+import { sqlLabel } from './persistence/claim-phase.ts';
+
/** Which engine seam the in-flight call went through. */
export type GaugeKind = 'raw' | 'direct' | 'reserved' | 'tx';
@@ -90,3 +92,46 @@ export function formatPoisonedDiscardWarning(pool: 'read' | 'direct', status: st
` cause="a connection came back to the pool inside a transaction; it was discarded and replaced"` +
` fix="gbrain doctor --json" docs=docs/ENGINES.md#pg-connection-poisoned`;
}
+
+/**
+ * #6383: connections the vendored driver's in-flight watchdog retired because a
+ * statement waited `statement_timeout + grace` with nothing coming back, and
+ * statements the driver rejected alone because they failed to build. Each is
+ * counted once and logged as one fixed-shape warn line. The statement is named
+ * by its first keyword and table (`sqlLabel`), never its text or parameters.
+ */
+export class PoolIncidentCounter {
+ private stuck = 0;
+ private buildFailures = 0;
+
+ get stuckCount(): number {
+ return this.stuck;
+ }
+
+ get buildFailureCount(): number {
+ return this.buildFailures;
+ }
+
+ recordStuck(pool: 'read' | 'direct', info: { age_ms: number; queued: number; statement: string }): void {
+ this.stuck += 1;
+ try { console.warn(formatStuckConnectionWarning(pool, info)); } catch { /* best-effort */ }
+ }
+
+ recordBuildFailure(pool: 'read' | 'direct', code: string, statement: string): void {
+ this.buildFailures += 1;
+ try { console.warn(formatBuildFailureWarning(pool, code, statement)); } catch { /* best-effort */ }
+ }
+}
+
+export function formatStuckConnectionWarning(pool: 'read' | 'direct', info: { age_ms: number; queued: number; statement: string }): string {
+ return `[gbrain] warn code=pg_connection_stuck pool=${pool} age_ms=${Math.max(0, Math.round(info.age_ms))} queued=${Math.max(0, info.queued | 0)} sql=${sqlLabel(info.statement).replaceAll(' ', '_')}` +
+ ` cause="a statement waited past statement_timeout with nothing coming back from the server; the connection was retired and its queued statements failed with CONNECTION_STUCK"` +
+ ` fix="gbrain doctor --json" docs=docs/ENGINES.md#pg-connection-stuck`;
+}
+
+export function formatBuildFailureWarning(pool: 'read' | 'direct', code: string, statement: string): string {
+ const safeCode = /^[A-Z_]+$/.test(code) ? code : 'BUILD_FAILED';
+ return `[gbrain] warn code=pg_statement_build_failed error=${safeCode} pool=${pool} sql=${sqlLabel(statement).replaceAll(' ', '_')}` +
+ ` cause="a statement could not be built from its parameters and was rejected before it reached the connection; other statements were not affected"` +
+ ` fix="gbrain doctor --json" docs=docs/ENGINES.md#pg-statement-build-failed`;
+}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 2d85898045..7329d368a3 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -45,7 +45,7 @@ import {
type BatchAuditSite,
} from './retry.ts';
import { isConnectionEndedError } from './retry-matcher.ts';
-import { CheckoutGauge, PoisonedDiscardCounter, type PoolGaugeSnapshot } from './pool-gauge.ts';
+import { CheckoutGauge, PoisonedDiscardCounter, PoolIncidentCounter, type PoolGaugeSnapshot } from './pool-gauge.ts';
import { driverPoolStats, type DriverPoolStats } from './postgres-engine/pool-stats.ts';
import {
valueHash,
@@ -207,6 +207,12 @@ export class PostgresEngine implements BrainEngine {
private checkoutGauge = new CheckoutGauge();
private poisonedDiscards = new PoisonedDiscardCounter();
private readonly onPoisoned = (pool: 'read' | 'direct', status: string) => this.poisonedDiscards.record(pool, status);
+ /** #6383: stuck-connection retirements and build failures, per engine, with their warn lines. */
+ private poolIncidents = new PoolIncidentCounter();
+ private readonly poolHealth = (pool: 'read' | 'direct') => ({
+ onstuck: (info: db.StuckConnectionInfo) => this.poolIncidents.recordStuck(pool, info),
+ onbuilderror: (code: string, statement: string) => this.poolIncidents.recordBuildFailure(pool, code, statement),
+ });
/**
* #1471: module-singleton OWNERSHIP token. `true` only for the engine whose
* connect() actually created the shared db.ts `sql` singleton (returned
@@ -394,7 +400,7 @@ export class PostgresEngine implements BrainEngine {
// idempotent CREATE migrations flood stdout). Opt back in with
// GBRAIN_PG_NOTICES=1.
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
- onpoisoned: (status: string) => this.onPoisoned('read', status),
+ ...db.poolHealthOptions({ ...this.poolHealth('read'), onpoisoned: (status: string) => this.onPoisoned('read', status) }, timeouts.statement_timeout),
shared_types: db.resolveSharedTypes(url),
};
opts.connection = { ...timeouts, application_name: db.gbrainApplicationName() };
@@ -414,6 +420,7 @@ export class PostgresEngine implements BrainEngine {
parent: config.parentConnectionManager,
readPoolOwnedExternally: true, // we own _sql; manager just routes
onpoisoned: this.onPoisoned,
+ health: this.poolHealth,
});
this.connectionManager.setReadPool(this._sql);
} else {
@@ -422,7 +429,7 @@ export class PostgresEngine implements BrainEngine {
// decided atomically inside connect() (no await between its null-check and
// pool assignment), so two concurrent module connects can't both claim
// ownership. Store the token; only the owner tears the singleton down.
- this._ownsModuleSingleton = await db.connect(config, { onpoisoned: status => this.onPoisoned('read', status) });
+ this._ownsModuleSingleton = await db.connect(config, { ...this.poolHealth('read'), onpoisoned: status => this.onPoisoned('read', status) });
this._connectionStyle = 'module';
// v0.30.1: connection-manager wraps the module singleton.
@@ -432,6 +439,7 @@ export class PostgresEngine implements BrainEngine {
parent: config.parentConnectionManager,
readPoolOwnedExternally: true, // db.ts owns the pool
onpoisoned: this.onPoisoned,
+ health: this.poolHealth,
});
this.connectionManager.setReadPool(db.getConnection());
}
@@ -719,13 +727,15 @@ export class PostgresEngine implements BrainEngine {
/** #5801: observe connection acquisition (see CheckoutGauge.onCheckout). Duck-typed like getPoolDiagnostics. */
onCheckout(listener: () => void): () => void { return this.checkoutGauge.onCheckout(listener); }
- getPoolDiagnostics(): { tracked: PoolGaugeSnapshot; poolMax: number | null; poisonedDiscards: number; pool: DriverPoolStats | null; prepare: boolean | null } | null {
+ getPoolDiagnostics(): { tracked: PoolGaugeSnapshot; poolMax: number | null; poisonedDiscards: number; stuckDiscards: number; buildFailures: number; pool: DriverPoolStats | null; prepare: boolean | null } | null {
try {
const max = (this.sql as unknown as { options?: { max?: number } }).options?.max;
return {
tracked: this.checkoutGauge.snapshot(),
poolMax: typeof max === 'number' ? max : null,
poisonedDiscards: this.poisonedDiscards?.count ?? 0,
+ stuckDiscards: this.poolIncidents?.stuckCount ?? 0,
+ buildFailures: this.poolIncidents?.buildFailureCount ?? 0,
pool: driverPoolStats(this.sql),
prepare: (this.sql as unknown as { options?: { prepare?: boolean } }).options?.prepare ?? null,
};
diff --git a/src/core/postgres-engine/pool-stall-watch.ts b/src/core/postgres-engine/pool-stall-watch.ts
new file mode 100644
index 0000000000..d96598127e
--- /dev/null
+++ b/src/core/postgres-engine/pool-stall-watch.ts
@@ -0,0 +1,76 @@
+/**
+ * #6383: the pool stall line. A resident process (serve) ticks this every
+ * 30 s; when the pool has connections checked out or statements waiting for
+ * one and the driver settled nothing for two ticks in a row, one fixed-shape
+ * warn line per tick names the numbers, and one info line marks the recovery. With the
+ * in-flight watchdog on, a stall lasts at most one `statement_timeout + grace`
+ * budget; with it off (`GBRAIN_PG_STUCK_GRACE_MS=off`) this line is the only
+ * trace a wedged pool leaves, instead of fifty silent minutes.
+ */
+import { poolHealthSnapshot, type PoolHealthSnapshot } from './pool-stats.ts';
+
+export const POOL_STALL_TICK_MS = 30_000;
+
+export function formatPoolStalledWarning(pool: PoolHealthSnapshot, sinceMs: number): string {
+ return `[gbrain] warn code=pg_pool_stalled checked_out=${pool.checked_out} max=${pool.max} waiters=${pool.waiters}` +
+ ` inflight_oldest_ms=${pool.inflight_oldest_ms} completed_delta=0 stalled_ms=${Math.max(0, Math.round(sinceMs))}` +
+ ` cause="connections are checked out but no statement has completed since the last tick"` +
+ ` fix="gbrain doctor --json" docs=docs/ENGINES.md#pg-pool-stalled`;
+}
+
+export function formatPoolRecoveredInfo(stalledMs: number, completedDelta: number): string {
+ return `[gbrain] info code=pg_pool_recovered stalled_ms=${Math.max(0, Math.round(stalledMs))} completed_delta=${completedDelta}`;
+}
+
+export class PoolStallWatch {
+ private lastCompleted: number | null = null;
+ private stalledSince: number | null = null;
+ private quietTicks = 0;
+ private intervalMs = POOL_STALL_TICK_MS;
+ private timer: ReturnType<typeof setInterval> | null = null;
+
+ constructor(
+ private readonly engine: unknown,
+ private readonly log: (line: string) => void = (line) => console.warn(line),
+ private readonly now: () => number = Date.now,
+ ) {}
+
+ /** One observation; returns what it logged, if anything. Exposed for tests; `start` drives it on a timer. */
+ tick(): 'stalled' | 'recovered' | null {
+ const pool = poolHealthSnapshot(this.engine);
+ if (!pool) return null;
+ const previous = this.lastCompleted;
+ this.lastCompleted = pool.completed;
+ if (previous === null) return null;
+ const busy = pool.checked_out > 0 || pool.waiters > 0;
+ const advanced = pool.completed !== previous;
+ if (busy && !advanced) {
+ // The first quiet tick is one slow statement; the line starts on the second, 60 s without a round trip.
+ if (this.quietTicks++ === 0) return null;
+ this.stalledSince ??= this.now() - 2 * this.intervalMs;
+ this.log(formatPoolStalledWarning(pool, this.now() - this.stalledSince));
+ return 'stalled';
+ }
+ this.quietTicks = 0;
+ if (this.stalledSince !== null) {
+ const since = this.stalledSince;
+ this.stalledSince = null;
+ this.log(formatPoolRecoveredInfo(this.now() - since, pool.completed - previous));
+ return 'recovered';
+ }
+ return null;
+ }
+
+ start(intervalMs: number = POOL_STALL_TICK_MS): this {
+ if (this.timer) return this;
+ this.intervalMs = intervalMs;
+ this.timer = setInterval(() => { try { this.tick(); } catch { /* diagnostic only */ } }, intervalMs);
+ this.timer.unref?.();
+ return this;
+ }
+
+ stop(): void {
+ if (this.timer) clearInterval(this.timer);
+ this.timer = null;
+ }
+}
diff --git a/src/core/postgres-engine/pool-stats.ts b/src/core/postgres-engine/pool-stats.ts
index 455422d045..595e9d6354 100644
--- a/src/core/postgres-engine/pool-stats.ts
+++ b/src/core/postgres-engine/pool-stats.ts
@@ -15,15 +15,25 @@ export interface DriverPoolStats {
checked_out: number;
max: number;
waiters: number;
+ /** #6383: age of the oldest statement still waiting for the server, 0 when nothing is in flight. */
+ inflight_oldest_ms: number;
+ /** #6383: statements the pool has settled since it opened; a pool that is checked out but never advances this is stalled. */
+ completed: number;
}
-interface DriverQueues { max: number; open: number; busy: number; full: number; reserved: number; connecting: number; closed: number; ended: number; queued: number }
+interface DriverQueues { max: number; open: number; busy: number; full: number; reserved: number; connecting: number; closed: number; ended: number; queued: number; inflight_oldest_ms?: number; completed?: number }
/** The pool numbers of one driver instance, or null when it exposes none. */
export function driverPoolStats(sql: unknown): DriverPoolStats | null {
const pool = (sql as { pool?: DriverQueues } | null)?.pool;
if (!pool || typeof pool.max !== 'number') return null;
- return { checked_out: pool.busy + pool.full + pool.reserved + pool.connecting, max: pool.max, waiters: pool.queued };
+ return {
+ checked_out: pool.busy + pool.full + pool.reserved + pool.connecting,
+ max: pool.max,
+ waiters: pool.queued,
+ inflight_oldest_ms: pool.inflight_oldest_ms ?? 0,
+ completed: pool.completed ?? 0,
+ };
}
/** The ordinary pool of an engine that reports one (`getPoolDiagnostics().pool`), else null. */
@@ -35,3 +45,25 @@ export function enginePoolStats(engine: unknown): DriverPoolStats | null {
return null;
}
}
+
+/** #6383: the ordinary pool's numbers plus the engine's incident counters, the block `/health?deep=1` and the stall watch report. */
+export interface PoolHealthSnapshot extends DriverPoolStats {
+ poisoned_discards: number;
+ stuck_discards: number;
+ build_failures: number;
+}
+
+export function poolHealthSnapshot(engine: unknown): PoolHealthSnapshot | null {
+ try {
+ const diagnostics = (engine as { getPoolDiagnostics?: () => { pool?: DriverPoolStats | null; poisonedDiscards?: number; stuckDiscards?: number; buildFailures?: number } | null } | null)?.getPoolDiagnostics?.();
+ if (!diagnostics?.pool) return null;
+ return {
+ ...diagnostics.pool,
+ poisoned_discards: diagnostics.poisonedDiscards ?? 0,
+ stuck_discards: diagnostics.stuckDiscards ?? 0,
+ build_failures: diagnostics.buildFailures ?? 0,
+ };
+ } catch {
+ return null;
+ }
+}
diff --git a/test/e2e/postgres-pipelined-build-failure-postgres.test.ts b/test/e2e/postgres-pipelined-build-failure-postgres.test.ts
new file mode 100644
index 0000000000..62f4dd9424
--- /dev/null
+++ b/test/e2e/postgres-pipelined-build-failure-postgres.test.ts
@@ -0,0 +1,131 @@
+/**
+ * #6383 (and the driver desync behind #6352): a statement that fails to build
+ * (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) used to join the connection's
+ * queue before it was built, so when another statement was already in flight
+ * the failure rejected that head statement with the wrong error, left the
+ * culprit queued with nothing on the wire, and every later reply on the socket
+ * was delivered one statement late. A describe-first statement then never got
+ * its ParameterDescription, so its Bind/Execute/Sync was never sent and the
+ * backend sat `active / ClientRead` until the process restarted.
+ *
+ * Protects: only the culprit rejects, with its own error; the head and every
+ * later statement resolve with their own rows; the backend returns to idle; a
+ * transaction with a bad member rolls back cleanly; the pool reports each
+ * build failure through `onbuilderror` with the statement's text and no
+ * parameter values. Regression that fails it on master: `next` and `later`
+ * never settle (the 5 s race below reports `hung`), and the backend stays
+ * `active`.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { createRequire } from 'node:module';
+import postgres from '#postgres';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+
+const url = process.env.DATABASE_URL;
+const opened: Array<{ end: (o?: { timeout?: number }) => Promise<void> }> = [];
+
+afterEach(async () => {
+ while (opened.length) await opened.pop()!.end({ timeout: 1 }).catch(() => {});
+});
+
+type Settled = { rows: unknown[] } | { code: string } | { hung: true };
+
+function settle(query: PromiseLike<unknown>, ms = 5000): Promise<Settled> {
+ return Promise.race([
+ Promise.resolve(query).then(rows => ({ rows: rows as unknown[] }), (e: { code?: string; message?: string }) => ({ code: e.code ?? e.message ?? 'error' })),
+ new Promise<Settled>(resolve => setTimeout(() => resolve({ hung: true }), ms)),
+ ]);
+}
+
+function pool(max: number, builds: Array<[string, string]>, driver: typeof postgres = postgres) {
+ assertSafeE2eDatabaseUrl(url!);
+ const appName = `gbrain-6383-${Math.random().toString(36).slice(2)}`;
+ const sql = driver(url!, {
+ max,
+ prepare: false,
+ shared_types: true,
+ onnotice: () => {},
+ connection: { application_name: appName },
+ onbuilderror: (code: string, statement: string) => { builds.push([code, statement]); },
+ } as Parameters<typeof postgres>[1]);
+ opened.push(sql);
+ return { sql, appName };
+}
+
+async function backendStates(appName: string): Promise<string[]> {
+ const observer = postgres(url!, { max: 1, onnotice: () => {} });
+ opened.push(observer);
+ const rows = await observer<{ state: string }[]>`SELECT state FROM pg_stat_activity WHERE application_name = ${appName}`;
+ return rows.map(r => r.state);
+}
+
+describe.skipIf(!url)('#6383 a statement that fails to build never desyncs its connection', () => {
+ test('a culprit pipelined behind a head statement rejects alone; head, a describe-first follower and later statements resolve', async () => {
+ const builds: Array<[string, string]> = [];
+ const { sql, appName } = pool(1, builds);
+ await sql`SELECT 1`;
+ const head = settle(sql`SELECT pg_sleep(0.3), 'head' AS who`);
+ const culprit = settle(sql`SELECT ${undefined as unknown as string}::text AS who`);
+ const next = settle(sql`SELECT 'next' AS who, ${1}::int AS n`);
+ expect(await head).toEqual({ rows: [{ pg_sleep: '', who: 'head' }] });
+ expect(await culprit).toEqual({ code: 'UNDEFINED_VALUE' });
+ expect(await next).toEqual({ rows: [{ who: 'next', n: 1 }] });
+ expect(await settle(sql`SELECT 'later' AS who`)).toEqual({ rows: [{ who: 'later' }] });
+ expect(await backendStates(appName)).toEqual(['idle']);
+ expect(builds).toEqual([['UNDEFINED_VALUE', 'SELECT $1::text AS who']]);
+ });
+
+ test('a culprit as the head statement of an idle connection leaves it usable, and so does one on a reserved connection', async () => {
+ const builds: Array<[string, string]> = [];
+ const { sql } = pool(1, builds);
+ expect(await settle(sql`SELECT ${undefined as unknown as string}::text`)).toEqual({ code: 'UNDEFINED_VALUE' });
+ expect(await settle(sql`SELECT 'after' AS who`)).toEqual({ rows: [{ who: 'after' }] });
+ const reserved = await sql.reserve();
+ expect(await settle(reserved`SELECT ${undefined as unknown as string}::text`)).toEqual({ code: 'UNDEFINED_VALUE' });
+ expect(await settle(reserved`SELECT 'reserved' AS who`)).toEqual({ rows: [{ who: 'reserved' }] });
+ reserved.release();
+ expect(await settle(sql`SELECT 'pooled' AS who`)).toEqual({ rows: [{ who: 'pooled' }] });
+ expect(builds.map(b => b[0])).toEqual(['UNDEFINED_VALUE', 'UNDEFINED_VALUE']);
+ });
+
+ test('a transaction with a bad member rolls back and the backend is idle, not left in the transaction', async () => {
+ const builds: Array<[string, string]> = [];
+ const { sql, appName } = pool(1, builds);
+ const tx = await settle(sql.begin(async tx => Promise.allSettled([
+ tx`SELECT 1 AS a`,
+ tx`SELECT ${undefined as unknown as string}::text`,
+ tx`SELECT 2 AS b, ${3}::int AS c`,
+ ])));
+ expect(tx).toEqual({ code: 'UNDEFINED_VALUE' });
+ expect(await settle(sql`SELECT 'after' AS who`)).toEqual({ rows: [{ who: 'after' }] });
+ expect(await backendStates(appName)).toEqual(['idle']);
+ });
+
+ test('MAX_PARAMETERS_EXCEEDED behind a head statement is rejected alone too', async () => {
+ const builds: Array<[string, string]> = [];
+ const { sql } = pool(1, builds);
+ await sql`SELECT 1`;
+ const head = settle(sql`SELECT pg_sleep(0.2), 'head' AS who`);
+ const tooMany = settle(sql.unsafe(`SELECT ${Array.from({ length: 65534 }, (_, i) => `$${i + 1}::int`).join(',')}`, Array.from({ length: 65534 }, (_, i) => i)));
+ const next = settle(sql`SELECT 'next' AS who, ${1}::int AS n`);
+ expect(await head).toEqual({ rows: [{ pg_sleep: '', who: 'head' }] });
+ expect(await tooMany).toEqual({ code: 'MAX_PARAMETERS_EXCEEDED' });
+ expect(await next).toEqual({ rows: [{ who: 'next', n: 1 }] });
+ expect(builds.map(b => b[0])).toEqual(['MAX_PARAMETERS_EXCEEDED']);
+ });
+
+ test('CommonJS build behaves the same', async () => {
+ const cjs = createRequire(import.meta.url)('#postgres') as typeof postgres;
+ expect(cjs).not.toBe(postgres);
+ const builds: Array<[string, string]> = [];
+ const { sql } = pool(1, builds, cjs);
+ await sql`SELECT 1`;
+ const head = settle(sql`SELECT pg_sleep(0.2), 'head' AS who`);
+ const culprit = settle(sql`SELECT ${undefined as unknown as string}::text AS who`);
+ const next = settle(sql`SELECT 'next' AS who, ${1}::int AS n`);
+ expect(await head).toEqual({ rows: [{ pg_sleep: '', who: 'head' }] });
+ expect(await culprit).toEqual({ code: 'UNDEFINED_VALUE' });
+ expect(await next).toEqual({ rows: [{ who: 'next', n: 1 }] });
+ expect(builds).toEqual([['UNDEFINED_VALUE', 'SELECT $1::text AS who']]);
+ });
+});
diff --git a/test/e2e/postgres-stuck-connection-postgres.test.ts b/test/e2e/postgres-stuck-connection-postgres.test.ts
new file mode 100644
index 0000000000..eabbf5e02a
--- /dev/null
+++ b/test/e2e/postgres-stuck-connection-postgres.test.ts
@@ -0,0 +1,149 @@
+/**
+ * #6383: the vendored driver's in-flight watchdog and live pool numbers.
+ *
+ * A connection whose head statement has waited `inflight_timeout` seconds
+ * with nothing coming back from the server (a desynced pipeline, a
+ * transaction pooler that swallowed a CancelRequest, a dead peer) is retired:
+ * the statement and everything queued behind it reject with
+ * `CONNECTION_STUCK`, the pool reports it once through `onstuck`, the
+ * connection leaves rotation before its socket closes, and the next statement
+ * runs on a fresh connection. A statement the server answers in time is never
+ * retired, because the budget is at least the server's own statement timeout.
+ *
+ * `sql.pool` used to be a construction-time snapshot (Object.assign read the
+ * getter once), so `busy` was always 0; it is live now and carries the oldest
+ * in-flight age and the completed count the stall watch and `/health?deep=1`
+ * read. Regression that fails it on master: `busy` stays 0 during `pg_sleep`,
+ * and a statement the server never answers hangs forever instead of
+ * rejecting with `CONNECTION_STUCK`.
+ */
+import { afterEach, describe, expect, spyOn, test } from 'bun:test';
+import postgres from '#postgres';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+
+const url = process.env.DATABASE_URL;
+const opened: Array<{ end: (o?: { timeout?: number }) => Promise<void> }> = [];
+
+afterEach(async () => {
+ while (opened.length) await opened.pop()!.end({ timeout: 1 }).catch(() => {});
+});
+
+type Settled = { rows: unknown[] } | { code: string } | { hung: true };
+
+function settle(query: PromiseLike<unknown>, ms = 5000): Promise<Settled> {
+ return Promise.race([
+ Promise.resolve(query).then(rows => ({ rows: rows as unknown[] }), (e: { code?: string; message?: string }) => ({ code: e.code ?? e.message ?? 'error' })),
+ new Promise<Settled>(resolve => setTimeout(() => resolve({ hung: true }), ms)),
+ ]);
+}
+
+function pool(max: number, inflightTimeout: number | null, stucks: unknown[]) {
+ assertSafeE2eDatabaseUrl(url!);
+ const sql = postgres(url!, {
+ max,
+ prepare: false,
+ onnotice: () => {},
+ // No server-side statement_timeout on these connections: the watchdog is the only bound.
+ connection: { application_name: `gbrain-6383-stuck-${Math.random().toString(36).slice(2)}` },
+ inflight_timeout: inflightTimeout,
+ onstuck: (info: unknown) => { stucks.push(info); },
+ } as Parameters<typeof postgres>[1]);
+ opened.push(sql);
+ return sql;
+}
+
+describe.skipIf(!url)('#6383 in-flight watchdog and live pool numbers', () => {
+ test('sql.pool is live: busy and inflight_oldest_ms move while a statement runs, completed counts settled statements', async () => {
+ const sql = pool(2, null, []);
+ await sql`SELECT 1`;
+ const before = sql.pool;
+ expect(before.open).toBe(1);
+ expect(before.busy).toBe(0);
+ const slow = sql`SELECT pg_sleep(0.4)`.execute();
+ await new Promise(r => setTimeout(r, 150));
+ const during = sql.pool;
+ expect(during.busy + during.full).toBe(1);
+ expect(during.inflight_oldest_ms).toBeGreaterThanOrEqual(100);
+ await slow;
+ const after = sql.pool;
+ expect(after.busy + after.full).toBe(0);
+ expect(after.inflight_oldest_ms).toBe(0);
+ expect(after.completed).toBeGreaterThan(before.completed);
+ });
+
+ test('a statement the server never answers in time rejects with CONNECTION_STUCK, its queued follower too, and the pool recovers on a fresh connection', async () => {
+ const stucks: Array<{ age_ms: number; queued: number; statement: string }> = [];
+ const sql = pool(1, 1, stucks);
+ await sql`SELECT 1`;
+ const started = Date.now();
+ const slow = settle(sql`SELECT pg_sleep(5), 'slow' AS who`);
+ await new Promise(r => setTimeout(r, 100));
+ const follower = settle(sql`SELECT 'follower' AS who`);
+ expect(await slow).toEqual({ code: 'CONNECTION_STUCK' });
+ expect(await follower).toEqual({ code: 'CONNECTION_STUCK' });
+ expect(Date.now() - started).toBeLessThan(3000);
+ expect(stucks).toHaveLength(1);
+ expect(stucks[0].queued).toBe(1);
+ expect(stucks[0].age_ms).toBeGreaterThanOrEqual(900);
+ expect(stucks[0].statement).toBe("SELECT pg_sleep(5), 'slow' AS who");
+ expect(sql.pool.busy + sql.pool.full).toBe(0);
+ expect(await settle(sql`SELECT 'fresh' AS who`)).toEqual({ rows: [{ who: 'fresh' }] });
+ expect(sql.pool.inflight_oldest_ms).toBe(0);
+ });
+
+ test('a stuck reserved connection rejects its holder and the pool serves the next caller', async () => {
+ const stucks: unknown[] = [];
+ const sql = pool(1, 1, stucks);
+ const reserved = await sql.reserve();
+ expect(await settle(reserved`SELECT pg_sleep(5)`)).toEqual({ code: 'CONNECTION_STUCK' });
+ expect(await settle(reserved`SELECT 1`)).toEqual({ code: 'CONNECTION_DESTROYED' });
+ reserved.release();
+ expect(await settle(sql`SELECT 'next' AS who`)).toEqual({ rows: [{ who: 'next' }] });
+ expect(stucks).toHaveLength(1);
+ });
+
+ test('a statement answered within the budget is never retired, and a null budget disables the watchdog', async () => {
+ const stucks: unknown[] = [];
+ const bounded = pool(1, 2, stucks);
+ expect(await settle(bounded`SELECT pg_sleep(0.5), 1 AS x`)).toEqual({ rows: [{ pg_sleep: '', x: 1 }] });
+ const unbounded = pool(1, null, stucks);
+ expect(await settle(unbounded`SELECT pg_sleep(1.2), 2 AS x`)).toEqual({ rows: [{ pg_sleep: '', x: 2 }] });
+ expect(stucks).toEqual([]);
+ });
+
+ test('engine: a stuck connection is counted once, logged as one pg_connection_stuck line, and seen by getPoolDiagnostics', async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const previous = { grace: process.env.GBRAIN_PG_STUCK_GRACE_MS, timeout: process.env.GBRAIN_STATEMENT_TIMEOUT };
+ // Budget = statement_timeout (500 ms) + grace (500 ms) = 1 s. The session below lifts its own server-side
+ // statement_timeout first, so the sleep is only ever ended by the watchdog.
+ process.env.GBRAIN_STATEMENT_TIMEOUT = '500ms';
+ process.env.GBRAIN_PG_STUCK_GRACE_MS = '500';
+ const engine = new PostgresEngine();
+ const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ await engine.connect({ engine: 'postgres', database_url: url!, poolSize: 2 });
+ const stuck = await settle(engine.withReservedConnection(async conn => {
+ await conn.executeRaw('SET statement_timeout = 0');
+ await conn.executeRaw('SELECT pg_sleep(5)');
+ }), 6000);
+ expect(stuck).toEqual({ code: 'CONNECTION_STUCK' });
+ const diagnostics = engine.getPoolDiagnostics();
+ expect(diagnostics?.stuckDiscards).toBe(1);
+ expect(diagnostics?.pool?.inflight_oldest_ms).toBe(0);
+ const rows = await engine.executeRaw<{ x: number }>('SELECT 1 AS x');
+ expect(rows).toEqual([{ x: 1 }]);
+ const lines = warn.mock.calls.map(c => String(c[0])).filter(l => l.includes('pg_connection_stuck'));
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toContain('pool=read');
+ expect(lines[0]).toContain('sql=SELECT');
+ expect(lines[0]).not.toContain('pg_sleep');
+ expect(lines[0]).not.toContain(url!);
+ } finally {
+ warn.mockRestore();
+ await engine.disconnect();
+ if (previous.grace === undefined) delete process.env.GBRAIN_PG_STUCK_GRACE_MS; else process.env.GBRAIN_PG_STUCK_GRACE_MS = previous.grace;
+ if (previous.timeout === undefined) delete process.env.GBRAIN_STATEMENT_TIMEOUT; else process.env.GBRAIN_STATEMENT_TIMEOUT = previous.timeout;
+ }
+ });
+});
diff --git a/test/pool-health-6383.test.ts b/test/pool-health-6383.test.ts
new file mode 100644
index 0000000000..0975e39cbe
--- /dev/null
+++ b/test/pool-health-6383.test.ts
@@ -0,0 +1,227 @@
+/**
+ * #6383: the gbrain side of the pool-health work, without a database.
+ *
+ * Protects: the in-flight budget derives from the pool's statement_timeout
+ * plus `GBRAIN_PG_STUCK_GRACE_MS` and switches off with the timeout or with
+ * `0`/`off`; the three warn lines keep the `code= cause= fix= docs=` contract
+ * and name a statement by keyword and table only; the stall watch speaks on
+ * the second quiet tick and announces recovery once; `/health?deep=1`
+ * answers 503 on a probe timeout, on a statement past the pool budget, and
+ * while an earlier deep probe is still pending, and 200 with the pool block
+ * otherwise.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { gucMilliseconds, poolHealthOptions, resolveInflightTimeoutSeconds } from '../src/core/db.ts';
+import { formatBuildFailureWarning, formatStuckConnectionWarning, PoolIncidentCounter } from '../src/core/pool-gauge.ts';
+import { driverPoolStats, poolHealthSnapshot } from '../src/core/postgres-engine/pool-stats.ts';
+import { formatPoolRecoveredInfo, formatPoolStalledWarning, PoolStallWatch } from '../src/core/postgres-engine/pool-stall-watch.ts';
+import { probeDeepHealth } from '../src/commands/serve-http-metrics.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+const previousGrace = process.env.GBRAIN_PG_STUCK_GRACE_MS;
+afterEach(() => {
+ if (previousGrace === undefined) delete process.env.GBRAIN_PG_STUCK_GRACE_MS; else process.env.GBRAIN_PG_STUCK_GRACE_MS = previousGrace;
+});
+
+describe('in-flight budget', () => {
+ test('gucMilliseconds reads every statement_timeout unit and treats a bare number as milliseconds', () => {
+ expect(gucMilliseconds('5min')).toBe(300_000);
+ expect(gucMilliseconds('30s')).toBe(30_000);
+ expect(gucMilliseconds('1800000')).toBe(1_800_000);
+ expect(gucMilliseconds('2h')).toBe(7_200_000);
+ expect(gucMilliseconds('500ms')).toBe(500);
+ expect(gucMilliseconds('0')).toBeNull();
+ expect(gucMilliseconds(undefined)).toBeNull();
+ expect(gucMilliseconds('soon')).toBeNull();
+ });
+
+ test('resolveInflightTimeoutSeconds is statement_timeout plus a 30 s default grace, in whole seconds', () => {
+ delete process.env.GBRAIN_PG_STUCK_GRACE_MS;
+ expect(resolveInflightTimeoutSeconds('5min')).toBe(330);
+ expect(resolveInflightTimeoutSeconds('1800000')).toBe(1830);
+ process.env.GBRAIN_PG_STUCK_GRACE_MS = '500';
+ expect(resolveInflightTimeoutSeconds('500ms')).toBe(1);
+ });
+
+ test('the watchdog is off without a statement timeout and with grace 0 or off', () => {
+ delete process.env.GBRAIN_PG_STUCK_GRACE_MS;
+ expect(resolveInflightTimeoutSeconds(undefined)).toBeNull();
+ process.env.GBRAIN_PG_STUCK_GRACE_MS = '0';
+ expect(resolveInflightTimeoutSeconds('5min')).toBeNull();
+ process.env.GBRAIN_PG_STUCK_GRACE_MS = 'off';
+ expect(resolveInflightTimeoutSeconds('5min')).toBeNull();
+ process.env.GBRAIN_PG_STUCK_GRACE_MS = 'nonsense';
+ expect(resolveInflightTimeoutSeconds('5min')).toBe(330);
+ });
+
+ test('poolHealthOptions carries the hooks and the budget into postgres.js options', () => {
+ delete process.env.GBRAIN_PG_STUCK_GRACE_MS;
+ const onstuck = () => {};
+ const options = poolHealthOptions({ onstuck }, '5min');
+ expect(options.onstuck).toBe(onstuck);
+ expect(options.onpoisoned).toBeUndefined();
+ expect(options.inflight_timeout).toBe(330);
+ expect(poolHealthOptions(undefined, undefined).inflight_timeout).toBeNull();
+ });
+});
+
+describe('warn lines', () => {
+ test('pg_connection_stuck names the pool, the age, the queue depth and the statement by keyword and table only', () => {
+ const line = formatStuckConnectionWarning('read', { age_ms: 330_412.6, queued: 3, statement: "SELECT p.id FROM pages p WHERE p.slug = $1 AND secret = 'x'" });
+ expect(line).toContain('[gbrain] warn code=pg_connection_stuck pool=read age_ms=330413 queued=3 sql=SELECT_pages');
+ expect(line).toContain('fix="gbrain doctor --json" docs=docs/ENGINES.md#pg-connection-stuck');
+ expect(line).not.toContain('secret');
+ });
+
+ test('pg_statement_build_failed names the error code and the statement by keyword and table only', () => {
+ const line = formatBuildFailureWarning('direct', 'UNDEFINED_VALUE', 'INSERT INTO mcp_request_log (a, b) VALUES ($1, $2)');
+ expect(line).toContain('code=pg_statement_build_failed error=UNDEFINED_VALUE pool=direct sql=INSERT_mcp_request_log');
+ expect(formatBuildFailureWarning('read', 'weird code', 'SELECT 1')).toContain('error=BUILD_FAILED');
+ });
+
+ test('PoolIncidentCounter counts each kind once per report', () => {
+ const counter = new PoolIncidentCounter();
+ const warn = console.warn;
+ const lines: string[] = [];
+ console.warn = (line: string) => { lines.push(line); };
+ try {
+ counter.recordStuck('read', { age_ms: 1, queued: 0, statement: 'SELECT 1' });
+ counter.recordBuildFailure('read', 'UNDEFINED_VALUE', 'SELECT $1');
+ counter.recordBuildFailure('direct', 'MAX_PARAMETERS_EXCEEDED', 'SELECT $1');
+ } finally {
+ console.warn = warn;
+ }
+ expect(counter.stuckCount).toBe(1);
+ expect(counter.buildFailureCount).toBe(2);
+ expect(lines.filter(l => l.includes('pg_connection_stuck'))).toHaveLength(1);
+ expect(lines.filter(l => l.includes('pg_statement_build_failed'))).toHaveLength(2);
+ });
+});
+
+function fakeEngine(state: { busy: number; queued: number; completed: number; oldest: number; executeRaw?: () => Promise<unknown> }) {
+ return {
+ kind: 'postgres',
+ executeRaw: () => (state.executeRaw ? state.executeRaw() : Promise.resolve([{ '?column?': 1 }])),
+ getPoolDiagnostics: () => ({
+ tracked: { raw: 0, direct: 0, reserved: 0, tx: 0 },
+ poolMax: 4,
+ poisonedDiscards: 1,
+ stuckDiscards: 2,
+ buildFailures: 3,
+ prepare: false,
+ pool: driverPoolStats({ pool: { max: 4, open: 4 - state.busy, busy: state.busy, full: 0, reserved: 0, connecting: 0, closed: 0, ended: 0, queued: state.queued, inflight_oldest_ms: state.oldest, completed: state.completed } }),
+ }),
+ } as unknown as BrainEngine;
+}
+
+describe('poolHealthSnapshot', () => {
+ test('joins the driver numbers with the engine counters, and is null for an engine without pool numbers', () => {
+ const snapshot = poolHealthSnapshot(fakeEngine({ busy: 1, queued: 2, completed: 10, oldest: 250 }));
+ expect(snapshot).toEqual({ checked_out: 1, max: 4, waiters: 2, inflight_oldest_ms: 250, completed: 10, poisoned_discards: 1, stuck_discards: 2, build_failures: 3 });
+ expect(poolHealthSnapshot({ kind: 'pglite' })).toBeNull();
+ expect(poolHealthSnapshot({ getPoolDiagnostics: () => { throw new Error('closed'); } })).toBeNull();
+ });
+});
+
+describe('PoolStallWatch', () => {
+ test('stays quiet while statements complete, speaks on the second quiet tick, repeats, and announces recovery once', () => {
+ const state = { busy: 1, queued: 0, completed: 10, oldest: 0 };
+ const lines: string[] = [];
+ let now = 1_000_000;
+ const watch = new PoolStallWatch(fakeEngine(state), (line) => lines.push(line), () => now);
+ expect(watch.tick()).toBeNull();
+ state.completed = 11;
+ now += 30_000;
+ expect(watch.tick()).toBeNull();
+ now += 30_000;
+ expect(watch.tick()).toBeNull();
+ now += 30_000;
+ state.oldest = 90_000;
+ expect(watch.tick()).toBe('stalled');
+ now += 30_000;
+ expect(watch.tick()).toBe('stalled');
+ state.completed = 12;
+ state.busy = 0;
+ now += 30_000;
+ expect(watch.tick()).toBe('recovered');
+ now += 30_000;
+ expect(watch.tick()).toBeNull();
+ expect(lines).toHaveLength(3);
+ expect(lines[0]).toBe(formatPoolStalledWarning({ checked_out: 1, max: 4, waiters: 0, inflight_oldest_ms: 90_000, completed: 11, poisoned_discards: 1, stuck_discards: 2, build_failures: 3 }, 60_000));
+ expect(lines[0]).toContain('code=pg_pool_stalled checked_out=1 max=4 waiters=0 inflight_oldest_ms=90000 completed_delta=0 stalled_ms=60000');
+ expect(lines[1]).toContain('stalled_ms=90000');
+ expect(lines[2]).toBe(formatPoolRecoveredInfo(120_000, 1));
+ });
+
+ test('an idle pool that completes nothing is not a stall', () => {
+ const state = { busy: 0, queued: 0, completed: 5, oldest: 0 };
+ const lines: string[] = [];
+ const watch = new PoolStallWatch(fakeEngine(state), (line) => lines.push(line), () => 0);
+ for (let i = 0; i < 5; i++) expect(watch.tick()).toBeNull();
+ expect(lines).toEqual([]);
+ });
+
+ test('reports nothing for an engine without pool numbers', () => {
+ const lines: string[] = [];
+ const watch = new PoolStallWatch({ kind: 'pglite' }, (line) => lines.push(line));
+ expect(watch.tick()).toBeNull();
+ expect(lines).toEqual([]);
+ });
+});
+
+describe('probeDeepHealth', () => {
+ test('200 with the pool block when the pooled SELECT 1 answers and nothing is past budget', async () => {
+ const result = await probeDeepHealth(fakeEngine({ busy: 1, queued: 0, completed: 3, oldest: 1200 }), 'postgres', '1.2.3', 100, 330_000);
+ expect(result.status).toBe(200);
+ if (result.ok) {
+ expect(result.body.deep).toBe(true);
+ expect(result.body.pool?.inflight_oldest_ms).toBe(1200);
+ expect(result.body.pool?.stuck_discards).toBe(2);
+ expect(result.body.engine).toBe('postgres');
+ }
+ });
+
+ test('503 when a statement has waited past the pool budget even though the probe answered', async () => {
+ const result = await probeDeepHealth(fakeEngine({ busy: 2, queued: 1, completed: 3, oldest: 400_000 }), 'postgres', '1.2.3', 100, 330_000);
+ expect(result.status).toBe(503);
+ if (!result.ok) {
+ expect(result.body.error_description).toContain('waited 400000 ms');
+ expect(result.body.pool?.waiters).toBe(1);
+ }
+ });
+
+ test('a null budget (watchdog off) skips the age rule', async () => {
+ const result = await probeDeepHealth(fakeEngine({ busy: 2, queued: 1, completed: 3, oldest: 400_000 }), 'postgres', '1.2.3', 100, null);
+ expect(result.status).toBe(200);
+ });
+
+ test('503 when the probe times out, and 503 again while that probe is still pending', async () => {
+ let release: () => void = () => {};
+ const pending = new Promise<unknown>(resolve => { release = () => resolve([]); });
+ const engine = fakeEngine({ busy: 4, queued: 2, completed: 3, oldest: 5000, executeRaw: () => pending });
+ const first = await probeDeepHealth(engine, 'postgres', '1.2.3', 20, 330_000);
+ expect(first.status).toBe(503);
+ if (!first.ok) expect(first.body.error_description).toContain('did not answer within 20 ms');
+ const second = await probeDeepHealth(engine, 'postgres', '1.2.3', 20, 330_000);
+ expect(second.status).toBe(503);
+ if (!second.ok) expect(second.body.error_description).toContain('still pending');
+ release();
+ await pending;
+ await new Promise(r => setTimeout(r, 0));
+ const third = await probeDeepHealth(fakeEngine({ busy: 0, queued: 0, completed: 4, oldest: 0 }), 'postgres', '1.2.3', 20, 330_000);
+ expect(third.status).toBe(200);
+ });
+
+ test('503 when the pooled probe rejects', async () => {
+ const result = await probeDeepHealth(fakeEngine({ busy: 0, queued: 0, completed: 0, oldest: 0, executeRaw: () => Promise.reject(new Error('write CONNECTION_STUCK host:5432')) }), 'postgres', '1.2.3', 100, 330_000);
+ expect(result.status).toBe(503);
+ if (!result.ok) expect(result.body.error_description).toContain('CONNECTION_STUCK');
+ });
+
+ test('a PGLite engine answers 200 with a null pool block', async () => {
+ const engine = { kind: 'pglite', executeRaw: async () => [] } as unknown as BrainEngine;
+ const result = await probeDeepHealth(engine, 'pglite', '1.2.3', 100, null);
+ expect(result.status).toBe(200);
+ if (result.ok) expect(result.body.pool).toBeNull();
+ });
+});
diff --git a/test/writer-status-owner-backends.test.ts b/test/writer-status-owner-backends.test.ts
index fc7588abac..688ae0fe53 100644
--- a/test/writer-status-owner-backends.test.ts
+++ b/test/writer-status-owner-backends.test.ts
@@ -77,7 +77,7 @@ describe('claim stamp identity and last_sql', () => {
});
test('driverPoolStats reads the vendored driver\'s queues and reports null for a driver without the accessor', () => {
- expect(driverPoolStats({ pool: { max: 10, open: 6, busy: 2, full: 1, reserved: 1, connecting: 0, closed: 0, ended: 0, queued: 3 } })).toEqual({ checked_out: 4, max: 10, waiters: 3 });
+ expect(driverPoolStats({ pool: { max: 10, open: 6, busy: 2, full: 1, reserved: 1, connecting: 0, closed: 0, ended: 0, queued: 3, inflight_oldest_ms: 250, completed: 42 } })).toEqual({ checked_out: 4, max: 10, waiters: 3, inflight_oldest_ms: 250, completed: 42 });
expect(driverPoolStats({})).toBeNull();
expect(driverPoolStats(null)).toBeNull();
});
diff --git a/vendor/README.md b/vendor/README.md
index d5b4763855..0efeedda69 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -37,6 +37,23 @@ must settle or retire the connection before another query can own it. This
is necessary for worker admission, query timeout and lease-release safety.
See issues #5466 and #5560 and `test/e2e/persistence-chaos.test.ts`.
+A statement is built and serialized before it joins a connection's queue
+(#6383). Stock postgres.js enqueues first, so a statement that fails to build
+(`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) behind an in-flight statement
+rejects that head statement with its error, stays queued with nothing on the
+wire, and every later reply on the socket is delivered one statement late until
+the process restarts; with the patch only the culprit rejects, reported through
+`onbuilderror(code, statement)` (template text with `$n` placeholders, no
+values). The same patch adds the in-flight watchdog: `inflight_timeout`
+(seconds) bounds how long a head statement may wait with nothing coming back;
+past it the statement and its queued followers reject with `CONNECTION_STUCK`,
+the pool parks the connection out of rotation, reports `onstuck({ age_ms,
+queued, statement })` and reconnects. `sql.pool` is a live property getter
+(stock `Object.assign` froze the #6317 numbers at construction) and carries
+`inflight_oldest_ms` and `completed`. Tests:
+`test/e2e/postgres-pipelined-build-failure-postgres.test.ts`,
+`test/e2e/postgres-stuck-connection-postgres.test.ts`.
+
The patch also lets a pool share the parameter types of a described statement
across its connections (`shared_types`, on by default; GBrain turns it off with
`GBRAIN_PG_TYPE_CACHE=0`). Stock postgres.js describes every parameterized
diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.js
index 4f654a37ab..e8ecf9da80 100644
--- a/vendor/postgres/cf/src/connection.js
+++ b/vendor/postgres/cf/src/connection.js
@@ -51,7 +51,7 @@ const errorFields = {
82 : 'routine' // R
}
-function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
+function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop } = {}) {
const {
sslnegotiation,
ssl,
@@ -77,6 +77,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
, idleTimer = timer(end, options.idle_timeout)
, lifeTimer = timer(end, options.max_lifetime)
, connectTimer = timer(connectTimedOut, options.connect_timeout)
+ , inflightTimer = timer(inflightTimedOut, options.inflight_timeout)
let socket = null
, cancelMessage
@@ -110,11 +111,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
, ended = null
, nonce = null
, query = null
+ , queryStart = 0
, final = null
const connection = {
queue: queues.closed,
idleTimer,
+ inflightSince: 0,
connect(query) {
initial = query
reconnect()
@@ -170,26 +173,88 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
if (q.cancelled)
return
+ // GBrain (#6383): a statement is built and serialized before it joins this connection's queue. It used to
+ // join first, so a statement that failed to build (UNDEFINED_VALUE, MAX_PARAMETERS_EXCEEDED) behind an
+ // in-flight one rejected that head statement with its error, stayed queued with nothing on the wire, and
+ // every later reply on the socket was delivered one statement late until the process restarted.
+ let bytes
try {
q.state = backend
+ build(q)
+ bytes = toBuffer(q)
+ } catch (error) {
+ if (!query) {
+ // An idle connection owns the ReadyForQuery its Sync produces, exactly as a failed head statement did.
+ query = q
+ query.active = true
+ write(Sync)
+ armInflight()
+ }
+ options.onbuilderror && reportBuildError(q, error)
+ queryError(q, error)
+ return true
+ }
+
+ try {
query
? sent.push(q)
- : (query = q, query.active = true)
+ : (query = q, query.active = true, armInflight())
- build(q)
const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)
- return write(toBuffer(q))
+ return write(bytes)
&& !q.describeFirst
&& !q.cursorFn
&& sent.length < max_pipeline
&& mayPipeline
} catch (error) {
- sent.length === 0 && write(Sync)
- errored(error)
+ if (query === q) {
+ sent.length === 0 && write(Sync)
+ errored(error)
+ } else {
+ sent.remove(q)
+ queryError(q, error)
+ }
return true
}
}
+ function reportBuildError(q, error) {
+ try {
+ options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q))
+ } catch (_) {}
+ }
+
+ // The statement's text with $n placeholders, never its parameter values.
+ function statementText(q) {
+ const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
+ return String(q.string || strings.reduce((a, s, i) => a + '$' + i + s)).replace(/\s+/g, ' ').trim().slice(0, 200)
+ }
+
+ // GBrain (#6383): the head statement's clock. It starts when a statement becomes the head, restarts on every
+ // byte the server sends and stops at ReadyForQuery. A statement that outlives options.inflight_timeout with
+ // nothing coming back (a desynced connection, a pooler that swallowed a CancelRequest, a dead peer) has no
+ // server-side timeout left to save it: the connection is retired instead of holding its queue forever.
+ function armInflight() {
+ queryStart = connection.inflightSince = performance.now()
+ inflightTimer.start()
+ }
+
+ function inflightTimedOut() {
+ if (!query)
+ return
+ const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query) }
+ const s = socket
+ error(Errors.connection('CONNECTION_STUCK', options, socket))
+ query = null
+ connection.inflightSince = 0
+ onstuck(connection, stuck)
+ terminate()
+ if (s && !s.destroyed) {
+ const t = setTimeout(() => s.destroyed || s.destroy(), 1000)
+ t.unref && t.unref()
+ }
+ }
+
function toBuffer(q) {
if (q.parameters.length >= 65534)
throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')
@@ -312,6 +377,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function data(x) {
+ query && inflightTimer.start()
if (incomings) {
incomings.push(x)
remaining -= x.length
@@ -464,6 +530,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
idleTimer.cancel()
lifeTimer.cancel()
connectTimer.cancel()
+ inflightTimer.cancel()
+ connection.inflightSince = 0
socket.removeAllListeners()
socket = null
@@ -568,7 +636,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
function ReadyForQuery(x) {
connection.status = x[5]
+ connection.inflightSince = 0
if (query) {
+ options.shared.completed++
if (errorResponse) {
// GBrain: a failed statement describes again next time instead of trusting shared parameter types.
query.sharedTypes && options.shared_types.delete(query.typesKey)
@@ -587,6 +657,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
query = results = errorResponse = null
result = new Result()
connectTimer.cancel()
+ inflightTimer.cancel()
if (initial) {
if (target_session_attrs) {
@@ -613,7 +684,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)
if (query)
- return // Consider opening if able and sent.length < 50
+ return armInflight() // Consider opening if able and sent.length < 50
connection.reserved
? !connection.reserved.release && x[5] === 73 // I
diff --git a/vendor/postgres/cf/src/index.js b/vendor/postgres/cf/src/index.js
index 39f8a14944..81c46a3c8b 100644
--- a/vendor/postgres/cf/src/index.js
+++ b/vendor/postgres/cf/src/index.js
@@ -63,14 +63,18 @@ function Postgres(a, b) {
, full = Queue()
, queues = { connecting, reserved, closed, ended, open, busy, full }
- const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose }))
+ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck }))
const sql = Sql(handler)
- Object.assign(sql, {
- get parameters() { return options.parameters },
- // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317).
- get pool() {
+ // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317). A property
+ // getter, not an Object.assign member: Object.assign reads a getter once and copies its value, which froze
+ // these numbers at construction (#6383). `inflight_oldest_ms` is the age of the oldest head statement across
+ // the pool's connections and `completed` counts every ReadyForQuery that settled a statement.
+ Object.defineProperty(sql, 'pool', {
+ enumerable: false,
+ get() {
+ const now = performance.now()
return {
max: options.max,
open: open.length,
@@ -80,9 +84,15 @@ function Postgres(a, b) {
connecting: connecting.length,
closed: closed.length,
ended: ended.length,
- queued: queries.length
+ queued: queries.length,
+ inflight_oldest_ms: connections.reduce((age, c) => c.inflightSince ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),
+ completed: options.shared.completed
}
- },
+ }
+ })
+
+ Object.assign(sql, {
+ get parameters() { return options.parameters },
largeObject: largeObject.bind(null, sql),
subscribe,
CLOSE,
@@ -557,6 +567,15 @@ function Postgres(a, b) {
: move(c, full)
}
+ // GBrain (#6383): a connection the in-flight watchdog retired leaves rotation before its socket closes, so no
+ // statement is routed to it in between; onclose then returns it to `closed` like any other dropped connection.
+ function onstuck(c, info) {
+ c.queue !== ended && move(c, ended)
+ try {
+ options.onstuck && options.onstuck(info)
+ } catch (_) {}
+ }
+
function poisoned(c) {
if (c.queue === ended)
return
@@ -603,7 +622,7 @@ function parseOptions(a, b) {
'timeout' in o && (console.log('The timeout option is deprecated, use idle_timeout instead'), o.idle_timeout = o.timeout) // eslint-disable-line
query.sslrootcert === 'system' && (query.ssl = 'verify-full')
- const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive']
+ const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout']
const defaults = {
max : globalThis.Cloudflare ? 3 : 10,
ssl : false,
@@ -612,6 +631,7 @@ function parseOptions(a, b) {
connect_timeout : 30,
max_lifetime : max_lifetime,
max_pipeline : 100,
+ inflight_timeout: null,
backoff : backoff,
keep_alive : 60,
prepare : true,
@@ -651,12 +671,14 @@ function parseOptions(a, b) {
onnotify : o.onnotify,
onclose : o.onclose,
onpoisoned : o.onpoisoned,
+ onstuck : o.onstuck,
+ onbuilderror : o.onbuilderror,
shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
parameters : {},
- shared : { retries: 0, typeArrayMap: {} },
+ shared : { retries: 0, typeArrayMap: {}, completed: 0 },
...mergeUserTypes(o.types)
}
}
diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.js
index ec88b7ca40..813790ce78 100644
--- a/vendor/postgres/cjs/src/connection.js
+++ b/vendor/postgres/cjs/src/connection.js
@@ -49,7 +49,7 @@ const errorFields = {
82 : 'routine' // R
}
-function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
+function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop } = {}) {
const {
sslnegotiation,
ssl,
@@ -75,6 +75,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
, idleTimer = timer(end, options.idle_timeout)
, lifeTimer = timer(end, options.max_lifetime)
, connectTimer = timer(connectTimedOut, options.connect_timeout)
+ , inflightTimer = timer(inflightTimedOut, options.inflight_timeout)
let socket = null
, cancelMessage
@@ -108,11 +109,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
, ended = null
, nonce = null
, query = null
+ , queryStart = 0
, final = null
const connection = {
queue: queues.closed,
idleTimer,
+ inflightSince: 0,
connect(query) {
initial = query
reconnect()
@@ -168,26 +171,88 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
if (q.cancelled)
return
+ // GBrain (#6383): a statement is built and serialized before it joins this connection's queue. It used to
+ // join first, so a statement that failed to build (UNDEFINED_VALUE, MAX_PARAMETERS_EXCEEDED) behind an
+ // in-flight one rejected that head statement with its error, stayed queued with nothing on the wire, and
+ // every later reply on the socket was delivered one statement late until the process restarted.
+ let bytes
try {
q.state = backend
+ build(q)
+ bytes = toBuffer(q)
+ } catch (error) {
+ if (!query) {
+ // An idle connection owns the ReadyForQuery its Sync produces, exactly as a failed head statement did.
+ query = q
+ query.active = true
+ write(Sync)
+ armInflight()
+ }
+ options.onbuilderror && reportBuildError(q, error)
+ queryError(q, error)
+ return true
+ }
+
+ try {
query
? sent.push(q)
- : (query = q, query.active = true)
+ : (query = q, query.active = true, armInflight())
- build(q)
const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)
- return write(toBuffer(q))
+ return write(bytes)
&& !q.describeFirst
&& !q.cursorFn
&& sent.length < max_pipeline
&& mayPipeline
} catch (error) {
- sent.length === 0 && write(Sync)
- errored(error)
+ if (query === q) {
+ sent.length === 0 && write(Sync)
+ errored(error)
+ } else {
+ sent.remove(q)
+ queryError(q, error)
+ }
return true
}
}
+ function reportBuildError(q, error) {
+ try {
+ options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q))
+ } catch (_) {}
+ }
+
+ // The statement's text with $n placeholders, never its parameter values.
+ function statementText(q) {
+ const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
+ return String(q.string || strings.reduce((a, s, i) => a + '$' + i + s)).replace(/\s+/g, ' ').trim().slice(0, 200)
+ }
+
+ // GBrain (#6383): the head statement's clock. It starts when a statement becomes the head, restarts on every
+ // byte the server sends and stops at ReadyForQuery. A statement that outlives options.inflight_timeout with
+ // nothing coming back (a desynced connection, a pooler that swallowed a CancelRequest, a dead peer) has no
+ // server-side timeout left to save it: the connection is retired instead of holding its queue forever.
+ function armInflight() {
+ queryStart = connection.inflightSince = performance.now()
+ inflightTimer.start()
+ }
+
+ function inflightTimedOut() {
+ if (!query)
+ return
+ const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query) }
+ const s = socket
+ error(Errors.connection('CONNECTION_STUCK', options, socket))
+ query = null
+ connection.inflightSince = 0
+ onstuck(connection, stuck)
+ terminate()
+ if (s && !s.destroyed) {
+ const t = setTimeout(() => s.destroyed || s.destroy(), 1000)
+ t.unref && t.unref()
+ }
+ }
+
function toBuffer(q) {
if (q.parameters.length >= 65534)
throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')
@@ -310,6 +375,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function data(x) {
+ query && inflightTimer.start()
if (incomings) {
incomings.push(x)
remaining -= x.length
@@ -462,6 +528,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
idleTimer.cancel()
lifeTimer.cancel()
connectTimer.cancel()
+ inflightTimer.cancel()
+ connection.inflightSince = 0
socket.removeAllListeners()
socket = null
@@ -566,7 +634,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
function ReadyForQuery(x) {
connection.status = x[5]
+ connection.inflightSince = 0
if (query) {
+ options.shared.completed++
if (errorResponse) {
// GBrain: a failed statement describes again next time instead of trusting shared parameter types.
query.sharedTypes && options.shared_types.delete(query.typesKey)
@@ -585,6 +655,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
query = results = errorResponse = null
result = new Result()
connectTimer.cancel()
+ inflightTimer.cancel()
if (initial) {
if (target_session_attrs) {
@@ -611,7 +682,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)
if (query)
- return // Consider opening if able and sent.length < 50
+ return armInflight() // Consider opening if able and sent.length < 50
connection.reserved
? !connection.reserved.release && x[5] === 73 // I
diff --git a/vendor/postgres/cjs/src/index.js b/vendor/postgres/cjs/src/index.js
index 694550be26..abb4a15856 100644
--- a/vendor/postgres/cjs/src/index.js
+++ b/vendor/postgres/cjs/src/index.js
@@ -62,14 +62,18 @@ function Postgres(a, b) {
, full = Queue()
, queues = { connecting, reserved, closed, ended, open, busy, full }
- const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose }))
+ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck }))
const sql = Sql(handler)
- Object.assign(sql, {
- get parameters() { return options.parameters },
- // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317).
- get pool() {
+ // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317). A property
+ // getter, not an Object.assign member: Object.assign reads a getter once and copies its value, which froze
+ // these numbers at construction (#6383). `inflight_oldest_ms` is the age of the oldest head statement across
+ // the pool's connections and `completed` counts every ReadyForQuery that settled a statement.
+ Object.defineProperty(sql, 'pool', {
+ enumerable: false,
+ get() {
+ const now = performance.now()
return {
max: options.max,
open: open.length,
@@ -79,9 +83,15 @@ function Postgres(a, b) {
connecting: connecting.length,
closed: closed.length,
ended: ended.length,
- queued: queries.length
+ queued: queries.length,
+ inflight_oldest_ms: connections.reduce((age, c) => c.inflightSince ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),
+ completed: options.shared.completed
}
- },
+ }
+ })
+
+ Object.assign(sql, {
+ get parameters() { return options.parameters },
largeObject: largeObject.bind(null, sql),
subscribe,
CLOSE,
@@ -556,6 +566,15 @@ function Postgres(a, b) {
: move(c, full)
}
+ // GBrain (#6383): a connection the in-flight watchdog retired leaves rotation before its socket closes, so no
+ // statement is routed to it in between; onclose then returns it to `closed` like any other dropped connection.
+ function onstuck(c, info) {
+ c.queue !== ended && move(c, ended)
+ try {
+ options.onstuck && options.onstuck(info)
+ } catch (_) {}
+ }
+
function poisoned(c) {
if (c.queue === ended)
return
@@ -602,7 +621,7 @@ function parseOptions(a, b) {
'timeout' in o && (console.log('The timeout option is deprecated, use idle_timeout instead'), o.idle_timeout = o.timeout) // eslint-disable-line
query.sslrootcert === 'system' && (query.ssl = 'verify-full')
- const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive']
+ const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout']
const defaults = {
max : globalThis.Cloudflare ? 3 : 10,
ssl : false,
@@ -611,6 +630,7 @@ function parseOptions(a, b) {
connect_timeout : 30,
max_lifetime : max_lifetime,
max_pipeline : 100,
+ inflight_timeout: null,
backoff : backoff,
keep_alive : 60,
prepare : true,
@@ -650,12 +670,14 @@ function parseOptions(a, b) {
onnotify : o.onnotify,
onclose : o.onclose,
onpoisoned : o.onpoisoned,
+ onstuck : o.onstuck,
+ onbuilderror : o.onbuilderror,
shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
parameters : {},
- shared : { retries: 0, typeArrayMap: {} },
+ shared : { retries: 0, typeArrayMap: {}, completed: 0 },
...mergeUserTypes(o.types)
}
}
diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.js
index c4d90e6282..a2e2deb1a2 100644
--- a/vendor/postgres/src/connection.js
+++ b/vendor/postgres/src/connection.js
@@ -49,7 +49,7 @@ const errorFields = {
82 : 'routine' // R
}
-function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
+function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop } = {}) {
const {
sslnegotiation,
ssl,
@@ -75,6 +75,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
, idleTimer = timer(end, options.idle_timeout)
, lifeTimer = timer(end, options.max_lifetime)
, connectTimer = timer(connectTimedOut, options.connect_timeout)
+ , inflightTimer = timer(inflightTimedOut, options.inflight_timeout)
let socket = null
, cancelMessage
@@ -108,11 +109,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
, ended = null
, nonce = null
, query = null
+ , queryStart = 0
, final = null
const connection = {
queue: queues.closed,
idleTimer,
+ inflightSince: 0,
connect(query) {
initial = query
reconnect()
@@ -168,26 +171,88 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
if (q.cancelled)
return
+ // GBrain (#6383): a statement is built and serialized before it joins this connection's queue. It used to
+ // join first, so a statement that failed to build (UNDEFINED_VALUE, MAX_PARAMETERS_EXCEEDED) behind an
+ // in-flight one rejected that head statement with its error, stayed queued with nothing on the wire, and
+ // every later reply on the socket was delivered one statement late until the process restarted.
+ let bytes
try {
q.state = backend
+ build(q)
+ bytes = toBuffer(q)
+ } catch (error) {
+ if (!query) {
+ // An idle connection owns the ReadyForQuery its Sync produces, exactly as a failed head statement did.
+ query = q
+ query.active = true
+ write(Sync)
+ armInflight()
+ }
+ options.onbuilderror && reportBuildError(q, error)
+ queryError(q, error)
+ return true
+ }
+
+ try {
query
? sent.push(q)
- : (query = q, query.active = true)
+ : (query = q, query.active = true, armInflight())
- build(q)
const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)
- return write(toBuffer(q))
+ return write(bytes)
&& !q.describeFirst
&& !q.cursorFn
&& sent.length < max_pipeline
&& mayPipeline
} catch (error) {
- sent.length === 0 && write(Sync)
- errored(error)
+ if (query === q) {
+ sent.length === 0 && write(Sync)
+ errored(error)
+ } else {
+ sent.remove(q)
+ queryError(q, error)
+ }
return true
}
}
+ function reportBuildError(q, error) {
+ try {
+ options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q))
+ } catch (_) {}
+ }
+
+ // The statement's text with $n placeholders, never its parameter values.
+ function statementText(q) {
+ const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
+ return String(q.string || strings.reduce((a, s, i) => a + '$' + i + s)).replace(/\s+/g, ' ').trim().slice(0, 200)
+ }
+
+ // GBrain (#6383): the head statement's clock. It starts when a statement becomes the head, restarts on every
+ // byte the server sends and stops at ReadyForQuery. A statement that outlives options.inflight_timeout with
+ // nothing coming back (a desynced connection, a pooler that swallowed a CancelRequest, a dead peer) has no
+ // server-side timeout left to save it: the connection is retired instead of holding its queue forever.
+ function armInflight() {
+ queryStart = connection.inflightSince = performance.now()
+ inflightTimer.start()
+ }
+
+ function inflightTimedOut() {
+ if (!query)
+ return
+ const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query) }
+ const s = socket
+ error(Errors.connection('CONNECTION_STUCK', options, socket))
+ query = null
+ connection.inflightSince = 0
+ onstuck(connection, stuck)
+ terminate()
+ if (s && !s.destroyed) {
+ const t = setTimeout(() => s.destroyed || s.destroy(), 1000)
+ t.unref && t.unref()
+ }
+ }
+
function toBuffer(q) {
if (q.parameters.length >= 65534)
throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')
@@ -310,6 +375,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function data(x) {
+ query && inflightTimer.start()
if (incomings) {
incomings.push(x)
remaining -= x.length
@@ -462,6 +528,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
idleTimer.cancel()
lifeTimer.cancel()
connectTimer.cancel()
+ inflightTimer.cancel()
+ connection.inflightSince = 0
socket.removeAllListeners()
socket = null
@@ -566,7 +634,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
function ReadyForQuery(x) {
connection.status = x[5]
+ connection.inflightSince = 0
if (query) {
+ options.shared.completed++
if (errorResponse) {
// GBrain: a failed statement describes again next time instead of trusting shared parameter types.
query.sharedTypes && options.shared_types.delete(query.typesKey)
@@ -585,6 +655,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
query = results = errorResponse = null
result = new Result()
connectTimer.cancel()
+ inflightTimer.cancel()
if (initial) {
if (target_session_attrs) {
@@ -611,7 +682,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)
if (query)
- return // Consider opening if able and sent.length < 50
+ return armInflight() // Consider opening if able and sent.length < 50
connection.reserved
? !connection.reserved.release && x[5] === 73 // I
diff --git a/vendor/postgres/src/index.js b/vendor/postgres/src/index.js
index fc9f766c4d..32efd8bf11 100644
--- a/vendor/postgres/src/index.js
+++ b/vendor/postgres/src/index.js
@@ -62,14 +62,18 @@ function Postgres(a, b) {
, full = Queue()
, queues = { connecting, reserved, closed, ended, open, busy, full }
- const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose }))
+ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck }))
const sql = Sql(handler)
- Object.assign(sql, {
- get parameters() { return options.parameters },
- // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317).
- get pool() {
+ // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317). A property
+ // getter, not an Object.assign member: Object.assign reads a getter once and copies its value, which froze
+ // these numbers at construction (#6383). `inflight_oldest_ms` is the age of the oldest head statement across
+ // the pool's connections and `completed` counts every ReadyForQuery that settled a statement.
+ Object.defineProperty(sql, 'pool', {
+ enumerable: false,
+ get() {
+ const now = performance.now()
return {
max: options.max,
open: open.length,
@@ -79,9 +83,15 @@ function Postgres(a, b) {
connecting: connecting.length,
closed: closed.length,
ended: ended.length,
- queued: queries.length
+ queued: queries.length,
+ inflight_oldest_ms: connections.reduce((age, c) => c.inflightSince ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),
+ completed: options.shared.completed
}
- },
+ }
+ })
+
+ Object.assign(sql, {
+ get parameters() { return options.parameters },
largeObject: largeObject.bind(null, sql),
subscribe,
CLOSE,
@@ -556,6 +566,15 @@ function Postgres(a, b) {
: move(c, full)
}
+ // GBrain (#6383): a connection the in-flight watchdog retired leaves rotation before its socket closes, so no
+ // statement is routed to it in between; onclose then returns it to `closed` like any other dropped connection.
+ function onstuck(c, info) {
+ c.queue !== ended && move(c, ended)
+ try {
+ options.onstuck && options.onstuck(info)
+ } catch (_) {}
+ }
+
function poisoned(c) {
if (c.queue === ended)
return
@@ -602,7 +621,7 @@ function parseOptions(a, b) {
'timeout' in o && (console.log('The timeout option is deprecated, use idle_timeout instead'), o.idle_timeout = o.timeout) // eslint-disable-line
query.sslrootcert === 'system' && (query.ssl = 'verify-full')
- const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive']
+ const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout']
const defaults = {
max : globalThis.Cloudflare ? 3 : 10,
ssl : false,
@@ -611,6 +630,7 @@ function parseOptions(a, b) {
connect_timeout : 30,
max_lifetime : max_lifetime,
max_pipeline : 100,
+ inflight_timeout: null,
backoff : backoff,
keep_alive : 60,
prepare : true,
@@ -650,12 +670,14 @@ function parseOptions(a, b) {
onnotify : o.onnotify,
onclose : o.onclose,
onpoisoned : o.onpoisoned,
+ onstuck : o.onstuck,
+ onbuilderror : o.onbuilderror,
shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
parameters : {},
- shared : { retries: 0, typeArrayMap: {} },
+ shared : { retries: 0, typeArrayMap: {}, completed: 0 },
...mergeUserTypes(o.types)
}
}
diff --git a/vendor/postgres/types/index.d.ts b/vendor/postgres/types/index.d.ts
index 03f1ddffe0..3623312172 100644
--- a/vendor/postgres/types/index.d.ts
+++ b/vendor/postgres/types/index.d.ts
@@ -124,6 +124,20 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {
* reused because its ReadyForQuery status was not idle ('T' or 'E').
*/
onpoisoned: (status: string) => void;
+ /**
+ * GBrain: seconds a head statement may wait for the server with nothing coming back
+ * before the connection is retired and every statement queued on it rejects with
+ * `CONNECTION_STUCK`. Null disables the watchdog.
+ * @default null
+ */
+ inflight_timeout: number | null;
+ /** GBrain: called once per connection the in-flight watchdog retired. */
+ onstuck: (stuck: { age_ms: number; queued: number; statement: string }) => void;
+ /**
+ * GBrain: called when a statement fails to build (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`);
+ * `statement` is its text with `$n` placeholders, never parameter values.
+ */
+ onbuilderror: (code: string, statement: string) => void;
/**
* GBrain: share the parameter types of a described statement across this pool's
* connections, so a connection running it for the first time skips the describe
@@ -719,7 +733,7 @@ declare namespace postgres {
options: ParsedOptions<TTypes>;
parameters: ConnectionParameters;
/** GBrain: the pool's own queue lengths at this instant (`queued` = queries waiting for a connection). */
- pool: { max: number; open: number; busy: number; full: number; reserved: number; connecting: number; closed: number; ended: number; queued: number };
+ pool: { max: number; open: number; busy: number; full: number; reserved: number; connecting: number; closed: number; ended: number; queued: number; inflight_oldest_ms: number; completed: number };
end(options?: { timeout?: number | undefined } | undefined): Promise<void>;