Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#6543): per-statement in-flight age cap and pool recovery counters (PR 2: A4 A6)
garrytan66891f757ce7
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex f23fde012a..e302400cd2 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -725,8 +725,9 @@ agreement, end it on the database host with `SELECT pg_terminate_backend(<pid>)`then rerun the same command. Test: `test/e2e/init-schema-lock-blocked.test.ts`.<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:+statement ran past its in-flight budget, either with nothing coming back from+the server (`reason=idle`) or while bytes kept arriving (`reason=age`, #6543),+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, andthe pool reconnected on its own (#6383). Usually only a wedged connection@@ -739,13 +740,23 @@ pooler (port 6543) the startup `statement_timeout` never reaches the backendreach the budget too (#6543). The budget is the pool's own startup `statement_timeout` (5 min onthe read pool, 30 min on the direct pool, `GBRAIN_STATEMENT_TIMEOUT` for theread 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+configured timeout even through a pooler that drops the startup parameter, and+`GBRAIN_PG_STUCK_GRACE_MS=0` or `off` disables the watchdog. Two clocks run+against it: the idle clock restarts on every byte the server sends, the age+clock never does, so a statement that keeps streaming rows or notices past the+budget is retired too. The budget is derived per statement and travels with the+operation: a statement after a `SET [LOCAL] statement_timeout` or+`set_config('statement_timeout', …)` on its connection (inside a transaction,+on a reserved connection, or in the same simple query) gets+`max(budget, that timeout + grace)`, and a declared `0` (an index build, a bulk+copy) has no cap. The driver reads the declaration from the statements it+sends, so it holds behind a transaction-mode pooler that never applies a+session `SET`; a transaction's `SET LOCAL` ends with it, `RESET` restores the+pool's budget. An operation that must run longer declares its own timeout that+way; `GBRAIN_STATEMENT_TIMEOUT` raises it for every read-pool statement. The+line names the pool, `reason`, `age_ms`, `budget_ms` (that statement's own+cap), `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 perengine; `/health?deep=1` reports them as `stuck_discards`. Retry the failedcall; if the line repeats, run `gbrain doctor --json` and report the warn lineswith the operations that preceded them.@@ -761,6 +772,20 @@ the last statement written on it by first keyword and table, never its text orparameters. Notices, notifications and parameter changes never trigger it.`getPoolDiagnostics().desyncDiscards` counts retirements per engine;`/health?deep=1` reports them as `desync_discards`.++<a id="pg-connection-recovery-failed"></a>**`pg_connection_recovery_failed`**+(warn). A connection the driver retired after an incident (stuck, desynced, or+closed under running statements, for example by `pg_terminate_backend` or a+pooler reap) could not reconnect; statements waiting for it failed with the+connect error, and the next statement retries. The line names the pool, the+driver's connection id, the incident (`cause=stuck|desync|closed`) and the+error code. `getPoolDiagnostics()` counts reconnects of retired connections as+`recovered` and failures as `recoveryFailed`; `/health?deep=1` reports them as+`recovered` and `recovery_failed` (#6543). A resident `gbrain serve` writes its+stuck, desync and recovery events to the pool-recovery audit+(`~/.gbrain/audit/pool-recovery-YYYY-Www.jsonl`), so+`gbrain doctor --only pool_reap_health` fails on a recovery failure and warns+on a stuck or desynced connection in the last hour.Retry the failed call; if the line repeats, run `gbrain doctor --json` andreport the warn lines.@@ -805,11 +830,13 @@ driver only ever claims from idle connections; a wedged connection sits in thebusy queue where handler statements are routed, so `/health` answered 200through the whole #6383 incident. `/health?deep=1` runs `SELECT 1` through theordinary 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+probe does not return in time, when a pooled statement is past its own+in-flight budget (the same per-statement budget the watchdog retires at, so a+transaction that declared a longer `statement_timeout` is measured against it;+the block's `inflight_over_budget_ms`), or when an earlier deep probe is still pending (onedeep 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, desync_discards }`. It is cheap enough for a two-minute cron. The+stuck_discards, build_failures, desync_discards, recovered, recovery_failed }`. It is cheap enough for a two-minute cron. Thesame pool numbers ride the persistence consumer's heartbeat row, so`gbrain sources writer status --json` shows `pool.inflight_oldest_ms` for theowner process.@@ -820,8 +847,9 @@ registry (#6543):- `persistence_restart_required`: this serve's persistence consumer reports`restart_required` (an abandoned preparation or a publication past itsdeadline), so it claims no write until the process restarts. Restart serve.-- `pool_inflight_over_budget`: a pooled statement has waited past the read- pool's in-flight budget. Restart serve; behind a transaction-mode pooler read+- `pool_inflight_over_budget`: a pooled statement has run past its own+ in-flight budget without being retired (the watchdog is off, or the serve+ runs a driver without per-statement budgets). Restart serve; behind a transaction-mode pooler read`transport` first and set `PGMAX_PIPELINE=0` if `max_pipeline` is not `0`.No request id or statement text reaches either body: the endpoint isunauthenticated.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex d6b881b420..8e5adf80f2 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2129,13 +2129,23 @@ More: [docs/ENGINES.md#serve-deep-health](../../docs/ENGINES.md#serve-deep-healtMore: [docs/guides/troubleshooting.md#persistence-write-stall](../../docs/guides/troubleshooting.md#persistence-write-stall)+### pg_connection_recovery_failed++<a id="pg_connection_recovery_failed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A Postgres connection the driver retired after an incident (stuck, desynced, or closed under running statements) could not reconnect; statements waiting for it failed with the connect error. | The database or pooler refused or dropped the new connection (unreachable host, exhausted connection slots, rotated credentials). The next statement retries the connect, and the connection stays marked until one succeeds, so a repeating line means the pool is not recovering on its own. | Check the database and pooler from the serve host (gbrain doctor --only pool_reap_health --json); a serve that keeps logging this line needs the database reachable again, then a restart if the pool never recovers. Run: gbrain doctor --only pool_reap_health --json | agent | `repeat the read that failed` | 1 | yes |++More: [docs/ENGINES.md#pg-connection-recovery-failed](../../docs/ENGINES.md#pg-connection-recovery-failed)+### 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. | Nothing arriving for that long usually means the connection 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. It is not proof: behind a transaction-mode pooler the startup statement_timeout never applies (SHOW statement_timeout reads 0), so a legitimately slow statement can reach the budget too, and the clock restarts on every byte, so a statement that keeps streaming is never retired. 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 |+| A pooled Postgres statement ran past its in-flight budget (the pool's statement_timeout plus grace, or the longer statement_timeout its operation declared) with nothing coming back from the server (reason=idle) or while bytes kept arriving (reason=age), so the driver retired that connection; the statement and everything queued behind it failed with CONNECTION_STUCK. | Nothing arriving for that long usually means the connection 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. It is not proof: behind a transaction-mode pooler the startup statement_timeout never applies (SHOW statement_timeout reads 0), so a legitimately slow statement can reach the budget too. reason=age is a statement that kept streaming rows or notices past its budget (#6543); an operation that needs longer declares it with SET LOCAL statement_timeout (0 for no limit), which the driver tracks per statement. 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)@@ -2201,7 +2211,7 @@ More: [docs/ENGINES.md#pglite-vector-index-ceiling](../../docs/ENGINES.md#pglite| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A pooled statement of this gbrain serve has waited longer than the read pool's in-flight budget (statement_timeout plus grace); `/health?deep=1` answers 503 with this code. | The in-flight watchdog retires a connection only after nothing arrives for the budget, so a statement that keeps receiving bytes, or one behind a transaction-mode pooler where no server statement_timeout applies, can sit past it while every statement queued behind it waits. Through a transaction-mode pooler a pipelined answer can also be misrouted. The probe reports it and never retires the connection, because the endpoint is unauthenticated. | Restart this gbrain serve. On a transaction-mode pooler check the transport block of /health?deep=1: max_pipeline should read 0 (set PGMAX_PIPELINE=0 in the serve environment to force it) and session_timeouts_not_applied names the ALTER ROLE fix. GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS does not act on this code: restart serve yourself or from your health check. | host_admin | `gbrain doctor --json` | 1 | no |+| A pooled statement of this gbrain serve has run longer than its in-flight budget (the read pool's statement_timeout plus grace, or the longer statement_timeout its operation declared); `/health?deep=1` answers 503 with this code. | Since #6543 the in-flight watchdog retires a statement past its budget whether or not bytes keep arriving (reason=age), so this code means the watchdog is off (GBRAIN_PG_STUCK_GRACE_MS=off), the serve runs a driver without per-statement budgets, or the retirement is still in progress; a transaction that declared a longer statement_timeout, or an index build that declared 0, is measured against its own budget and not reported. Through a transaction-mode pooler a pipelined answer can also be misrouted. The probe reports it and never retires the connection, because the endpoint is unauthenticated. | Restart this gbrain serve. On a transaction-mode pooler check the transport block of /health?deep=1: max_pipeline should read 0 (set PGMAX_PIPELINE=0 in the serve environment to force it) and session_timeouts_not_applied names the ALTER ROLE fix. GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS does not act on this code: restart serve yourself or from your health check. | host_admin | `gbrain doctor --json` | 1 | no |More: [docs/ENGINES.md#serve-deep-health](../../docs/ENGINES.md#serve-deep-health)diff --git a/llms-full.txt b/llms-full.txtindex f3d04818f9..d3108cfb37 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5891,8 +5891,9 @@ agreement, end it on the database host with `SELECT pg_terminate_backend(<pid>)`then rerun the same command. Test: `test/e2e/init-schema-lock-blocked.test.ts`.<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:+statement ran past its in-flight budget, either with nothing coming back from+the server (`reason=idle`) or while bytes kept arriving (`reason=age`, #6543),+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, andthe pool reconnected on its own (#6383). Usually only a wedged connection@@ -5905,13 +5906,23 @@ pooler (port 6543) the startup `statement_timeout` never reaches the backendreach the budget too (#6543). The budget is the pool's own startup `statement_timeout` (5 min onthe read pool, 30 min on the direct pool, `GBRAIN_STATEMENT_TIMEOUT` for theread 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+configured timeout even through a pooler that drops the startup parameter, and+`GBRAIN_PG_STUCK_GRACE_MS=0` or `off` disables the watchdog. Two clocks run+against it: the idle clock restarts on every byte the server sends, the age+clock never does, so a statement that keeps streaming rows or notices past the+budget is retired too. The budget is derived per statement and travels with the+operation: a statement after a `SET [LOCAL] statement_timeout` or+`set_config('statement_timeout', …)` on its connection (inside a transaction,+on a reserved connection, or in the same simple query) gets+`max(budget, that timeout + grace)`, and a declared `0` (an index build, a bulk+copy) has no cap. The driver reads the declaration from the statements it+sends, so it holds behind a transaction-mode pooler that never applies a+session `SET`; a transaction's `SET LOCAL` ends with it, `RESET` restores the+pool's budget. An operation that must run longer declares its own timeout that+way; `GBRAIN_STATEMENT_TIMEOUT` raises it for every read-pool statement. The+line names the pool, `reason`, `age_ms`, `budget_ms` (that statement's own+cap), `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 perengine; `/health?deep=1` reports them as `stuck_discards`. Retry the failedcall; if the line repeats, run `gbrain doctor --json` and report the warn lineswith the operations that preceded them.@@ -5927,6 +5938,20 @@ the last statement written on it by first keyword and table, never its text orparameters. Notices, notifications and parameter changes never trigger it.`getPoolDiagnostics().desyncDiscards` counts retirements per engine;`/health?deep=1` reports them as `desync_discards`.++<a id="pg-connection-recovery-failed"></a>**`pg_connection_recovery_failed`**+(warn). A connection the driver retired after an incident (stuck, desynced, or+closed under running statements, for example by `pg_terminate_backend` or a+pooler reap) could not reconnect; statements waiting for it failed with the+connect error, and the next statement retries. The line names the pool, the+driver's connection id, the incident (`cause=stuck|desync|closed`) and the+error code. `getPoolDiagnostics()` counts reconnects of retired connections as+`recovered` and failures as `recoveryFailed`; `/health?deep=1` reports them as+`recovered` and `recovery_failed` (#6543). A resident `gbrain serve` writes its+stuck, desync and recovery events to the pool-recovery audit+(`~/.gbrain/audit/pool-recovery-YYYY-Www.jsonl`), so+`gbrain doctor --only pool_reap_health` fails on a recovery failure and warns+on a stuck or desynced connection in the last hour.Retry the failed call; if the line repeats, run `gbrain doctor --json` andreport the warn lines.@@ -5971,11 +5996,13 @@ driver only ever claims from idle connections; a wedged connection sits in thebusy queue where handler statements are routed, so `/health` answered 200through the whole #6383 incident. `/health?deep=1` runs `SELECT 1` through theordinary 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+probe does not return in time, when a pooled statement is past its own+in-flight budget (the same per-statement budget the watchdog retires at, so a+transaction that declared a longer `statement_timeout` is measured against it;+the block's `inflight_over_budget_ms`), or when an earlier deep probe is still pending (onedeep 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, desync_discards }`. It is cheap enough for a two-minute cron. The+stuck_discards, build_failures, desync_discards, recovered, recovery_failed }`. It is cheap enough for a two-minute cron. Thesame pool numbers ride the persistence consumer's heartbeat row, so`gbrain sources writer status --json` shows `pool.inflight_oldest_ms` for theowner process.@@ -5986,8 +6013,9 @@ registry (#6543):- `persistence_restart_required`: this serve's persistence consumer reports`restart_required` (an abandoned preparation or a publication past itsdeadline), so it claims no write until the process restarts. Restart serve.-- `pool_inflight_over_budget`: a pooled statement has waited past the read- pool's in-flight budget. Restart serve; behind a transaction-mode pooler read+- `pool_inflight_over_budget`: a pooled statement has run past its own+ in-flight budget without being retired (the watchdog is off, or the serve+ runs a driver without per-statement budgets). Restart serve; behind a transaction-mode pooler read`transport` first and set `PGMAX_PIPELINE=0` if `max_pipeline` is not `0`.No request id or statement text reaches either body: the endpoint isunauthenticated.diff --git a/patches/[email protected] b/patches/[email protected]index 22d13e2f2a..e7f1485d24 100644--- a/patches/[email protected]+++ b/patches/[email protected]@@ -1,5 +1,5 @@diff --git a/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.js-index 07f67167..ad0cbd0c 100644+index 07f6716..16f1373 100644--- a/cjs/src/connection.js+++ b/vendor/postgres/cjs/src/connection.js@@ -20,6 +20,7 @@ const Sync = b().S().end()@@ -19,11 +19,12 @@ index 07f67167..ad0cbd0c 100644const {sslnegotiation,ssl,-@@ -75,9 +76,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -75,9 +76,14 @@ 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)++ , inflightTimer = budgetTimer('idle')++ , ageTimer = budgetTimer('age')let socket = null, cancelMessage@@ -33,7 +34,7 @@ index 07f67167..ad0cbd0c 100644, errorResponse = null, result = new Result(), incoming = Buffer.alloc(0)-@@ -95,6 +100,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -95,6 +101,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, rows = 0, serverSignature = null, nextWriteTimer = null@@ -43,21 +44,26 @@ index 07f67167..ad0cbd0c 100644, terminated = false, incomings = null, results = null-@@ -105,11 +113,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -105,11 +114,18 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, ended = null, nonce = null, query = null+ , queryStart = 0++ , received = 0++ , localBudget = undefined++ , sessionBudget = undefined++ , recovering = null, final = nullconst connection = {queue: queues.closed,idleTimer,+ inflightSince: 0,++ inflightCap: 0,connect(query) {initial = queryreconnect()-@@ -143,11 +153,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -143,11 +159,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}async function cancel({ pid, secret }, resolve, reject) {@@ -73,7 +79,7 @@ index 07f67167..ad0cbd0c 100644} catch (error) {reject(error)}-@@ -163,22 +175,78 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -163,22 +181,139 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseif (q.cancelled)return@@ -87,6 +93,7 @@ index 07f67167..ad0cbd0c 100644build(q)+ mayPipeline = mayPipeline || q.options.onexecute(connection)++ noteBudget(q)+ lastWritten = q+ lastExecuted = qreturn write(toBuffer(q))@@ -136,16 +143,76 @@ index 07f67167..ad0cbd0c 100644+ // 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.++ //++ // GBrain (#6543 A4): a second clock, `ageTimer`, is not restarted by received bytes, so a statement that keeps++ // streaming (or keeps receiving notices) past its budget is retired too (`reason: 'age'`; `'idle'` when nothing came++ // back). Both budgets are derived per statement from the statement_timeout the operation itself declared on this++ // connection (`SET [LOCAL] statement_timeout`, `set_config('statement_timeout', ...)`, tracked client-side so it++ // holds behind a transaction-mode pooler that never applies it): max(the pool's budget, the declared timeout) plus++ // `inflight_grace`, and none at all for a declared timeout of 0 (an index build, a bulk copy).+ function armInflight() {+ queryStart = connection.inflightSince = performance.now()++ received = 0++ query.inflightCaps || (query.inflightCaps = inflightCaps())++ connection.inflightCap = query.inflightCaps.age+ inflightTimer.start()++ ageTimer.start()+ }+-+ function inflightTimedOut() {++ function budgetTimer(kind) {++ let handle = null++ return {++ cancel() {++ handle && (clearTimeout(handle), handle = null)++ },++ start() {++ handle && clearTimeout(handle)++ const ms = query && query.inflightCaps ? query.inflightCaps[kind] : 0++ handle = ms ? setTimeout(() => (handle = null, inflightTimedOut(kind)), ms) : null++ }++ }++ }++++ function inflightCaps() {++ const declared = localBudget !== undefined ? localBudget : sessionBudget++ if (declared === 0)++ return { idle: 0, age: 0 }++ const raised = declared === undefined ? 0 : declared + (options.inflight_grace || 0) * 1000++ return {++ idle: options.inflight_timeout ? Math.max(options.inflight_timeout * 1000, raised) : 0,++ age: options.inflight_max ? Math.max(options.inflight_max * 1000, raised) : 0++ }++ }++++ // The statement_timeout changes a statement makes on this connection; a later statement is budgeted by them.++ function noteBudget(q) {++ const text = q.string || ''++ if (localBudget === undefined && sessionBudget === undefined && !/statement_timeout/i.test(text))++ return++ for (const change of statementTimeoutChanges(text, q.parameters)) {++ change.kind === 'end'++ ? localBudget = undefined++ : change.kind === 'reset'++ ? localBudget = sessionBudget = undefined++ : change.kind === 'set' && (change.local ? localBudget = change.ms : (sessionBudget = change.ms, localBudget = undefined))++ }++ q.inflightCaps = inflightCaps()++ if (q === query) {++ connection.inflightCap = q.inflightCaps.age++ inflightTimer.start()++ ageTimer.start()++ }++ }++++ function inflightTimedOut(kind = 'idle') {+ if (!query)+ return-+ const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query) }++ inflightTimer.cancel()++ ageTimer.cancel()++ const reason = kind === 'age' && received > 0 ? 'age' : 'idle'++ const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query), reason, budget_ms: query.inflightCaps ? query.inflightCaps[kind] : 0 }+ const s = socket++ recovering = recovering || 'stuck'+ error(Errors.connection('CONNECTION_STUCK', options, socket))+ query = null+ connection.inflightSince = 0@@ -157,7 +224,7 @@ index 07f67167..ad0cbd0c 100644}}-@@ -235,10 +303,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -235,10 +370,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.onlyDescribe && (delete statements[q.signature])q.parameters = q.parameters || parametersq.prepared = q.prepare && q.signature in statements@@ -175,7 +242,7 @@ index 07f67167..ad0cbd0c 100644typeof options.debug === 'function' && options.debug(id, string, parameters, types)}-@@ -295,10 +368,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -295,10 +435,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* c8 ignore next 3 */function drain() {@@ -184,11 +251,11 @@ index 07f67167..ad0cbd0c 100644}function data(x) {-+ query && inflightTimer.start()++ query && (received += x.length, inflightTimer.start())if (incomings) {incomings.push(x)remaining -= x.length-@@ -379,15 +453,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -379,20 +520,35 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function error(err) {@@ -209,8 +276,22 @@ index 07f67167..ad0cbd0c 100644+ cancelError = errstream && (stream.destroy(err), stream = null)query && queryError(query, err)++ initial && recovering && recoveryFailed(err)initial && (queryError(initial, err), initial = null)-@@ -438,19 +518,43 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+ }+++ // GBrain (#6543 A6): a connection retired by an incident (stuck, desync, closed under statements) that completes a++ // new startup is `recovered`; one whose reconnect fails is `recovery_failed` (it stays marked until one succeeds).++ function recoveryFailed(err) {++ try {++ options.onrecoveryfailed && options.onrecoveryfailed({ connection: id, cause: recovering, code: String(err && err.code || 'CONNECTION_ERROR') })++ } catch (_) {}++ }+++ function queryError(query, err) {+ if (query.reserve)+ return query.reject(err)+@@ -438,19 +594,47 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseremaining = 0incomings = nullclearImmediate(nextWriteTimer)@@ -224,7 +305,9 @@ index 07f67167..ad0cbd0c 100644lifeTimer.cancel()connectTimer.cancel()+ inflightTimer.cancel()-+ connection.inflightSince = 0++ ageTimer.cancel()++ connection.inflightSince = connection.inflightCap = 0++ localBudget = sessionBudget = undefinedsocket.removeAllListeners()socket = null@@ -245,6 +328,8 @@ index 07f67167..ad0cbd0c 100644return reconnect()+ }++ // GBrain (#6543 A6): a socket that closed under statements is a recovery the next completed startup reports.++ ;(query || sent.length) && (recovering = recovering || 'closed')!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))+ // GBrain (#6543): the dead socket's ErrorResponse (a FATAL 57P01, a pooler's XX000) and its partial result belonged+ // to statements that just failed. Left in place, the replacement connection's startup ReadyForQuery handed that@@ -255,7 +340,7 @@ index 07f67167..ad0cbd0c 100644closedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000-@@ -459,6 +563,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -459,6 +643,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* Handlers */function handle(xs, x = xs[0]) {@@ -266,7 +351,7 @@ index 07f67167..ad0cbd0c 100644(x === 68 ? DataRow : // Dx === 100 ? CopyData : // d-@@ -489,6 +597,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -489,6 +677,39 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose)(xs)}@@ -289,9 +374,12 @@ index 07f67167..ad0cbd0c 100644+ function desynced(x) {+ const s = socket+ const info = { message: String.fromCharCode(x), connection: id, statement: lastExecuted ? statementText(lastExecuted) : '' }++ recovering = recovering || 'desync'+ error(Errors.connection('CONNECTION_DESYNC', options, socket))++ inflightTimer.cancel()++ ageTimer.cancel()+ query = null-+ connection.inflightSince = 0++ connection.inflightSince = connection.inflightCap = 0+ ondesync(connection, info)+ terminate()+ if (s && !s.destroyed) {@@ -303,13 +391,15 @@ index 07f67167..ad0cbd0c 100644function DataRow(x) {let index = 7let length-@@ -533,13 +671,23 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -533,13 +754,25 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function ReadyForQuery(x) {+ connection.status = x[5]+ query && query === lastWritten && (lastWritten = null)-+ connection.inflightSince = 0++ connection.inflightSince = connection.inflightCap = 0++ // A transaction that ended takes its SET LOCAL statement_timeout with it.++ x[5] === 73 && !sent.length && (localBudget = undefined)if (query) {+ options.shared.completed++if (errorResponse) {@@ -328,15 +418,16 @@ index 07f67167..ad0cbd0c 100644} else {query.resolve(results || result)}-@@ -550,6 +698,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -550,6 +783,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosequery = results = errorResponse = nullresult = new Result()connectTimer.cancel()+ inflightTimer.cancel()++ ageTimer.cancel()if (initial) {if (target_session_attrs) {-@@ -564,23 +713,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -564,23 +799,43 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn fetchArrayTypes()}@@ -346,12 +437,17 @@ index 07f67167..ad0cbd0c 100644options.shared.retries = retries = 0initial = null- return++ if (recovering) {++ const cause = recovering++ recovering = null++ try {++ options.onrecovered && options.onrecovered({ connection: id, cause })++ } catch (_) {}++ }+ if (!reserving)+ return- }--- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))-- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)++ }+++ // GBrain: the stock loop skipped a query cancelled while it waited behind another one, so the answer the+ // server still sent for it was read for the next query (the next query resolved with another statement's+ // rows, and the cancelled one never settled). The cancelled query stays current and absorbs its own answer.@@ -362,8 +458,10 @@ index 07f67167..ad0cbd0c 100644+ query.cancelled && (sent.length+ ? query.cancelled.resolve()+ : Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject))-+ }-++ }++- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))+- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)+ flushRetries()if (query)@@ -379,7 +477,7 @@ index 07f67167..ad0cbd0c 100644: connection.reserved(): ending? terminate()-@@ -630,7 +792,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -630,7 +885,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))query.prepare && (statements[query.signature] = query.statement)@@ -391,7 +489,7 @@ index 07f67167..ad0cbd0c 100644}function RowDescription(x) {-@@ -767,14 +933,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -767,14 +1026,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false@@ -421,7 +519,7 @@ index 07f67167..ad0cbd0c 100644types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))}-@@ -821,7 +994,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -821,7 +1087,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction retry(q, error) {delete statements[q.signature]q.retried = error@@ -439,11 +537,71 @@ index 07f67167..ad0cbd0c 100644}function NotificationResponse(x) {+@@ -1039,6 +1314,59 @@ function xor(a, b) {+ return buffer+ }+++// GBrain (#6543 A4): what one statement does to the connection's statement_timeout, in order: `set` (`local`, `ms`;++// 0 disables it, undefined is DEFAULT), `reset` (RESET statement_timeout / RESET ALL / DISCARD ALL), `end` (a++// transaction began or ended, which drops a SET LOCAL), and `unknown` for a change whose value cannot be read here.++// Dollar-quoted bodies are skipped, so a function body's BEGIN/END is not a transaction boundary.++const budgetSyntax = /(?:^|;)\s*(begin|start\s+transaction|commit|end|abort|rollback(?!\s+(?:to|prepared)\b))\b|\bset\s+(local\s+|session\s+)?statement_timeout\s*(?:=|\bto\b)\s*('(?:[^']|'')*'|[^\s;)]+)|\breset\s+(?:statement_timeout|all)\b|\bdiscard\s+all\b|\bset_config\s*\(\s*'statement_timeout'\s*,\s*('(?:[^']|'')*'|\$\d+)\s*,\s*([^)\s]+)\s*\)/gi++++function statementTimeoutChanges(text, parameters) {++ const changes = []++ const plain = String(text || '').replace(/\$([A-Za-z_][A-Za-z0-9_]*)?\$[\s\S]*?\$\1\$/g, ' ')++ budgetSyntax.lastIndex = 0++ let m++ while ((m = budgetSyntax.exec(plain))) {++ if (m[1]) {++ changes.push({ kind: 'end' })++ } else if (m[3] !== undefined) {++ const ms = timeoutMs(m[3], parameters)++ changes.push(Number.isNaN(ms) ? { kind: 'unknown' } : { kind: 'set', local: /^local/i.test(m[2] || ''), ms })++ } else if (m[4] !== undefined) {++ const ms = timeoutMs(m[4], parameters)++ const local = parameterValue(m[5], parameters)++ changes.push(Number.isNaN(ms) || local === undefined ? { kind: 'unknown' } : { kind: 'set', local: /^(t|true|on|1)$/i.test(local), ms })++ } else {++ changes.push({ kind: 'reset' })++ }++ }++ return changes++}++++function parameterValue(raw, parameters) {++ const p = /^\$(\d+)$/.exec(raw.trim())++ if (p) {++ const v = parameters && parameters[p[1] - 1]++ return v === null || v === undefined ? undefined : String(v)++ }++ const v = raw.trim()++ return /^'.*'$/s.test(v) ? v.slice(1, -1).replace(/''/g, "'") : v++}++++function timeoutMs(raw, parameters) {++ const v = parameterValue(raw, parameters)++ if (v === undefined)++ return NaN++ if (/^default$/i.test(v.trim()))++ return undefined++ const m = /^\s*(\d+(?:\.\d+)?)\s*(us|ms|s|min|h|d)?\s*$/i.exec(v)++ if (!m)++ return NaN++ const unit = (m[2] || 'ms').toLowerCase()++ return Math.round(+m[1] * { us: 0.001, ms: 1, s: 1000, min: 60000, h: 3600000, d: 86400000 }[unit])++}++++Connection.statementTimeoutChanges = statementTimeoutChanges+++ function timer(fn, seconds) {+ seconds = typeof seconds === 'function' ? seconds() : seconds+ if (!seconds)diff --git a/cjs/src/index.js b/vendor/postgres/cjs/src/index.js-index f09c61c7..dc7e234d 100644+index f09c61c..93eb66d 100644--- a/cjs/src/index.js+++ b/vendor/postgres/cjs/src/index.js-@@ -62,10 +62,34 @@ function Postgres(a, b) {+@@ -62,10 +62,36 @@ function Postgres(a, b) {, full = Queue(), queues = { connecting, reserved, closed, ended, open, busy, full }@@ -471,6 +629,8 @@ index f09c61c7..dc7e234d 100644+ ended: ended.length,+ queued: queries.length,+ inflight_oldest_ms: connections.reduce((age, c) => c.inflightSince ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),++ // GBrain (#6543 A4): the oldest head statement past its own budget (the cap the driver retires it at), 0 when none is.++ inflight_over_budget_ms: connections.reduce((age, c) => c.inflightSince && c.inflightCap && now - c.inflightSince > c.inflightCap ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),+ completed: options.shared.completed+ }+ }@@ -479,7 +639,7 @@ index f09c61c7..dc7e234d 100644Object.assign(sql, {get parameters() { return options.parameters },largeObject: largeObject.bind(null, sql),-@@ -200,40 +224,134 @@ function Postgres(a, b) {+@@ -200,40 +226,134 @@ function Postgres(a, b) {return await sql`select pg_notify(${ channel }, ${ '' + payload })`}@@ -633,7 +793,7 @@ index f09c61c7..dc7e234d 100644let savepoints = 0, connection, prepare = null-@@ -249,9 +367,13 @@ function Postgres(a, b) {+@@ -249,9 +369,13 @@ function Postgres(a, b) {}async function scope(c, fn, name) {@@ -647,7 +807,7 @@ index f09c61c7..dc7e234d 100644let uncaughtError, result-@@ -281,6 +403,8 @@ function Postgres(a, b) {+@@ -281,6 +405,8 @@ function Postgres(a, b) {return resultfunction savepoint(name, fn) {@@ -656,7 +816,7 @@ index f09c61c7..dc7e234d 100644if (name && Array.isArray(name.raw))return savepoint(sql => sql.apply(sql, arguments))-@@ -290,18 +414,16 @@ function Postgres(a, b) {+@@ -290,18 +416,16 @@ function Postgres(a, b) {function handler(q) {q.catch(e => uncaughtError || (uncaughtError = e))@@ -679,7 +839,7 @@ index f09c61c7..dc7e234d 100644}}-@@ -351,7 +473,7 @@ function Postgres(a, b) {+@@ -351,7 +475,7 @@ function Postgres(a, b) {return new Promise((resolve, reject) => {query.state? query.active@@ -688,7 +848,7 @@ index f09c61c7..dc7e234d 100644: query.cancelled = { resolve, reject }: (queries.remove(query),-@@ -362,6 +484,25 @@ function Postgres(a, b) {+@@ -362,6 +486,25 @@ function Postgres(a, b) {})}@@ -714,7 +874,7 @@ index f09c61c7..dc7e234d 100644async function end({ timeout = null } = {}) {if (ending)return ending-@@ -398,7 +539,14 @@ function Postgres(a, b) {+@@ -398,7 +541,14 @@ function Postgres(a, b) {move(c, ended)}@@ -730,7 +890,7 @@ index f09c61c7..dc7e234d 100644if (queries.length === 0)return move(c, open)-@@ -418,12 +566,50 @@ function Postgres(a, b) {+@@ -418,12 +568,50 @@ function Postgres(a, b) {: move(c, full)}@@ -782,24 +942,26 @@ index f09c61c7..dc7e234d 100644}}-@@ -444,7 +630,7 @@ function parseOptions(a, b) {+@@ -444,7 +632,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-linequery.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 ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout', 'inflight_max', 'inflight_grace']const defaults = {max : globalThis.Cloudflare ? 3 : 10,ssl : false,-@@ -453,6 +639,7 @@ function parseOptions(a, b) {+@@ -453,6 +641,9 @@ function parseOptions(a, b) {connect_timeout : 30,max_lifetime : max_lifetime,max_pipeline : 100,+ inflight_timeout: null,++ inflight_max : null,++ inflight_grace : null,backoff : backoff,keep_alive : 60,prepare : true,-@@ -491,11 +678,16 @@ function parseOptions(a, b) {+@@ -491,11 +682,18 @@ function parseOptions(a, b) {onnotice : o.onnotice,onnotify : o.onnotify,onclose : o.onclose,@@ -807,6 +969,8 @@ index f09c61c7..dc7e234d 100644+ onstuck : o.onstuck,+ onbuilderror : o.onbuilderror,+ ondesync : o.ondesync,++ onrecovered : o.onrecovered,++ onrecoveryfailed: o.onrecoveryfailed,+ shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),onparameter : o.onparameter,socket : o.socket,@@ -818,7 +982,7 @@ index f09c61c7..dc7e234d 100644}}diff --git a/cjs/src/query.js b/vendor/postgres/cjs/src/query.js-index 45327f2f..1d092504 100644+index 45327f2..1d09250 100644--- a/cjs/src/query.js+++ b/vendor/postgres/cjs/src/query.js@@ -23,11 +23,12 @@ const Query = module.exports.Query = class Query extends Promise {@@ -862,7 +1026,7 @@ index 45327f2f..1d092504 100644this.execute()return promisediff --git a/cjs/src/queue.js b/vendor/postgres/cjs/src/queue.js-index 8438f5da..c444310f 100644+index 8438f5d..c444310 100644--- a/cjs/src/queue.js+++ b/vendor/postgres/cjs/src/queue.js@@ -15,6 +15,7 @@ function Queue(initial = []) {@@ -874,7 +1038,7 @@ index 8438f5da..c444310f 100644const out = xs[index++]diff --git a/cjs/src/types.js b/vendor/postgres/cjs/src/types.js-index 0578284c..e80a868e 100644+index 0578284..e80a868 100644--- a/cjs/src/types.js+++ b/vendor/postgres/cjs/src/types.js@@ -80,7 +80,7 @@ module.exports.handleValue = handleValue;function handleValue(x, parameters, typ@@ -887,7 +1051,7 @@ index 0578284c..e80a868e 100644return '$' + (types.push(diff --git a/src/connection.js b/vendor/postgres/src/connection.js-index 1b1cccde..84f8a587 100644+index 1b1cccd..9fc39c2 100644--- a/src/connection.js+++ b/vendor/postgres/src/connection.js@@ -20,6 +20,7 @@ const Sync = b().S().end()@@ -907,11 +1071,12 @@ index 1b1cccde..84f8a587 100644const {sslnegotiation,ssl,-@@ -75,9 +76,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -75,9 +76,14 @@ 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)++ , inflightTimer = budgetTimer('idle')++ , ageTimer = budgetTimer('age')let socket = null, cancelMessage@@ -921,7 +1086,7 @@ index 1b1cccde..84f8a587 100644, errorResponse = null, result = new Result(), incoming = Buffer.alloc(0)-@@ -95,6 +100,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -95,6 +101,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, rows = 0, serverSignature = null, nextWriteTimer = null@@ -931,21 +1096,26 @@ index 1b1cccde..84f8a587 100644, terminated = false, incomings = null, results = null-@@ -105,11 +113,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -105,11 +114,18 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, ended = null, nonce = null, query = null+ , queryStart = 0++ , received = 0++ , localBudget = undefined++ , sessionBudget = undefined++ , recovering = null, final = nullconst connection = {queue: queues.closed,idleTimer,+ inflightSince: 0,++ inflightCap: 0,connect(query) {initial = queryreconnect()-@@ -143,11 +153,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -143,11 +159,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}async function cancel({ pid, secret }, resolve, reject) {@@ -961,7 +1131,7 @@ index 1b1cccde..84f8a587 100644} catch (error) {reject(error)}-@@ -163,22 +175,78 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -163,22 +181,139 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseif (q.cancelled)return@@ -975,6 +1145,7 @@ index 1b1cccde..84f8a587 100644build(q)+ mayPipeline = mayPipeline || q.options.onexecute(connection)++ noteBudget(q)+ lastWritten = q+ lastExecuted = qreturn write(toBuffer(q))@@ -1024,16 +1195,76 @@ index 1b1cccde..84f8a587 100644+ // 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.++ //++ // GBrain (#6543 A4): a second clock, `ageTimer`, is not restarted by received bytes, so a statement that keeps++ // streaming (or keeps receiving notices) past its budget is retired too (`reason: 'age'`; `'idle'` when nothing came++ // back). Both budgets are derived per statement from the statement_timeout the operation itself declared on this++ // connection (`SET [LOCAL] statement_timeout`, `set_config('statement_timeout', ...)`, tracked client-side so it++ // holds behind a transaction-mode pooler that never applies it): max(the pool's budget, the declared timeout) plus++ // `inflight_grace`, and none at all for a declared timeout of 0 (an index build, a bulk copy).+ function armInflight() {+ queryStart = connection.inflightSince = performance.now()++ received = 0++ query.inflightCaps || (query.inflightCaps = inflightCaps())++ connection.inflightCap = query.inflightCaps.age+ inflightTimer.start()++ ageTimer.start()+ }+-+ function inflightTimedOut() {++ function budgetTimer(kind) {++ let handle = null++ return {++ cancel() {++ handle && (clearTimeout(handle), handle = null)++ },++ start() {++ handle && clearTimeout(handle)++ const ms = query && query.inflightCaps ? query.inflightCaps[kind] : 0++ handle = ms ? setTimeout(() => (handle = null, inflightTimedOut(kind)), ms) : null++ }++ }++ }++++ function inflightCaps() {++ const declared = localBudget !== undefined ? localBudget : sessionBudget++ if (declared === 0)++ return { idle: 0, age: 0 }++ const raised = declared === undefined ? 0 : declared + (options.inflight_grace || 0) * 1000++ return {++ idle: options.inflight_timeout ? Math.max(options.inflight_timeout * 1000, raised) : 0,++ age: options.inflight_max ? Math.max(options.inflight_max * 1000, raised) : 0++ }++ }++++ // The statement_timeout changes a statement makes on this connection; a later statement is budgeted by them.++ function noteBudget(q) {++ const text = q.string || ''++ if (localBudget === undefined && sessionBudget === undefined && !/statement_timeout/i.test(text))++ return++ for (const change of statementTimeoutChanges(text, q.parameters)) {++ change.kind === 'end'++ ? localBudget = undefined++ : change.kind === 'reset'++ ? localBudget = sessionBudget = undefined++ : change.kind === 'set' && (change.local ? localBudget = change.ms : (sessionBudget = change.ms, localBudget = undefined))++ }++ q.inflightCaps = inflightCaps()++ if (q === query) {++ connection.inflightCap = q.inflightCaps.age++ inflightTimer.start()++ ageTimer.start()++ }++ }++++ function inflightTimedOut(kind = 'idle') {+ if (!query)+ return-+ const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query) }++ inflightTimer.cancel()++ ageTimer.cancel()++ const reason = kind === 'age' && received > 0 ? 'age' : 'idle'++ const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query), reason, budget_ms: query.inflightCaps ? query.inflightCaps[kind] : 0 }+ const s = socket++ recovering = recovering || 'stuck'+ error(Errors.connection('CONNECTION_STUCK', options, socket))+ query = null+ connection.inflightSince = 0@@ -1045,7 +1276,7 @@ index 1b1cccde..84f8a587 100644}}-@@ -235,10 +303,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -235,10 +370,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.onlyDescribe && (delete statements[q.signature])q.parameters = q.parameters || parametersq.prepared = q.prepare && q.signature in statements@@ -1063,7 +1294,7 @@ index 1b1cccde..84f8a587 100644typeof options.debug === 'function' && options.debug(id, string, parameters, types)}-@@ -295,10 +368,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -295,10 +435,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* c8 ignore next 3 */function drain() {@@ -1072,11 +1303,11 @@ index 1b1cccde..84f8a587 100644}function data(x) {-+ query && inflightTimer.start()++ query && (received += x.length, inflightTimer.start())if (incomings) {incomings.push(x)remaining -= x.length-@@ -379,15 +453,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -379,20 +520,35 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function error(err) {@@ -1097,8 +1328,22 @@ index 1b1cccde..84f8a587 100644+ cancelError = errstream && (stream.destroy(err), stream = null)query && queryError(query, err)++ initial && recovering && recoveryFailed(err)initial && (queryError(initial, err), initial = null)-@@ -438,19 +518,43 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+ }+++ // GBrain (#6543 A6): a connection retired by an incident (stuck, desync, closed under statements) that completes a++ // new startup is `recovered`; one whose reconnect fails is `recovery_failed` (it stays marked until one succeeds).++ function recoveryFailed(err) {++ try {++ options.onrecoveryfailed && options.onrecoveryfailed({ connection: id, cause: recovering, code: String(err && err.code || 'CONNECTION_ERROR') })++ } catch (_) {}++ }+++ function queryError(query, err) {+ if (query.reserve)+ return query.reject(err)+@@ -438,19 +594,47 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseremaining = 0incomings = nullclearImmediate(nextWriteTimer)@@ -1112,7 +1357,9 @@ index 1b1cccde..84f8a587 100644lifeTimer.cancel()connectTimer.cancel()+ inflightTimer.cancel()-+ connection.inflightSince = 0++ ageTimer.cancel()++ connection.inflightSince = connection.inflightCap = 0++ localBudget = sessionBudget = undefinedsocket.removeAllListeners()socket = null@@ -1133,6 +1380,8 @@ index 1b1cccde..84f8a587 100644return reconnect()+ }++ // GBrain (#6543 A6): a socket that closed under statements is a recovery the next completed startup reports.++ ;(query || sent.length) && (recovering = recovering || 'closed')!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))+ // GBrain (#6543): the dead socket's ErrorResponse (a FATAL 57P01, a pooler's XX000) and its partial result belonged+ // to statements that just failed. Left in place, the replacement connection's startup ReadyForQuery handed that@@ -1143,7 +1392,7 @@ index 1b1cccde..84f8a587 100644closedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000-@@ -459,6 +563,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -459,6 +643,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* Handlers */function handle(xs, x = xs[0]) {@@ -1154,7 +1403,7 @@ index 1b1cccde..84f8a587 100644(x === 68 ? DataRow : // Dx === 100 ? CopyData : // d-@@ -489,6 +597,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -489,6 +677,39 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose)(xs)}@@ -1177,9 +1426,12 @@ index 1b1cccde..84f8a587 100644+ function desynced(x) {+ const s = socket+ const info = { message: String.fromCharCode(x), connection: id, statement: lastExecuted ? statementText(lastExecuted) : '' }++ recovering = recovering || 'desync'+ error(Errors.connection('CONNECTION_DESYNC', options, socket))++ inflightTimer.cancel()++ ageTimer.cancel()+ query = null-+ connection.inflightSince = 0++ connection.inflightSince = connection.inflightCap = 0+ ondesync(connection, info)+ terminate()+ if (s && !s.destroyed) {@@ -1191,13 +1443,15 @@ index 1b1cccde..84f8a587 100644function DataRow(x) {let index = 7let length-@@ -533,13 +671,23 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -533,13 +754,25 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function ReadyForQuery(x) {+ connection.status = x[5]+ query && query === lastWritten && (lastWritten = null)-+ connection.inflightSince = 0++ connection.inflightSince = connection.inflightCap = 0++ // A transaction that ended takes its SET LOCAL statement_timeout with it.++ x[5] === 73 && !sent.length && (localBudget = undefined)if (query) {+ options.shared.completed++if (errorResponse) {@@ -1216,15 +1470,16 @@ index 1b1cccde..84f8a587 100644} else {query.resolve(results || result)}-@@ -550,6 +698,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -550,6 +783,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosequery = results = errorResponse = nullresult = new Result()connectTimer.cancel()+ inflightTimer.cancel()++ ageTimer.cancel()if (initial) {if (target_session_attrs) {-@@ -564,23 +713,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -564,23 +799,43 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn fetchArrayTypes()}@@ -1234,12 +1489,17 @@ index 1b1cccde..84f8a587 100644options.shared.retries = retries = 0initial = null- return++ if (recovering) {++ const cause = recovering++ recovering = null++ try {++ options.onrecovered && options.onrecovered({ connection: id, cause })++ } catch (_) {}++ }+ if (!reserving)+ return- }--- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))-- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)++ }+++ // GBrain: the stock loop skipped a query cancelled while it waited behind another one, so the answer the+ // server still sent for it was read for the next query (the next query resolved with another statement's+ // rows, and the cancelled one never settled). The cancelled query stays current and absorbs its own answer.@@ -1250,8 +1510,10 @@ index 1b1cccde..84f8a587 100644+ query.cancelled && (sent.length+ ? query.cancelled.resolve()+ : Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject))-+ }-++ }++- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))+- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)+ flushRetries()if (query)@@ -1267,7 +1529,7 @@ index 1b1cccde..84f8a587 100644: connection.reserved(): ending? terminate()-@@ -630,7 +792,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -630,7 +885,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))query.prepare && (statements[query.signature] = query.statement)@@ -1279,7 +1541,7 @@ index 1b1cccde..84f8a587 100644}function RowDescription(x) {-@@ -767,14 +933,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -767,14 +1026,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false@@ -1309,7 +1571,7 @@ index 1b1cccde..84f8a587 100644types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))}-@@ -821,7 +994,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -821,7 +1087,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction retry(q, error) {delete statements[q.signature]q.retried = error@@ -1327,11 +1589,71 @@ index 1b1cccde..84f8a587 100644}function NotificationResponse(x) {+@@ -1039,6 +1314,59 @@ function xor(a, b) {+ return buffer+ }+++// GBrain (#6543 A4): what one statement does to the connection's statement_timeout, in order: `set` (`local`, `ms`;++// 0 disables it, undefined is DEFAULT), `reset` (RESET statement_timeout / RESET ALL / DISCARD ALL), `end` (a++// transaction began or ended, which drops a SET LOCAL), and `unknown` for a change whose value cannot be read here.++// Dollar-quoted bodies are skipped, so a function body's BEGIN/END is not a transaction boundary.++const budgetSyntax = /(?:^|;)\s*(begin|start\s+transaction|commit|end|abort|rollback(?!\s+(?:to|prepared)\b))\b|\bset\s+(local\s+|session\s+)?statement_timeout\s*(?:=|\bto\b)\s*('(?:[^']|'')*'|[^\s;)]+)|\breset\s+(?:statement_timeout|all)\b|\bdiscard\s+all\b|\bset_config\s*\(\s*'statement_timeout'\s*,\s*('(?:[^']|'')*'|\$\d+)\s*,\s*([^)\s]+)\s*\)/gi++++function statementTimeoutChanges(text, parameters) {++ const changes = []++ const plain = String(text || '').replace(/\$([A-Za-z_][A-Za-z0-9_]*)?\$[\s\S]*?\$\1\$/g, ' ')++ budgetSyntax.lastIndex = 0++ let m++ while ((m = budgetSyntax.exec(plain))) {++ if (m[1]) {++ changes.push({ kind: 'end' })++ } else if (m[3] !== undefined) {++ const ms = timeoutMs(m[3], parameters)++ changes.push(Number.isNaN(ms) ? { kind: 'unknown' } : { kind: 'set', local: /^local/i.test(m[2] || ''), ms })++ } else if (m[4] !== undefined) {++ const ms = timeoutMs(m[4], parameters)++ const local = parameterValue(m[5], parameters)++ changes.push(Number.isNaN(ms) || local === undefined ? { kind: 'unknown' } : { kind: 'set', local: /^(t|true|on|1)$/i.test(local), ms })++ } else {++ changes.push({ kind: 'reset' })++ }++ }++ return changes++}++++function parameterValue(raw, parameters) {++ const p = /^\$(\d+)$/.exec(raw.trim())++ if (p) {++ const v = parameters && parameters[p[1] - 1]++ return v === null || v === undefined ? undefined : String(v)++ }++ const v = raw.trim()++ return /^'.*'$/s.test(v) ? v.slice(1, -1).replace(/''/g, "'") : v++}++++function timeoutMs(raw, parameters) {++ const v = parameterValue(raw, parameters)++ if (v === undefined)++ return NaN++ if (/^default$/i.test(v.trim()))++ return undefined++ const m = /^\s*(\d+(?:\.\d+)?)\s*(us|ms|s|min|h|d)?\s*$/i.exec(v)++ if (!m)++ return NaN++ const unit = (m[2] || 'ms').toLowerCase()++ return Math.round(+m[1] * { us: 0.001, ms: 1, s: 1000, min: 60000, h: 3600000, d: 86400000 }[unit])++}++++Connection.statementTimeoutChanges = statementTimeoutChanges+++ function timer(fn, seconds) {+ seconds = typeof seconds === 'function' ? seconds() : seconds+ if (!seconds)diff --git a/src/index.js b/vendor/postgres/src/index.js-index c7fba3da..6718a17d 100644+index c7fba3d..5bfd92f 100644--- a/src/index.js+++ b/vendor/postgres/src/index.js-@@ -62,10 +62,34 @@ function Postgres(a, b) {+@@ -62,10 +62,36 @@ function Postgres(a, b) {, full = Queue(), queues = { connecting, reserved, closed, ended, open, busy, full }@@ -1359,6 +1681,8 @@ index c7fba3da..6718a17d 100644+ ended: ended.length,+ queued: queries.length,+ inflight_oldest_ms: connections.reduce((age, c) => c.inflightSince ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),++ // GBrain (#6543 A4): the oldest head statement past its own budget (the cap the driver retires it at), 0 when none is.++ inflight_over_budget_ms: connections.reduce((age, c) => c.inflightSince && c.inflightCap && now - c.inflightSince > c.inflightCap ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),+ completed: options.shared.completed+ }+ }@@ -1367,7 +1691,7 @@ index c7fba3da..6718a17d 100644Object.assign(sql, {get parameters() { return options.parameters },largeObject: largeObject.bind(null, sql),-@@ -200,40 +224,134 @@ function Postgres(a, b) {+@@ -200,40 +226,134 @@ function Postgres(a, b) {return await sql`select pg_notify(${ channel }, ${ '' + payload })`}@@ -1521,7 +1845,7 @@ index c7fba3da..6718a17d 100644let savepoints = 0, connection, prepare = null-@@ -249,9 +367,13 @@ function Postgres(a, b) {+@@ -249,9 +369,13 @@ function Postgres(a, b) {}async function scope(c, fn, name) {@@ -1535,7 +1859,7 @@ index c7fba3da..6718a17d 100644let uncaughtError, result-@@ -281,6 +403,8 @@ function Postgres(a, b) {+@@ -281,6 +405,8 @@ function Postgres(a, b) {return resultfunction savepoint(name, fn) {@@ -1544,7 +1868,7 @@ index c7fba3da..6718a17d 100644if (name && Array.isArray(name.raw))return savepoint(sql => sql.apply(sql, arguments))-@@ -290,18 +414,16 @@ function Postgres(a, b) {+@@ -290,18 +416,16 @@ function Postgres(a, b) {function handler(q) {q.catch(e => uncaughtError || (uncaughtError = e))@@ -1567,7 +1891,7 @@ index c7fba3da..6718a17d 100644}}-@@ -351,7 +473,7 @@ function Postgres(a, b) {+@@ -351,7 +475,7 @@ function Postgres(a, b) {return new Promise((resolve, reject) => {query.state? query.active@@ -1576,7 +1900,7 @@ index c7fba3da..6718a17d 100644: query.cancelled = { resolve, reject }: (queries.remove(query),-@@ -362,6 +484,25 @@ function Postgres(a, b) {+@@ -362,6 +486,25 @@ function Postgres(a, b) {})}@@ -1602,7 +1926,7 @@ index c7fba3da..6718a17d 100644async function end({ timeout = null } = {}) {if (ending)return ending-@@ -398,7 +539,14 @@ function Postgres(a, b) {+@@ -398,7 +541,14 @@ function Postgres(a, b) {move(c, ended)}@@ -1618,7 +1942,7 @@ index c7fba3da..6718a17d 100644if (queries.length === 0)return move(c, open)-@@ -418,12 +566,50 @@ function Postgres(a, b) {+@@ -418,12 +568,50 @@ function Postgres(a, b) {: move(c, full)}@@ -1670,24 +1994,26 @@ index c7fba3da..6718a17d 100644}}-@@ -444,7 +630,7 @@ function parseOptions(a, b) {+@@ -444,7 +632,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-linequery.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 ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout', 'inflight_max', 'inflight_grace']const defaults = {max : globalThis.Cloudflare ? 3 : 10,ssl : false,-@@ -453,6 +639,7 @@ function parseOptions(a, b) {+@@ -453,6 +641,9 @@ function parseOptions(a, b) {connect_timeout : 30,max_lifetime : max_lifetime,max_pipeline : 100,+ inflight_timeout: null,++ inflight_max : null,++ inflight_grace : null,backoff : backoff,keep_alive : 60,prepare : true,-@@ -491,11 +678,16 @@ function parseOptions(a, b) {+@@ -491,11 +682,18 @@ function parseOptions(a, b) {onnotice : o.onnotice,onnotify : o.onnotify,onclose : o.onclose,@@ -1695,6 +2021,8 @@ index c7fba3da..6718a17d 100644+ onstuck : o.onstuck,+ onbuilderror : o.onbuilderror,+ ondesync : o.ondesync,++ onrecovered : o.onrecovered,++ onrecoveryfailed: o.onrecoveryfailed,+ shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),onparameter : o.onparameter,socket : o.socket,@@ -1706,7 +2034,7 @@ index c7fba3da..6718a17d 100644}}diff --git a/src/query.js b/vendor/postgres/src/query.js-index 0d44a15c..96967780 100644+index 0d44a15..9696778 100644--- a/src/query.js+++ b/vendor/postgres/src/query.js@@ -23,11 +23,12 @@ export class Query extends Promise {@@ -1750,7 +2078,7 @@ index 0d44a15c..96967780 100644this.execute()return promisediff --git a/src/queue.js b/vendor/postgres/src/queue.js-index c4ef9716..8fba891b 100644+index c4ef971..8fba891 100644--- a/src/queue.js+++ b/vendor/postgres/src/queue.js@@ -15,6 +15,7 @@ function Queue(initial = []) {@@ -1762,7 +2090,7 @@ index c4ef9716..8fba891b 100644const out = xs[index++]diff --git a/src/types.js b/vendor/postgres/src/types.js-index 7c7c2b93..d462498a 100644+index 7c7c2b9..d462498 100644--- a/src/types.js+++ b/vendor/postgres/src/types.js@@ -80,7 +80,7 @@ export function handleValue(x, parameters, types, options) {@@ -1775,10 +2103,10 @@ index 7c7c2b93..d462498a 100644return '$' + (types.push(diff --git a/types/index.d.ts b/vendor/postgres/types/index.d.ts-index 13c3432f..b77d74e1 100644+index 13c3432..0d48716 100644--- a/types/index.d.ts+++ b/vendor/postgres/types/index.d.ts-@@ -119,6 +119,38 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {+@@ -119,6 +119,51 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {*/publications: stringonclose: (connId: number) => void;@@ -1794,8 +2122,21 @@ index 13c3432f..b77d74e1 100644+ * @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 (#6543): seconds a head statement may run in total, whatever the server keeps sending, before the++ * connection is retired with `CONNECTION_STUCK` (`reason: 'age'`). A statement after a declared++ * `statement_timeout` above the budget gets that timeout plus `inflight_grace`; a declared 0 disables both clocks.++ * @default null++ */++ inflight_max: number | null;++ /** GBrain (#6543): seconds added to a declared statement_timeout that raises a statement's budget. @default null */++ inflight_grace: number | null;++ /** GBrain: called once per connection the in-flight watchdog retired; `reason` is `age` when bytes kept arriving, else `idle`. */++ onstuck: (stuck: { age_ms: number; queued: number; statement: string; reason: 'age' | 'idle'; budget_ms: number }) => void;++ /** GBrain (#6543): a connection retired by an incident (`stuck`, `desync`, `closed` under statements) completed a new startup. */++ onrecovered: (recovered: { connection: number; cause: 'stuck' | 'desync' | 'closed' }) => void;++ /** GBrain (#6543): the reconnect of a connection retired by an incident failed; it stays marked until one succeeds. */++ onrecoveryfailed: (failed: { connection: number; cause: 'stuck' | 'desync' | 'closed'; code: 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; `parameter` is the 1-based@@ -1817,7 +2158,7 @@ index 13c3432f..b77d74e1 100644backoff: boolean | ((attemptNum: number) => number);max_lifetime: number | null;keep_alive: number | null;-@@ -605,7 +637,7 @@ declare namespace postgres {+@@ -605,7 +650,7 @@ declare namespace postgres {writable(): Promise<Writable>;execute(): this;@@ -1826,7 +2167,7 @@ index 13c3432f..b77d74e1 100644/*** @deprecated `.stream` has been renamed to `.forEach`-@@ -659,6 +691,7 @@ declare namespace postgres {+@@ -659,6 +704,7 @@ declare namespace postgres {| Fragment[]interface UnsafeQueryOptions {@@ -1834,7 +2175,7 @@ index 13c3432f..b77d74e1 100644/*** When executes query as prepared statement.* @default false-@@ -705,6 +738,8 @@ declare namespace postgres {+@@ -705,6 +751,8 @@ declare namespace postgres {options: ParsedOptions<TTypes>;parameters: ConnectionParameters;@@ -1843,7 +2184,7 @@ index 13c3432f..b77d74e1 100644end(options?: { timeout?: number | undefined } | undefined): Promise<void>;-@@ -717,10 +752,11 @@ declare namespace postgres {+@@ -717,10 +765,11 @@ declare namespace postgres {begin<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;begin<T>(options: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;@@ -1856,7 +2197,7 @@ index 13c3432f..b77d74e1 100644savepoint<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;savepoint<T>(name: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;-@@ -728,6 +764,7 @@ declare namespace postgres {+@@ -728,6 +777,7 @@ declare namespace postgres {}interface ReservedSql<TTypes extends Record<string, unknown> = {}> extends Sql<TTypes> {diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex a64bf3b96b..ca3f419ed0 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -255,7 +255,7 @@ test/pglite-repair-command.serial.test.ts gbrain pglite-repair — interactive ctest/pglite-wal-repair.serial.test.ts WAL auto-repair — real-brain regression (#223/#1670/#2575) 6 source-surface-helpertest/physical-root-birth-tolerance-6501.test.ts physical root birth drift (${kind}) 5 readFileSynctest/physical-root-birth-tolerance-6501.test.ts samePhysicalBirth (#6501) 5 readFileSync-test/postgres-driver-vendor.test.ts vendored Postgres driver packaging 4 readFileSync+test/postgres-driver-vendor.test.ts vendored Postgres driver packaging 5 readFileSynctest/postgres-engine.test.ts postgres-engine / search date filtering 2 source-surface-helpertest/postgres-engine.test.ts postgres-engine / search path timeout isolation 7 source-surface-helpertest/private-visibility.test.ts shared private predicate lives once (#4352 remediation) 1 readFileSyncdiff --git a/src/commands/doctor/checks/pglite-worker.ts b/src/commands/doctor/checks/pglite-worker.tsindex 5674f93948..6d8ad34fbb 100644--- a/src/commands/doctor/checks/pglite-worker.ts+++ b/src/commands/doctor/checks/pglite-worker.ts@@ -233,6 +233,10 @@ export async function computeWorkerOomLoopCheck(* rebuilds are throwing (genuinely not recovering).* - warn: reaps>=10/hr, all recovered → pooler thrash (self-heal works but the* cap is likely too low / concurrency too high).+ * - fail (#6543 A6): a connection serve's driver retired (stuck, desync,+ * closed under statements) could not reconnect.+ * - warn (#6543 A6): serve's driver retired a connection as stuck or+ * desynced in the last hour (statements failed with it).* - else: null (quiet — a few reaps that all recovered is normal).** Returns null on PGLite / no engine / audit-read failure. Exported so@@ -242,7 +246,7 @@ export async function computePoolReapHealthCheck(engine: BrainEngine | null,): Promise<Check | null> {if (!engine || engine.kind === 'pglite') return null;- let r: { reaps: number; recoveries: number; failures: number };+ let r: { reaps: number; recoveries: number; failures: number; stuck: number; desyncs: number; connection_recoveries: number; connection_recovery_failures: number };try {const { readRecentPoolRecoveries } = await import('../../../core/audit/pool-recovery-audit.ts');r = readRecentPoolRecoveries(1);@@ -267,6 +271,31 @@ export async function computePoolReapHealthCheck(details: { reaps: r.reaps, recoveries: r.recoveries, failures: r.failures, fix_hint: fix },};}+ const incidents = { stuck: r.stuck, desyncs: r.desyncs, connection_recoveries: r.connection_recoveries, connection_recovery_failures: r.connection_recovery_failures };+ if (r.connection_recovery_failures > 0) {+ const fix = 'check DB reachability / credentials from the serve host (a retired connection cannot reconnect); see docs/ENGINES.md#pg-connection-recovery-failed';+ return {+ name: 'pool_reap_health',+ status: 'fail',+ message:+ `gbrain serve could not reconnect a retired connection ${r.connection_recovery_failures}× in last hour ` ++ `(${r.stuck} stuck, ${r.desyncs} desynced, ${r.connection_recoveries} recovered); ${fix}.`,+ details: { reaps: r.reaps, recoveries: r.recoveries, failures: r.failures, ...incidents, fix_hint: fix },+ };+ }+ if (r.stuck + r.desyncs > 0) {+ const fix = r.desyncs > 0+ ? 'a desynced pipeline usually means a transaction-mode pooler: set PGMAX_PIPELINE=0 for serve; see docs/ENGINES.md#pg-connection-stuck'+ : 'a statement outlived its in-flight budget; the warn line names reason=age|idle and the statement; see docs/ENGINES.md#pg-connection-stuck';+ return {+ name: 'pool_reap_health',+ status: 'warn',+ message:+ `gbrain serve retired ${r.stuck} stuck and ${r.desyncs} desynced connection(s) in last hour ` ++ `(${r.connection_recoveries} recovered); ${fix}.`,+ details: { reaps: r.reaps, recoveries: r.recoveries, failures: r.failures, ...incidents, fix_hint: fix },+ };+ }if (r.reaps >= 10) {const fix = 'raise --max-rss or reduce worker concurrency (pooler thrash)';return {diff --git a/src/commands/serve-http-metrics.ts b/src/commands/serve-http-metrics.tsindex 109c37c439..c052276e17 100644--- a/src/commands/serve-http-metrics.ts+++ b/src/commands/serve-http-metrics.ts@@ -283,8 +283,12 @@ export async function probeDeepHealth(if (timer !== null) clearTimeout(timer);}const snapshot = pool();- if (snapshot && budgetMs !== null && snapshot.inflight_oldest_ms > budgetMs) {- return unavailable('pool_inflight_over_budget', `A pooled statement has waited ${snapshot.inflight_oldest_ms} ms for the server, past the pool budget of ${budgetMs} ms`);+ // #6543 (A4): a driver with per-statement budgets reports the statements past their own budget, so a transaction that+ // declared a longer statement_timeout (or an index build that declared 0) is not called over budget; an older driver+ // falls back to the pool budget.+ const over = snapshot ? snapshot.inflight_over_budget_ms ?? (budgetMs !== null && snapshot.inflight_oldest_ms > budgetMs ? snapshot.inflight_oldest_ms : 0) : 0;+ if (over > 0) {+ return unavailable('pool_inflight_over_budget', `A pooled statement has waited ${over} ms for the server, past its in-flight budget${budgetMs !== null ? ` (the pool's is ${budgetMs} ms)` : ''}`);}return { ok: true, status: 200, body: { status: 'ok', deep: true, version, engine: engineName, probe_ms: Date.now() - started, pool: pool(), transport } };}diff --git a/src/commands/serve.ts b/src/commands/serve.tsindex 56a32428d2..c948ad15a9 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -249,6 +249,11 @@ export async function runServe(}console.error(`[gbrain serve] surface=${surface} (source: ${SURFACE_SOURCE_LABEL[resolved.source]})`);void (await import('../core/serve-behavior-notice.ts')).logServeBehaviorNotice(engine, loadConfig());+ // #6543 (A6): serve's stuck, desync and recovery events go to the pool-recovery audit `doctor --only pool_reap_health` reads.+ if (engine.kind === 'postgres') {+ const { logPoolRecovery } = await import('../core/audit/pool-recovery-audit.ts');+ (await import('../core/pool-gauge.ts')).setPoolIncidentAudit((kind, detail) => logPoolRecovery(kind, undefined, detail));+ }// #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();// #6543: the read pool's transport facts, logged once and kept for /health?deep=1; the opt-in unhealthy exit.diff --git a/src/core/audit/pool-recovery-audit.ts b/src/core/audit/pool-recovery-audit.tsindex 2cdc5e8bfc..ab6c25290d 100644--- a/src/core/audit/pool-recovery-audit.ts+++ b/src/core/audit/pool-recovery-audit.ts@@ -20,6 +20,15 @@* - `reconnect_succeeded` the rebuild completed* - `reconnect_failed` the rebuild threw (NOT auto-recovering)*+ * #6543 (A6): a resident `gbrain serve` also records the vendored driver's own+ * per-connection incidents here (`setPoolIncidentAudit` in pool-gauge.ts):+ * - `connection_stuck` the in-flight watchdog retired a connection+ * - `connection_desync` a desynced pipeline retired a connection+ * - `connection_recovered` a retired connection reconnected+ * - `connection_recovery_failed` its reconnect failed+ * `detail` carries the fixed-shape warn line (pool, reason, SQL keyword and+ * table; never statement text or parameters).+ ** Built on the shared `audit-writer.ts` cathedral — same ISO-week rotation,* same best-effort write semantics. File:* `~/.gbrain/audit/pool-recovery-YYYY-Www.jsonl` (honors `GBRAIN_AUDIT_DIR`).@@ -37,13 +46,19 @@ export type PoolRecoveryEventKind =| 'reap_detected'| 'reconnect_other'| 'reconnect_succeeded'- | 'reconnect_failed';+ | 'reconnect_failed'+ | 'connection_stuck'+ | 'connection_desync'+ | 'connection_recovered'+ | 'connection_recovery_failed';export interface PoolRecoveryEvent {ts: string;kind: PoolRecoveryEventKind;/** Redacted + truncated triggering-error message; absent on success events. */error_summary?: string;+ /** #6543 (A6): the driver incident's fixed-shape line (connection_* kinds). */+ detail?: string;pid: number;}@@ -66,12 +81,13 @@ function summarizeError(err: unknown): string | undefined {* Log one pool-recovery event. Best-effort: stderr-warns on write failure but* never throws. The caller's reconnect path continues regardless.*/-export function logPoolRecovery(kind: PoolRecoveryEventKind, err?: unknown): void {+export function logPoolRecovery(kind: PoolRecoveryEventKind, err?: unknown, detail?: string): void {const summary = summarizeError(err);writer.log({kind,pid: process.pid,...(summary !== undefined ? { error_summary: summary } : {}),+ ...(detail !== undefined ? { detail: redactConnectionInfo(detail).slice(0, 600) } : {}),});}@@ -85,6 +101,11 @@ export interface ReadPoolRecoveryResult {failures: number;/** Non-reap reconnects (network/auth/health-check) in window. */others: number;+ /** #6543 (A6): connections the driver retired as stuck / desynced, and their reconnects that succeeded / failed. */+ stuck: number;+ desyncs: number;+ connection_recoveries: number;+ connection_recovery_failures: number;most_recent_ts: string | null;}@@ -111,11 +132,19 @@ export function readRecentPoolRecoveries(let recoveries = 0;let failures = 0;let others = 0;+ let stuck = 0;+ let desyncs = 0;+ let connectionRecoveries = 0;+ let connectionRecoveryFailures = 0;for (const e of events) {if (e.kind === 'reap_detected') reaps++;else if (e.kind === 'reconnect_succeeded') recoveries++;else if (e.kind === 'reconnect_failed') failures++;else if (e.kind === 'reconnect_other') others++;+ else if (e.kind === 'connection_stuck') stuck++;+ else if (e.kind === 'connection_desync') desyncs++;+ else if (e.kind === 'connection_recovered') connectionRecoveries++;+ else if (e.kind === 'connection_recovery_failed') connectionRecoveryFailures++;}return {@@ -124,6 +153,10 @@ export function readRecentPoolRecoveries(recoveries,failures,others,+ stuck,+ desyncs,+ connection_recoveries: connectionRecoveries,+ connection_recovery_failures: connectionRecoveryFailures,most_recent_ts: events[0]?.ts ?? null,};}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 50fe89829e..7ee377f520 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -496,6 +496,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.187.0', text: 'Importing an image no longer writes `type` or `title` into its frontmatter (the keys `gbrain repair frontmatter-keys` strips since 0.60.177.0). Doctor `stale_frontmatter_keys` names 0.60.177.0 and, on a brain with several sources, its fix is the all-sources `gbrain repair frontmatter-keys`, with the per-source commands listed.' },{ since: '0.60.187.0', text: '`gbrain embed --stale --images` and doctor `image_assets` find an image whose recorded path differs from the file on disk only in letter case (an exact match still wins), import it under the real-case path, and refuse a case-fold match that is ambiguous or resolves outside the source root instead of importing or counting it. `image_assets` reports case-only, ambiguous and unrooted counts.' },{ since: '0.60.187.0', text: 'On a managed brain, a successful `gbrain sync --source <id>` settles legacy rows the pre-managed sync left in `sync-failures.jsonl` one at a time (the imported commit holds the file and a live page claims it, or the file is gone and no page claims it); rows on an unknown commit, sentinel rows, held files and files it did not index stay. Doctor `sync_failures` says how many unresolved rows are legacy and which command settles them, and `gbrain sync --retry-failed` names them instead of saying the ledger is empty.' },+ { since: '0.60.187.0', text: 'The Postgres in-flight watchdog now also retires a connection whose statement keeps receiving rows or notices past its budget (`pg_connection_stuck` `reason=age`; `reason=idle` when nothing came back, which used to be the only case), and the budget is per statement: an operation that declares a longer `statement_timeout` on its connection (`SET LOCAL`, `set_config`, a session `SET` on a reserved connection) gets that timeout plus the grace, and a declared 0 has no cap, read from the statements themselves so it holds behind a transaction-mode pooler. The warn line adds `reason=` and `budget_ms=`, and `/health?deep=1` reports `pool_inflight_over_budget` only for a statement past its own budget (a long transaction that declared its timeout no longer reads as over budget).' },+ { since: '0.60.187.0', text: 'Pools count reconnects of connections retired after an incident (stuck, desynced, or closed under running statements): `recovered` and `recovery_failed` in `/health?deep=1` and `getPoolDiagnostics()`, and a failed reconnect logs `pg_connection_recovery_failed`. `gbrain serve` writes its stuck, desync and recovery events to the pool-recovery audit, so `gbrain doctor --only pool_reap_health` now fails on a recovery failure and warns on a stuck or desynced connection in the last hour.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/db.ts b/src/core/db.tsindex 46c241a37e..a6f1126e69 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -343,7 +343,10 @@ export function gbrainApplicationName(): string {* 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 }+/** #6543 (A4): `reason` is `age` when the statement kept receiving bytes past its budget, `idle` when nothing came back; `budget_ms` is that statement's own cap. */+export interface StuckConnectionInfo { age_ms: number; queued: number; statement: string; reason?: 'age' | 'idle'; budget_ms?: number }+/** #6543 (A6): a connection the driver retired for an incident (`stuck`, `desync`, `closed` under statements) reconnected, or failed to. */+export interface ConnectionRecoveryInfo { connection: number; cause: 'stuck' | 'desync' | 'closed'; code?: string }export interface PoolHealthHooks {/** #5730: a connection came back to the pool inside a transaction and was discarded. */onpoisoned?: (status: string) => void;@@ -353,6 +356,10 @@ export interface PoolHealthHooks {onbuilderror?: (code: string, statement: string, parameter?: number) => void;/** An answer arrived on a connection with no statement waiting for it; the driver retired the connection. */ondesync?: (info: DesyncConnectionInfo) => void;+ /** #6543 (A6): a connection retired by an incident completed a new startup. */+ onrecovered?: (info: ConnectionRecoveryInfo) => void;+ /** #6543 (A6): the reconnect of a connection retired by an incident failed. */+ onrecoveryfailed?: (info: ConnectionRecoveryInfo) => void;}export interface DesyncConnectionInfo { message: string; connection: number; statement: string }@@ -370,32 +377,48 @@ export function gucMilliseconds(value: string | undefined): number | 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). Usually only a wedged connection- * (a desynced pipeline, a pooler that swallowed a CancelRequest, a dead peer)- * reaches it, but not always: behind a transaction-mode pooler the startup- * statement_timeout never applies, so a slow statement can reach it too, and- * the clock restarts on every byte, so a streaming statement never does (#6543).- * Null, which disables the watchdog, when the statement timeout is off or the- * grace is `0`/`off`.+ * #6383: the pool's in-flight budget in seconds: its `statement_timeout` plus+ * `GBRAIN_PG_STUCK_GRACE_MS` (default 30000). The driver retires a connection+ * whose head statement waits that long with nothing coming back (`reason=idle`)+ * or, since #6543, runs that long in total while bytes keep arriving+ * (`reason=age`). A statement whose operation declared a longer+ * `statement_timeout` on its connection gets that timeout plus the grace; a+ * declared 0 has no cap. 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 grace = resolveStuckGraceMs();+ const budget = gucMilliseconds(statementTimeout);+ return budget === null || grace === null ? null : Math.ceil((budget + grace) / 1000);+}++/** `GBRAIN_PG_STUCK_GRACE_MS` (default 30000), or null when it is `0`/`off` (the watchdog is disabled). */+export function resolveStuckGraceMs(): 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);+ return raw !== undefined && Number.isFinite(Number(raw)) && Number(raw) > 0 ? Number(raw) : DEFAULT_STUCK_GRACE_MS;}-/** The postgres.js options for `PoolHealthHooks` on a pool whose connections start with `connection.statement_timeout`. */+/**+ * The postgres.js options for `PoolHealthHooks` on a pool whose connections start with `connection.statement_timeout`.+ * #6543 (A4): the same budget caps a statement's total age (`inflight_max`, never reset by received bytes) and its+ * silence (`inflight_timeout`). The driver raises both for a statement whose operation declared a longer+ * `statement_timeout` on its connection (to that timeout plus `inflight_grace`) and drops both for a declared 0, so+ * the budget travels with the operation and does not depend on a session `SET` reaching the backend.+ */export function poolHealthOptions(hooks: PoolHealthHooks | undefined, statementTimeout: string | undefined): Record<string, unknown> {+ const seconds = resolveInflightTimeoutSeconds(statementTimeout);+ const grace = resolveStuckGraceMs();return {onpoisoned: hooks?.onpoisoned,onstuck: hooks?.onstuck,onbuilderror: hooks?.onbuilderror,ondesync: hooks?.ondesync,- inflight_timeout: resolveInflightTimeoutSeconds(statementTimeout),+ onrecovered: hooks?.onrecovered,+ onrecoveryfailed: hooks?.onrecoveryfailed,+ inflight_timeout: seconds,+ inflight_max: seconds,+ inflight_grace: seconds === null || grace === null ? null : grace / 1000,};}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 3ec36995e6..8e6cfaafa1 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -330,14 +330,15 @@ 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_restart_required: { class: 'host_only', summary: "This gbrain serve's persistence consumer reports restart_required, so it claims no write until the process restarts; `/health?deep=1` answers 503 with this code.", why: "A preparation abandoned past the ceiling (a zombie) or a publication that never settled past its deadline makes the owner stop claiming on every root, because the abandoned work may still hold locks or write files; only a process exit releases it. The deep health probe reports it so a supervisor can restart serve; it never acts on its own (GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS opts into an exit).", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Restart the serve process (for the installed service: systemctl --user restart gbrain-serve; otherwise stop and start it in the foreground); to let a supervisor do it unattended, set GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=300 in the serve environment (~/.gbrain/env for the installed service). Then run gbrain sources writer status --json.' },- pool_inflight_over_budget: { class: 'host_only', summary: "A pooled statement of this gbrain serve has waited longer than the read pool's in-flight budget (statement_timeout plus grace); `/health?deep=1` answers 503 with this code.", why: "The in-flight watchdog retires a connection only after nothing arrives for the budget, so a statement that keeps receiving bytes, or one behind a transaction-mode pooler where no server statement_timeout applies, can sit past it while every statement queued behind it waits. Through a transaction-mode pooler a pipelined answer can also be misrouted. The probe reports it and never retires the connection, because the endpoint is unauthenticated.", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Restart this gbrain serve. On a transaction-mode pooler check the transport block of /health?deep=1: max_pipeline should read 0 (set PGMAX_PIPELINE=0 in the serve environment to force it) and session_timeouts_not_applied names the ALTER ROLE fix. GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS does not act on this code: restart serve yourself or from your health check.' },+ pool_inflight_over_budget: { class: 'host_only', summary: "A pooled statement of this gbrain serve has run longer than its in-flight budget (the read pool's statement_timeout plus grace, or the longer statement_timeout its operation declared); `/health?deep=1` answers 503 with this code.", why: "Since #6543 the in-flight watchdog retires a statement past its budget whether or not bytes keep arriving (reason=age), so this code means the watchdog is off (GBRAIN_PG_STUCK_GRACE_MS=off), the serve runs a driver without per-statement budgets, or the retirement is still in progress; a transaction that declared a longer statement_timeout, or an index build that declared 0, is measured against its own budget and not reported. Through a transaction-mode pooler a pipelined answer can also be misrouted. The probe reports it and never retires the connection, because the endpoint is unauthenticated.", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Restart this gbrain serve. On a transaction-mode pooler check the transport block of /health?deep=1: max_pipeline should read 0 (set PGMAX_PIPELINE=0 in the serve environment to force it) and session_timeouts_not_applied names the ALTER ROLE fix. GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS does not act on this code: restart serve yourself or from your health check.' },deep_health_probe_failed: { class: 'retryable', summary: "The pooled `SELECT 1` of `/health?deep=1` did not answer: an earlier probe is still pending, it timed out, or it failed.", reasons: ['pending', 'timeout', 'error'], why: "The deep probe runs through the ordinary pooled dispatch, where handler statements wait, so a saturated or wedged pool fails it while plain /health (a reserved idle connection) may still answer 200. One deep probe runs per engine at a time.", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Retry in a few seconds; if it keeps failing, run gbrain doctor --json from a fresh process to check the database and pooler, then restart this gbrain serve.' },serve_self_exit_suppressed: { class: 'host_only', summary: "gbrain serve stayed at restart_required past GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS but did not exit, because it had already exited on its own 3 times within the hour; `/health?deep=1` reports self_exit_suppressed.", why: "The opt-in self-exit keeps a durable ledger (serve-self-exit.json under the gbrain home). A serve that reaches restart_required again right after every restart has a cause a restart does not fix, so after 3 self-exits in an hour it keeps serving reads and leaves the decision to a human instead of looping.", docs: 'docs/ENGINES.md#serve-unhealthy-exit', suggestion: 'Run gbrain sources writer status --json and gbrain doctor --json, report both with the serve log lines, then restart serve by hand.' },serve_unhealthy_exit: { class: 'unavailable', exit: 69, summary: "gbrain serve exited on its own because its persistence consumer reported restart_required continuously for GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS.", why: "Opt-in (off by default, at least 120 s): a supervisor that restarts on failure, such as the installed gbrain-serve service, then starts a fresh serve without a human. Cleanup is bounded (5 s) because the consumer's stop waits on the stuck work, so the process exits even when it cannot drain. Abandoned claims lapse with the exited process's heartbeat; journaled writes resume on the next owner.", docs: 'docs/ENGINES.md#serve-unhealthy-exit', suggestion: 'Let the supervisor restart serve; if it exits this way again soon after, run gbrain doctor --json and gbrain sources writer status --json and report both with the exit line.' },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 } },push_unconfirmed: { class: 'retryable', summary: "The commit is durable locally but no push destination confirmed it.", docs: 'docs/guides/shared-checkout-git.md#outcomes', exit: 4 },schema_lock_blocked: { class: 'retryable', summary: "A schema step (the schema.sql replay in init/upgrade, or one migration) waited its lock_timeout for a table lock another session holds and stopped instead of hanging.", why: "Every ALTER TABLE in the replay takes an ACCESS EXCLUSIVE lock even as a no-op, so one open transaction in another client (idle in transaction, a stuck job) blocked gbrain init and upgrade forever with no output. The wait is now bounded (GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS, default 60) and the refusal names the blocking sessions by pid, application and state, sampled while the wait was active; query text is never shown. The cancelled step changed nothing.", docs: 'docs/ENGINES.md#schema-lock-blocked', suggestion: 'Let the named session finish or, with the user\'s agreement, end it on the database host with SELECT pg_terminate_backend(<pid>), then rerun the same gbrain command; init retries a few times on its own with a short backoff.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the database, the pooler and the schema version so the rerun is judged against the current state.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },- 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: "Nothing arriving for that long usually means the connection 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. It is not proof: behind a transaction-mode pooler the startup statement_timeout never applies (SHOW statement_timeout reads 0), so a legitimately slow statement can reach the budget too, and the clock restarts on every byte, so a statement that keeps streaming is never retired. 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_connection_recovery_failed: { class: 'retryable', summary: "A Postgres connection the driver retired after an incident (stuck, desynced, or closed under running statements) could not reconnect; statements waiting for it failed with the connect error.", why: "The database or pooler refused or dropped the new connection (unreachable host, exhausted connection slots, rotated credentials). The next statement retries the connect, and the connection stays marked until one succeeds, so a repeating line means the pool is not recovering on its own.", docs: 'docs/ENGINES.md#pg-connection-recovery-failed', suggestion: 'Check the database and pooler from the serve host (gbrain doctor --only pool_reap_health --json); a serve that keeps logging this line needs the database reachable again, then a restart if the pool never recovers.', fix: { argv: ['gbrain', 'doctor', '--only', 'pool_reap_health', '--json'], consent: [], actor: 'agent', why: 'Read-only: counts the recent stuck, desync and recovery events serve recorded.', requires_exclusive: false } },+ pg_connection_stuck: { class: 'retryable', summary: "A pooled Postgres statement ran past its in-flight budget (the pool's statement_timeout plus grace, or the longer statement_timeout its operation declared) with nothing coming back from the server (reason=idle) or while bytes kept arriving (reason=age), so the driver retired that connection; the statement and everything queued behind it failed with CONNECTION_STUCK.", why: "Nothing arriving for that long usually means the connection 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. It is not proof: behind a transaction-mode pooler the startup statement_timeout never applies (SHOW statement_timeout reads 0), so a legitimately slow statement can reach the budget too. reason=age is a statement that kept streaming rows or notices past its budget (#6543); an operation that needs longer declares it with SET LOCAL statement_timeout (0 for no limit), which the driver tracks per statement. 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 answered in its place in the pipeline by a query the server refuses; it failed, and a transaction it was part of was aborted rather than committed without it.", why: "Either a gbrain programming error at the call site the warn line names by keyword and table (and by `param=$n`), or, behind a transaction-mode pooler (port 6543, prepare off), a value read from a row that belonged to another statement: a pooler that misroutes pipelined answers hands a statement someone else's row, and binding one of its missing columns fails here. 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 answers the culprit in its place (the approach of porsager/postgres#1236), so only it rejects and a transaction it was in aborts.", docs: 'docs/ENGINES.md#pg-statement-build-failed', suggestion: 'On a transaction-mode pooler, check /health?deep=1 transport (max_pipeline should be 0; PGMAX_PIPELINE=0 on the serve environment forces it) and treat earlier reads as suspect (docs/guides/pooler-misroute-audit.md); otherwise report the warn line (it names the statement and parameter) 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.' },diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex 91634f77fa..73f4a9341c 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -251,7 +251,12 @@ export async function runMigrationSQL(// Falling through means the DDL runs with the server default.}// #5227 (W14 P1.6): no transaction here, so the lock bound is session-level on this reserved backend and restored after.- await withSchemaLockTimeout({ unsafe: (query: string) => conn.executeRaw(query) }, () => conn.executeRaw(sql), { step: `migration v${m.version}` });+ // #6543 (A4): the raised statement_timeout is restored too, so the connection does not carry this migration's budget back to the pool.+ try {+ await withSchemaLockTimeout({ unsafe: (query: string) => conn.executeRaw(query) }, () => conn.executeRaw(sql), { step: `migration v${m.version}` });+ } finally {+ await conn.executeRaw('RESET statement_timeout').catch(() => {});+ }}, { selfContained: true });}}diff --git a/src/core/pool-gauge.ts b/src/core/pool-gauge.tsindex 87c79203d8..46104102ec 100644--- a/src/core/pool-gauge.ts+++ b/src/core/pool-gauge.ts@@ -18,6 +18,17 @@*/import { sqlLabel } from './persistence/claim-phase.ts';+import type { ConnectionRecoveryInfo, StuckConnectionInfo } from './db.ts';+import type { PoolRecoveryEventKind } from './audit/pool-recovery-audit.ts';++/** #6543 (A6): where a resident process records its pool incidents (serve: the pool-recovery audit doctor reads). */+export type PoolIncidentAudit = (kind: Extract<PoolRecoveryEventKind, `connection_${string}`>, detail: string) => void;+let incidentAudit: PoolIncidentAudit | null = null;+/** Serve turns this on at startup so `gbrain doctor --only pool_reap_health` sees its stuck, desync and recovery events. */+export function setPoolIncidentAudit(audit: PoolIncidentAudit | null): void { incidentAudit = audit; }+function audit(kind: Parameters<PoolIncidentAudit>[0], detail: string): void {+ try { incidentAudit?.(kind, detail); } catch { /* best-effort */ }+}/** Which engine seam the in-flight call went through. */export type GaugeKind = 'raw' | 'direct' | 'reserved' | 'tx';@@ -95,16 +106,29 @@ export function formatPoisonedDiscardWarning(pool: 'read' | 'direct', status: st/*** #6383: connections the vendored driver's in-flight watchdog retired because a- * statement waited `statement_timeout + grace` with nothing coming back (the- * clock restarts on every byte, so a streaming statement never trips it), 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.+ * statement waited past its budget (`statement_timeout + grace`, raised for an+ * operation that declared a longer timeout) with nothing coming back+ * (`reason=idle`) or, since #6543, ran past it while bytes kept arriving+ * (`reason=age`), and statements the driver rejected alone because they failed+ * to build. #6543 (A6): `recovered` / `recovery_failed` count reconnects of+ * connections retired by an incident. 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;private desyncs = 0;+ private recoveries = 0;+ private recoveryFailures = 0;++ get recoveredCount(): number {+ return this.recoveries;+ }++ get recoveryFailedCount(): number {+ return this.recoveryFailures;+ }get stuckCount(): number {return this.stuck;@@ -119,18 +143,36 @@ export class PoolIncidentCounter {}/** The driver hooks of one pool, bound to this counter (what an engine passes as `PoolHealthHooks`). */- hooks(pool: 'read' | 'direct'): { onstuck: (info: { age_ms: number; queued: number; statement: string }) => void; onbuilderror: (code: string, statement: string, parameter?: number) => void; ondesync: (info: { message: string; connection: number; statement: string }) => void } {- return { onstuck: (info) => this.recordStuck(pool, info), onbuilderror: (code, statement, parameter) => this.recordBuildFailure(pool, code, statement, parameter), ondesync: (info) => this.recordDesync(pool, info) };+ hooks(pool: 'read' | 'direct'): { onstuck: (info: StuckConnectionInfo) => void; onbuilderror: (code: string, statement: string, parameter?: number) => void;+ ondesync: (info: { message: string; connection: number; statement: string }) => void; onrecovered: (info: ConnectionRecoveryInfo) => void; onrecoveryfailed: (info: ConnectionRecoveryInfo) => void } {+ return { onstuck: (info) => this.recordStuck(pool, info), onbuilderror: (code, statement, parameter) => this.recordBuildFailure(pool, code, statement, parameter),+ ondesync: (info) => this.recordDesync(pool, info), onrecovered: (info) => this.recordRecovered(pool, info), onrecoveryfailed: (info) => this.recordRecoveryFailed(pool, info) };}- recordStuck(pool: 'read' | 'direct', info: { age_ms: number; queued: number; statement: string }): void {+ recordStuck(pool: 'read' | 'direct', info: StuckConnectionInfo): void {this.stuck += 1;- try { console.warn(formatStuckConnectionWarning(pool, info)); } catch { /* best-effort */ }+ const line = formatStuckConnectionWarning(pool, info);+ try { console.warn(line); } catch { /* best-effort */ }+ audit('connection_stuck', line);}recordDesync(pool: 'read' | 'direct', info: { message: string; connection: number; statement: string }): void {this.desyncs += 1;- try { console.warn(formatDesyncWarning(pool, info)); } catch { /* best-effort */ }+ const line = formatDesyncWarning(pool, info);+ try { console.warn(line); } catch { /* best-effort */ }+ audit('connection_desync', line);+ }++ recordRecovered(pool: 'read' | 'direct', info: ConnectionRecoveryInfo): void {+ this.recoveries += 1;+ audit('connection_recovered', `pool=${pool} connection=${Math.max(0, info.connection | 0)} cause=${recoveryCause(info.cause)}`);+ }++ recordRecoveryFailed(pool: 'read' | 'direct', info: ConnectionRecoveryInfo): void {+ this.recoveryFailures += 1;+ const line = formatRecoveryFailedWarning(pool, info);+ try { console.warn(line); } catch { /* best-effort */ }+ audit('connection_recovery_failed', line);}recordBuildFailure(pool: 'read' | 'direct', code: string, statement: string, parameter?: number): void {@@ -139,12 +181,27 @@ export class PoolIncidentCounter {}}-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 the pool's in-flight budget (statement_timeout plus grace) with nothing coming back from the server; the connection was retired and its queued statements failed with CONNECTION_STUCK"` ++export function formatStuckConnectionWarning(pool: 'read' | 'direct', info: StuckConnectionInfo): string {+ const reason = info.reason === 'age' ? 'age' : 'idle';+ const budget = Number.isFinite(info.budget_ms) && info.budget_ms! > 0 ? ` budget_ms=${Math.round(info.budget_ms!)}` : '';+ 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(' ', '_')} reason=${reason}${budget}` ++ (reason === 'age'+ ? ` cause="a statement kept receiving data past its in-flight budget (statement_timeout plus grace, or the longer statement_timeout its operation declared); the connection was retired and its queued statements failed with CONNECTION_STUCK"`+ : ` cause="a statement waited past its in-flight budget (statement_timeout plus grace, or the longer statement_timeout its operation declared) 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`;}+function recoveryCause(cause: string): string {+ return cause === 'stuck' || cause === 'desync' || cause === 'closed' ? cause : 'unknown';+}++export function formatRecoveryFailedWarning(pool: 'read' | 'direct', info: ConnectionRecoveryInfo): string {+ const code = /^[A-Z0-9_]+$/.test(info.code ?? '') ? info.code : 'CONNECTION_ERROR';+ return `[gbrain] warn code=pg_connection_recovery_failed pool=${pool} connection=${Math.max(0, info.connection | 0)} cause=${recoveryCause(info.cause)} error=${code}` ++ ` cause="a connection retired after an incident could not reconnect; statements waiting for it failed and the next one retries the connect"` ++ ` fix="gbrain doctor --only pool_reap_health --json" docs=docs/ENGINES.md#pg-connection-recovery-failed`;+}+export function formatDesyncWarning(pool: 'read' | 'direct', info: { message: string; connection: number; statement: string }): string {const message = /^[A-Za-z0-9]$/.test(info.message) ? info.message : '?';return `[gbrain] warn code=pg_connection_desync pool=${pool} message=${message} connection=${Math.max(0, info.connection | 0)} sql=${sqlLabel(info.statement).replaceAll(' ', '_')}` +diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex a923750632..4a93bbdc59 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -732,7 +732,7 @@ 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; stuckDiscards: number; buildFailures: number; desyncDiscards: number; pool: DriverPoolStats | null; prepare: boolean | null } | null {+ getPoolDiagnostics(): { tracked: PoolGaugeSnapshot; poolMax: number | null; poisonedDiscards: number; stuckDiscards: number; buildFailures: number; desyncDiscards: number; recovered: number; recoveryFailed: number; pool: DriverPoolStats | null; prepare: boolean | null } | null {try {const max = (this.sql as unknown as { options?: { max?: number } }).options?.max;return {@@ -741,7 +741,7 @@ export class PostgresEngine implements BrainEngine {poisonedDiscards: this.poisonedDiscards?.count ?? 0,stuckDiscards: this.poolIncidents?.stuckCount ?? 0,buildFailures: this.poolIncidents?.buildFailureCount ?? 0,- desyncDiscards: this.poolIncidents?.desyncCount ?? 0,+ desyncDiscards: this.poolIncidents?.desyncCount ?? 0, recovered: this.poolIncidents?.recoveredCount ?? 0, recoveryFailed: this.poolIncidents?.recoveryFailedCount ?? 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-stats.ts b/src/core/postgres-engine/pool-stats.tsindex 8ec6316cd7..25560243aa 100644--- a/src/core/postgres-engine/pool-stats.ts+++ b/src/core/postgres-engine/pool-stats.ts@@ -19,9 +19,15 @@ export interface DriverPoolStats {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;+ /**+ * #6543 (A4): age of the oldest statement past its own budget (the pool's, raised for an operation that declared a longer+ * statement_timeout, none for a declared 0), 0 when none is; absent when the driver predates per-statement budgets.+ */+ inflight_over_budget_ms?: 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 }+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;+ inflight_over_budget_ms?: number }/** The pool numbers of one driver instance, or null when it exposes none. */export function driverPoolStats(sql: unknown): DriverPoolStats | null {@@ -33,6 +39,7 @@ export function driverPoolStats(sql: unknown): DriverPoolStats | null {waiters: pool.queued,inflight_oldest_ms: pool.inflight_oldest_ms ?? 0,completed: pool.completed ?? 0,+ ...(typeof pool.inflight_over_budget_ms === 'number' ? { inflight_over_budget_ms: pool.inflight_over_budget_ms } : {}),};}@@ -52,11 +59,15 @@ export interface PoolHealthSnapshot extends DriverPoolStats {stuck_discards: number;build_failures: number;desync_discards: number;+ /** #6543 (A6): connections retired by an incident (stuck, desync, closed under statements) that reconnected, and reconnects that failed. */+ recovered: number;+ recovery_failed: number;}export function poolHealthSnapshot(engine: unknown): PoolHealthSnapshot | null {try {- const diagnostics = (engine as { getPoolDiagnostics?: () => { pool?: DriverPoolStats | null; poisonedDiscards?: number; stuckDiscards?: number; buildFailures?: number; desyncDiscards?: number } | null } | null)?.getPoolDiagnostics?.();+ const diagnostics = (engine as { getPoolDiagnostics?: () => { pool?: DriverPoolStats | null; poisonedDiscards?: number; stuckDiscards?: number; buildFailures?: number; desyncDiscards?: number;+ recovered?: number; recoveryFailed?: number } | null } | null)?.getPoolDiagnostics?.();if (!diagnostics?.pool) return null;return {...diagnostics.pool,@@ -64,6 +75,8 @@ export function poolHealthSnapshot(engine: unknown): PoolHealthSnapshot | null {stuck_discards: diagnostics.stuckDiscards ?? 0,build_failures: diagnostics.buildFailures ?? 0,desync_discards: diagnostics.desyncDiscards ?? 0,+ recovered: diagnostics.recovered ?? 0,+ recovery_failed: diagnostics.recoveryFailed ?? 0,};} catch {return null;diff --git a/test/e2e/inflight-budget-raisers-6543-postgres.test.ts b/test/e2e/inflight-budget-raisers-6543-postgres.test.tsnew file mode 100644index 0000000000..d95779fdbc--- /dev/null+++ b/test/e2e/inflight-budget-raisers-6543-postgres.test.ts@@ -0,0 +1,75 @@+/**+ * #6543 (A4): the real gbrain paths that lift or raise a statement timeout keep+ * running past the pool's in-flight budget on the ordinary pool, because the+ * driver budgets each statement from the timeout its operation declared:+ * the deferred ANN build (`SET statement_timeout = 0` on a reserved connection+ * for CREATE INDEX CONCURRENTLY) and both migration paths (SET LOCAL in a+ * transaction; a session SET on a reserved connection for transaction:false).+ * The pool budget here is 1 s (statement_timeout 500 ms + grace 500 ms).+ * Regression that fails it on master: each statement is retired with+ * CONNECTION_STUCK after 1 s of silence.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { buildDeferredAnnIndexes } from '../../src/core/embedding-ann-build.ts';+import { runMigrationSQL, type Migration } from '../../src/core/migrate.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';++const url = process.env.DATABASE_URL;+let engine: PostgresEngine;+let warn: { mock: { calls: unknown[][] }; mockRestore: () => void };+const previous = { grace: process.env.GBRAIN_PG_STUCK_GRACE_MS, timeout: process.env.GBRAIN_STATEMENT_TIMEOUT };+const stuckLines = () => warn.mock.calls.map(c => String(c[0])).filter(l => l.includes('pg_connection_stuck'));++describe.skipIf(!url)('#6543 A4: timeout raisers on the ordinary pool', () => {+ beforeAll(async () => {+ assertSafeE2eDatabaseUrl(url!);+ process.env.GBRAIN_STATEMENT_TIMEOUT = '500ms';+ process.env.GBRAIN_PG_STUCK_GRACE_MS = '500';+ warn = spyOn(console, 'warn').mockImplementation(() => {});+ engine = new PostgresEngine();+ await engine.connect({ engine: 'postgres', database_url: url!, poolSize: 3 });+ await engine.executeRaw('DROP TABLE IF EXISTS inflight_6543_t');+ await engine.executeRaw('CREATE TABLE inflight_6543_t (x int)');+ await engine.executeRaw('INSERT INTO inflight_6543_t SELECT g FROM generate_series(1, 8) g');+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION slow_6543(int) RETURNS int LANGUAGE plpgsql IMMUTABLE AS $$ BEGIN PERFORM pg_sleep(0.3); RETURN $1; END $$`);+ }, 30_000);++ afterAll(async () => {+ try {+ await engine?.executeRaw('DROP TABLE IF EXISTS inflight_6543_t').catch(() => {});+ await engine?.executeRaw('DROP FUNCTION IF EXISTS slow_6543(int)').catch(() => {});+ await engine?.disconnect();+ } finally {+ warn?.mockRestore();+ 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;+ }+ });++ test('the deferred ANN build (CREATE INDEX CONCURRENTLY after SET statement_timeout = 0) runs past the budget unretired', async () => {+ let pending = [{ name: 'idx_inflight_6543', def: 'CREATE INDEX idx_inflight_6543 ON inflight_6543_t (slow_6543(x))' }];+ const started = Date.now();+ const result = await buildDeferredAnnIndexes(engine, { targetDims: 768, readPending: async () => pending, writePending: async next => { pending = next; }, log: () => {}, monitorIntervalMs: 200 });+ expect(Date.now() - started).toBeGreaterThan(1500);+ expect(result.built).toEqual(['idx_inflight_6543']);+ expect(pending).toEqual([]);+ expect(engine.getPoolDiagnostics()?.stuckDiscards).toBe(0);+ expect(stuckLines()).toEqual([]);+ }, 30_000);++ test('a migration in a transaction (SET LOCAL statement_timeout) runs past the budget unretired', async () => {+ const m = { version: 996543, name: 'inflight_6543_tx', sql: '' } as unknown as Migration;+ await runMigrationSQL(engine, m, 'SELECT pg_sleep(1.6)');+ expect(engine.getPoolDiagnostics()?.stuckDiscards).toBe(0);+ expect(stuckLines()).toEqual([]);+ }, 30_000);++ test('a transaction:false migration (session SET on a reserved connection) runs past the budget unretired', async () => {+ const m = { version: 996544, name: 'inflight_6543_notx', sql: '', transaction: false } as unknown as Migration;+ await runMigrationSQL(engine, m, 'SELECT pg_sleep(1.6)');+ expect(engine.getPoolDiagnostics()?.stuckDiscards).toBe(0);+ expect(stuckLines()).toEqual([]);+ expect(await engine.executeRaw<{ x: number }>('SELECT 1 AS x')).toEqual([{ x: 1 }]);+ }, 30_000);+});diff --git a/test/e2e/postgres-stuck-connection-postgres.test.ts b/test/e2e/postgres-stuck-connection-postgres.test.tsindex eabbf5e02a..91af01dbcf 100644--- a/test/e2e/postgres-stuck-connection-postgres.test.ts+++ b/test/e2e/postgres-stuck-connection-postgres.test.ts@@ -16,10 +16,20 @@* 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`.+ *+ * #6543 (A4): a second clock that received bytes never restart retires a+ * statement that keeps streaming past its budget (`reason: 'age'`), and the+ * budget is per statement: a transaction that declared a longer+ * statement_timeout, or a reserved connection that declared 0, keeps running.+ * (A6): reconnects of connections retired by an incident are reported through+ * `onrecovered` / `onrecoveryfailed`. Regression that fails it on master: the+ * trickle runs to completion, and no recovery hook fires.*/import { afterEach, describe, expect, spyOn, test } from 'bun:test';+import { createServer, connect as tcpConnect, type Server, type Socket } from 'node:net';import postgres from '#postgres';import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { poolHealthSnapshot } from '../../src/core/postgres-engine/pool-stats.ts';import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';const url = process.env.DATABASE_URL;@@ -38,9 +48,9 @@ function settle(query: PromiseLike<unknown>, ms = 5000): Promise<Settled> {]);}-function pool(max: number, inflightTimeout: number | null, stucks: unknown[]) {+function pool(max: number, inflightTimeout: number | null, stucks: unknown[], extra: Record<string, unknown> = {}, target = url!) {assertSafeE2eDatabaseUrl(url!);- const sql = postgres(url!, {+ const sql = postgres(target, {max,prepare: false,onnotice: () => {},@@ -48,11 +58,33 @@ function pool(max: number, inflightTimeout: number | null, stucks: unknown[]) {connection: { application_name: `gbrain-6383-stuck-${Math.random().toString(36).slice(2)}` },inflight_timeout: inflightTimeout,onstuck: (info: unknown) => { stucks.push(info); },+ ...extra,} as Parameters<typeof postgres>[1]);opened.push(sql);return sql;}+/** One 9 KB row (larger than the server's send buffer, so each is flushed) every `everyS` seconds. */+const trickle = (rows: number, everyS: number) => `SELECT g, repeat('x', 9000) AS pad, pg_sleep(${everyS}) FROM generate_series(1, ${rows}) g`;++/** A TCP relay to the test database that can stop accepting, so a reconnect is refused. */+function relay(): Promise<{ url: string; stop: () => void; server: Server }> {+ const target = new URL(url!);+ const sockets = new Set<Socket>();+ const server = createServer(client => {+ const upstream = tcpConnect(Number(target.port || 5432), target.hostname);+ for (const s of [client, upstream]) { sockets.add(s); s.on('error', () => {}); s.on('close', () => sockets.delete(s)); }+ client.pipe(upstream).pipe(client);+ });+ return new Promise(resolve => server.listen(0, '127.0.0.1', () => {+ const port = (server.address() as { port: number }).port;+ const relayed = new URL(url!);+ relayed.hostname = '127.0.0.1';+ relayed.port = String(port);+ resolve({ url: relayed.toString(), server, stop: () => { server.close(); for (const s of sockets) s.destroy(); } });+ }));+}+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, []);@@ -112,11 +144,107 @@ describe.skipIf(!url)('#6383 in-flight watchdog and live pool numbers', () => {expect(stucks).toEqual([]);});+ test('#6543 A4: a statement that keeps streaming past its budget is retired with reason age, and the pool serves the next caller', async () => {+ const stucks: Array<{ age_ms: number; queued: number; statement: string; reason: string; budget_ms: number }> = [];+ // Idle budget 1 s (a row arrives every 0.4 s, so it never fires), age budget 2 s.+ const sql = pool(1, 1, stucks, { inflight_max: 2 });+ await sql`SELECT 1`;+ const started = Date.now();+ expect(await settle(sql.unsafe(trickle(15, 0.4)), 8000)).toEqual({ code: 'CONNECTION_STUCK' });+ expect(Date.now() - started).toBeLessThan(4000);+ expect(stucks).toHaveLength(1);+ expect(stucks[0]).toMatchObject({ reason: 'age', budget_ms: 2000, queued: 0 });+ expect(stucks[0].age_ms).toBeGreaterThanOrEqual(1900);+ expect(await settle(sql`SELECT 'next' AS who`)).toEqual({ rows: [{ who: 'next' }] });+ });++ test('#6543 A4: a transaction that declared a longer statement_timeout streams past the pool budget unretired, and deep health does not call it over budget; its SET LOCAL ends with it', async () => {+ const stucks: unknown[] = [];+ const sql = pool(1, 1, stucks, { inflight_max: 2, inflight_grace: 1 });+ await sql`SELECT 1`;+ let midway: { inflight_oldest_ms: number; inflight_over_budget_ms: number } | null = null;+ const probe = setTimeout(() => { midway = sql.pool as never; }, 2600);+ const rows = await settle(sql.begin(async tx => {+ await tx`SET LOCAL statement_timeout = '600s'`;+ return tx.unsafe(trickle(8, 0.4));+ }), 8000);+ clearTimeout(probe);+ expect('rows' in rows && rows.rows.length).toBe(8);+ expect(stucks).toEqual([]);+ expect(midway!.inflight_oldest_ms).toBeGreaterThan(2000);+ expect(midway!.inflight_over_budget_ms).toBe(0);+ expect(await settle(sql.unsafe(trickle(15, 0.4)), 8000)).toEqual({ code: 'CONNECTION_STUCK' });+ expect(stucks).toHaveLength(1);+ });++ test('#6543 A4: a reserved connection that declared statement_timeout 0 is never retired until it resets the timeout', async () => {+ const stucks: unknown[] = [];+ const sql = pool(1, 1, stucks, { inflight_max: 1, inflight_grace: 1 });+ const reserved = await sql.reserve();+ await reserved`SET statement_timeout = 0`;+ expect(await settle(reserved`SELECT pg_sleep(1.6), 1 AS x`)).toEqual({ rows: [{ pg_sleep: '', x: 1 }] });+ await reserved`RESET statement_timeout`;+ expect(await settle(reserved`SELECT pg_sleep(5)`)).toEqual({ code: 'CONNECTION_STUCK' });+ reserved.release();+ expect(stucks).toHaveLength(1);+ });++ test('#6543 A6: a connection closed under a statement reports onrecovered on its next startup, and a refused reconnect reports onrecoveryfailed', async () => {+ const proxy = await relay();+ const recovered: unknown[] = [];+ const failed: Array<{ cause: string; code: string }> = [];+ const sql = pool(1, null, [], { onrecovered: (i: unknown) => recovered.push(i), onrecoveryfailed: (i: { cause: string; code: string }) => failed.push(i), backoff: 0 }, proxy.url);+ await sql`SELECT 1`;+ const running = settle(sql`SELECT pg_sleep(5)`);+ await new Promise(r => setTimeout(r, 200));+ proxy.stop();+ expect(await running).toEqual({ code: 'CONNECTION_CLOSED' });+ expect(await settle(sql`SELECT 1`)).toEqual({ code: 'ECONNREFUSED' });+ expect(failed).toHaveLength(1);+ expect(failed[0]).toMatchObject({ cause: 'closed', code: 'ECONNREFUSED' });+ expect(recovered).toEqual([]);+ await new Promise<void>(resolve => proxy.server.listen(Number(new URL(proxy.url).port), '127.0.0.1', () => resolve()));+ expect(await settle(sql`SELECT 'back' AS who`)).toEqual({ rows: [{ who: 'back' }] });+ expect(recovered).toEqual([{ connection: expect.any(Number), cause: 'closed' }]);+ expect(failed).toHaveLength(1);+ proxy.stop();+ });++ test('#6543 A6 engine: pg_terminate_backend under a statement counts recovered once, in getPoolDiagnostics and the deep-health snapshot', async () => {+ assertSafeE2eDatabaseUrl(url!);+ const engine = new PostgresEngine();+ const admin = pool(1, null, []);+ try {+ await engine.connect({ engine: 'postgres', database_url: url!, poolSize: 2 });+ const marker = `pg_sleep(4.${Math.floor(Math.random() * 900) + 100})`;+ const sleeping = settle(engine.executeRaw(`SELECT ${marker}`), 6000);+ let pids: Array<{ pid: number }> = [];+ for (let i = 0; i < 20 && pids.length === 0; i++) {+ await new Promise(r => setTimeout(r, 100));+ pids = await admin.unsafe<Array<{ pid: number }>>(`SELECT pid FROM pg_stat_activity WHERE query = 'SELECT ${marker}' AND pid <> pg_backend_pid()`);+ }+ expect(pids).toHaveLength(1);+ await admin`SELECT pg_terminate_backend(${pids[0]!.pid})`;+ expect('code' in (await sleeping)).toBe(true);+ expect(engine.getPoolDiagnostics()?.recovered).toBe(0);+ // Two statements at once need both connections, so the terminated one reconnects.+ expect(await Promise.all([engine.executeRaw<{ x: number; pg_sleep: string }>('SELECT 1 AS x, pg_sleep(0.3)'), engine.executeRaw<{ x: number; pg_sleep: string }>('SELECT 1 AS x, pg_sleep(0.3)')]))+ .toEqual([[{ x: 1, pg_sleep: '' }], [{ x: 1, pg_sleep: '' }]]);+ expect(engine.getPoolDiagnostics()?.recovered).toBe(1);+ expect(engine.getPoolDiagnostics()?.recoveryFailed).toBe(0);+ expect(poolHealthSnapshot(engine)).toMatchObject({ recovered: 1, recovery_failed: 0 });+ } finally {+ await engine.disconnect();+ }+ });+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.+ // statement_timeout first, so the sleep is only ever ended by the watchdog. It lifts it inside a DO body, which+ // the driver does not read (as a pooler that never applies the timeout would leave it): since #6543 a lift the+ // driver reads (`SET statement_timeout = 0`) also lifts the watchdog for that connection.process.env.GBRAIN_STATEMENT_TIMEOUT = '500ms';process.env.GBRAIN_PG_STUCK_GRACE_MS = '500';const engine = new PostgresEngine();@@ -124,7 +252,7 @@ describe.skipIf(!url)('#6383 in-flight watchdog and live pool numbers', () => {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("DO $$ BEGIN PERFORM set_config('statement_timeout', '0', false); END $$");await conn.executeRaw('SELECT pg_sleep(5)');}), 6000);expect(stuck).toEqual({ code: 'CONNECTION_STUCK' });@@ -137,6 +265,7 @@ describe.skipIf(!url)('#6383 in-flight watchdog and live pool numbers', () => {expect(lines).toHaveLength(1);expect(lines[0]).toContain('pool=read');expect(lines[0]).toContain('sql=SELECT');+ expect(lines[0]).toContain('reason=idle budget_ms=1000');expect(lines[0]).not.toContain('pg_sleep');expect(lines[0]).not.toContain(url!);} finally {diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex f336d4ccc1..a89154b3ca 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -1090,7 +1090,7 @@"getOntology: (entitySlug: string, opts?: OntologyReadOpts) => Promise<OntologyValue[]>","getPage: (slug: string, opts?: PageSnapshotOptions) => Promise<Page | null>","getPageTimestamps: (slugs: string[]) => Promise<Map<string, Date>>",- "getPoolDiagnostics: () => { tracked: PoolGaugeSnapshot; poolMax: number | null; poisonedDiscards: number; stuckDiscards: number; buildFailures: number; desyncDiscards: number; pool: DriverPoolStats | null; prepare: boolean | null; } | null",+ "getPoolDiagnostics: () => { tracked: PoolGaugeSnapshot; poolMax: number | null; poisonedDiscards: number; stuckDiscards: number; buildFailures: number; desyncDiscards: number; recovered: number; recoveryFailed: number; pool: DriverPoolStats | null; prepare: boolean | null; } | null","getRawData: (slug: string, source?: string, opts?: PageReadScope & { includeDeleted?: boolean; }) => Promise<RawData[]>","getRecentSalience: (opts: SalienceOpts) => Promise<SalienceResult[]>","getSalienceScores: (refs: Array<{ slug: string; source_id: string; }>, opts?: PageReadPolicy) => Promise<Map<string, number>>",@@ -6123,7 +6123,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/pool-health-6383.test.ts b/test/pool-health-6383.test.tsindex b03d2b0261..d0cf7aa3c2 100644--- a/test/pool-health-6383.test.ts+++ b/test/pool-health-6383.test.ts@@ -139,7 +139,7 @@ function fakeEngine(state: { busy: number; queued: number; completed: number; oldescribe('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, desync_discards: 4 });+ 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, desync_discards: 4, recovered: 0, recovery_failed: 0 });expect(poolHealthSnapshot({ kind: 'pglite' })).toBeNull();expect(poolHealthSnapshot({ getPoolDiagnostics: () => { throw new Error('closed'); } })).toBeNull();});@@ -169,7 +169,7 @@ describe('PoolStallWatch', () => {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, desync_discards: 4 }, 60_000));+ 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, desync_discards: 4, recovered: 0, recovery_failed: 0 }, 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));diff --git a/test/pool-incidents-6543.test.ts b/test/pool-incidents-6543.test.tsnew file mode 100644index 0000000000..c2afecc7a1--- /dev/null+++ b/test/pool-incidents-6543.test.ts@@ -0,0 +1,112 @@+/**+ * #6543 (A4, A6): the stuck warn line names why the watchdog fired+ * (`reason=age|idle`) and the statement's own budget; reconnects of retired+ * connections are counted (`recovered`, `recovery_failed`) and reach+ * `poolHealthSnapshot`; serve's incidents land in the pool-recovery audit, so+ * `doctor --only pool_reap_health` sees them.+ * Regression that fails it on master: no `reason=`, no recovery counters, no+ * audit sink, and the doctor check ignores driver incidents.+ */+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { formatRecoveryFailedWarning, formatStuckConnectionWarning, PoolIncidentCounter, setPoolIncidentAudit } from '../src/core/pool-gauge.ts';+import { logPoolRecovery, readRecentPoolRecoveries } from '../src/core/audit/pool-recovery-audit.ts';+import { computePoolReapHealthCheck } from '../src/commands/doctor.ts';+import { driverPoolStats, poolHealthSnapshot } from '../src/core/postgres-engine/pool-stats.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { withEnv } from './helpers/with-env.ts';++// eslint-disable-next-line @typescript-eslint/no-explicit-any+const pg = { kind: 'postgres' } as any;+let tmpDir: string;+beforeEach(() => { tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pool-incidents-6543-')); });+afterEach(() => {+ setPoolIncidentAudit(null);+ try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* best-effort */ }+});++describe('warn lines', () => {+ test('pg_connection_stuck says reason=age with the statement budget when bytes kept arriving, reason=idle otherwise', () => {+ const age = formatStuckConnectionWarning('read', { age_ms: 8_012.4, queued: 0, statement: "SELECT g, repeat('x', 9000) FROM generate_series(1, 8) g", reason: 'age', budget_ms: 3000 });+ expect(age).toContain('[gbrain] warn code=pg_connection_stuck pool=read age_ms=8012 queued=0 sql=SELECT_generate_series reason=age budget_ms=3000');+ expect(age).toContain('kept receiving data past its in-flight budget');+ expect(age).not.toContain('repeat(');+ const idle = formatStuckConnectionWarning('direct', { age_ms: 5000, queued: 1, statement: 'SELECT pg_sleep(5)', reason: 'idle', budget_ms: 4000 });+ expect(idle).toContain('reason=idle budget_ms=4000');+ expect(idle).toContain('with nothing coming back from the server');+ expect(formatStuckConnectionWarning('read', { age_ms: 1, queued: 0, statement: 'SELECT 1' })).toContain('reason=idle cause=');+ });++ test('pg_connection_recovery_failed names the pool, connection, cause and a safe error code only', () => {+ const line = formatRecoveryFailedWarning('read', { connection: 3, cause: 'stuck', code: 'ECONNREFUSED' });+ expect(line).toContain('[gbrain] warn code=pg_connection_recovery_failed pool=read connection=3 cause=stuck error=ECONNREFUSED');+ expect(line).toContain('docs=docs/ENGINES.md#pg-connection-recovery-failed');+ expect(formatRecoveryFailedWarning('direct', { connection: 1, cause: 'closed', code: 'password for postgres://u:p@h' })).toContain('error=CONNECTION_ERROR');+ });+});++describe('PoolIncidentCounter recovery counters and the audit sink', () => {+ test('driver hooks count recovered and recovery_failed; serve writes stuck, desync and recovery events to the audit', async () => {+ await withEnv({ GBRAIN_AUDIT_DIR: tmpDir }, async () => {+ const warn = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ setPoolIncidentAudit((kind, detail) => logPoolRecovery(kind, undefined, detail));+ const counter = new PoolIncidentCounter();+ const hooks = counter.hooks('read');+ hooks.onstuck({ age_ms: 4000, queued: 0, statement: 'SELECT * FROM pages', reason: 'age', budget_ms: 3000 });+ hooks.ondesync({ message: 'DataRow', connection: 2, statement: 'SELECT 1' });+ hooks.onrecovered({ connection: 1, cause: 'stuck' });+ hooks.onrecovered({ connection: 2, cause: 'desync' });+ expect(counter.stuckCount).toBe(1);+ expect(counter.desyncCount).toBe(1);+ expect(counter.recoveredCount).toBe(2);+ expect(counter.recoveryFailedCount).toBe(0);+ const recent = readRecentPoolRecoveries(1);+ expect(recent.stuck).toBe(1);+ expect(recent.desyncs).toBe(1);+ expect(recent.connection_recoveries).toBe(2);+ expect(recent.events.find(e => e.kind === 'connection_stuck')?.detail).toContain('reason=age');+ const warnCheck = await computePoolReapHealthCheck(pg);+ expect(warnCheck?.status).toBe('warn');+ expect(warnCheck?.message).toContain('retired 1 stuck and 1 desynced');+ expect(warnCheck?.details?.connection_recoveries).toBe(2);++ hooks.onrecoveryfailed({ connection: 1, cause: 'closed', code: 'ECONNREFUSED' });+ expect(counter.recoveryFailedCount).toBe(1);+ expect(warn.mock.calls.map(c => String(c[0])).filter(l => l.includes('pg_connection_recovery_failed'))).toHaveLength(1);+ const failCheck = await computePoolReapHealthCheck(pg);+ expect(failCheck?.status).toBe('fail');+ expect(failCheck?.message).toContain('could not reconnect a retired connection 1×');+ } finally {+ warn.mockRestore();+ }+ });+ });++ test('without a sink (CLI processes) nothing is written to the audit', async () => {+ await withEnv({ GBRAIN_AUDIT_DIR: tmpDir }, async () => {+ const warn = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ new PoolIncidentCounter().hooks('direct').onstuck({ age_ms: 4000, queued: 0, statement: 'SELECT 1', reason: 'idle', budget_ms: 3000 });+ expect(readRecentPoolRecoveries(1).events).toEqual([]);+ expect(await computePoolReapHealthCheck(pg)).toBeNull();+ } finally {+ warn.mockRestore();+ }+ });+ });+});++describe('poolHealthSnapshot', () => {+ test('carries recovered, recovery_failed and the driver per-statement over-budget age', () => {+ const engine = {+ getPoolDiagnostics: () => ({+ poisonedDiscards: 0, stuckDiscards: 1, buildFailures: 0, desyncDiscards: 0, recovered: 1, recoveryFailed: 2,+ pool: driverPoolStats({ pool: { max: 4, open: 4, busy: 1, full: 0, reserved: 0, connecting: 0, closed: 0, ended: 0, queued: 0, inflight_oldest_ms: 900_000, completed: 3, inflight_over_budget_ms: 0 } }),+ }),+ } as unknown as BrainEngine;+ expect(poolHealthSnapshot(engine)).toMatchObject({ inflight_oldest_ms: 900_000, inflight_over_budget_ms: 0, stuck_discards: 1, recovered: 1, recovery_failed: 2 });+ });+});diff --git a/test/postgres-driver-vendor.test.ts b/test/postgres-driver-vendor.test.tsindex 55934c8f14..550e3bf8ad 100644--- a/test/postgres-driver-vendor.test.ts+++ b/test/postgres-driver-vendor.test.ts@@ -61,4 +61,30 @@ describe('vendored Postgres driver packaging', () => {}expect(readFileSync(new URL('../vendor/postgres/types/index.d.ts', import.meta.url), 'utf8')).toContain('parameter?: number');});++ test('#6543: all three shipped copies carry the A4 per-statement age cap and the A6 recovery hooks (offline)', () => {+ for (const path of ['src', 'cjs/src', 'cf/src']) {+ const connection = readFileSync(new URL(`../vendor/postgres/${path}/connection.js`, import.meta.url), 'utf8');+ // A4: a second clock received bytes never restart, budgets derived per statement from its declared statement_timeout.+ expect(connection).toContain("ageTimer = budgetTimer('age')");+ expect(connection).toContain('query && (received += x.length, inflightTimer.start())');+ expect(connection).toMatch(/mayPipeline = mayPipeline \|\| q\.options\.onexecute\(connection\)\n\s+noteBudget\(q\)/);+ expect(connection).toContain("const reason = kind === 'age' && received > 0 ? 'age' : 'idle'");+ expect(connection).toContain('function statementTimeoutChanges(text, parameters)');+ expect(connection).toContain('x[5] === 73 && !sent.length && (localBudget = undefined)');+ // A6: an incident marks the connection; the next completed startup reports recovered, a failed one recovery_failed.+ expect(connection).toContain("recovering = recovering || 'stuck'");+ expect(connection).toContain("recovering = recovering || 'desync'");+ expect(connection).toContain("(query || sent.length) && (recovering = recovering || 'closed')");+ expect(connection).toContain('options.onrecovered && options.onrecovered({ connection: id, cause })');+ expect(connection).toContain('initial && recovering && recoveryFailed(err)');+ const index = readFileSync(new URL(`../vendor/postgres/${path}/index.js`, import.meta.url), 'utf8');+ expect(index).toContain("'inflight_timeout', 'inflight_max', 'inflight_grace'");+ expect(index).toContain('inflight_over_budget_ms:');+ expect(index).toContain('onrecoveryfailed: o.onrecoveryfailed,');+ }+ const types = readFileSync(new URL('../vendor/postgres/types/index.d.ts', import.meta.url), 'utf8');+ expect(types).toContain('inflight_max: number | null;');+ expect(types).toContain("reason: 'age' | 'idle'; budget_ms: number");+ });});diff --git a/test/postgres-inflight-budget-6543.test.ts b/test/postgres-inflight-budget-6543.test.tsnew file mode 100644index 0000000000..01be4068c6--- /dev/null+++ b/test/postgres-inflight-budget-6543.test.ts@@ -0,0 +1,136 @@+/**+ * #6543 (A4): the in-flight budget is derived per statement from the+ * statement_timeout its operation declared on the connection, read by the+ * vendored driver from the statements it sends (so it holds behind a+ * transaction-mode pooler that never applies a session SET).+ *+ * The guard below fails CI when gbrain code raises (or lifts) a statement+ * timeout in a form the driver cannot read: that statement would keep the+ * pool's budget and be retired as stuck while its own timeout still runs.+ * Regression that fails it on master: `Connection.statementTimeoutChanges`+ * does not exist, and `poolHealthOptions` sets no age cap.+ */+import { describe, expect, test } from 'bun:test';+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';+import { poolHealthOptions } from '../src/core/db.ts';+import { withEnv } from './helpers/with-env.ts';++type Change = { kind: 'set'; local: boolean; ms: number | undefined } | { kind: 'reset' | 'end' | 'unknown' };+const { default: Connection } = await import(new URL('../vendor/postgres/src/connection.js', import.meta.url).href) as { default: { statementTimeoutChanges: (text: string, parameters?: unknown[]) => Change[] } };+const changes = Connection.statementTimeoutChanges;++describe('statementTimeoutChanges: what one statement does to the connection statement_timeout', () => {+ test('SET [LOCAL|SESSION] statement_timeout with units, quotes, TO and DEFAULT', () => {+ expect(changes("SET LOCAL statement_timeout = '600s'")).toEqual([{ kind: 'set', local: true, ms: 600_000 }]);+ expect(changes('SET statement_timeout = 0')).toEqual([{ kind: 'set', local: false, ms: 0 }]);+ expect(changes("SET SESSION statement_timeout TO '2min'")).toEqual([{ kind: 'set', local: false, ms: 120_000 }]);+ expect(changes("set local statement_timeout='10s'")).toEqual([{ kind: 'set', local: true, ms: 10_000 }]);+ expect(changes('SET LOCAL statement_timeout = 60000')).toEqual([{ kind: 'set', local: true, ms: 60_000 }]);+ expect(changes('SET statement_timeout TO DEFAULT')).toEqual([{ kind: 'set', local: false, ms: undefined }]);+ expect(changes("SET LOCAL statement_timeout = 'soon'")).toEqual([{ kind: 'unknown' }]);+ });++ test('set_config with literal or bound values, local or session', () => {+ expect(changes("SELECT set_config('statement_timeout', $1, true)", ['8s'])).toEqual([{ kind: 'set', local: true, ms: 8_000 }]);+ expect(changes("SELECT set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)")).toEqual([{ kind: 'set', local: true, ms: 5_000 }]);+ expect(changes("SELECT set_config('statement_timeout', '0', false)")).toEqual([{ kind: 'set', local: false, ms: 0 }]);+ expect(changes("SELECT set_config('statement_timeout', $1, true)", [])).toEqual([{ kind: 'unknown' }]);+ });++ test('transaction boundaries, RESET and DISCARD; dollar-quoted bodies are not boundaries', () => {+ expect(changes("BEGIN; SET LOCAL statement_timeout = 250")).toEqual([{ kind: 'end' }, { kind: 'set', local: true, ms: 250 }]);+ expect(changes('commit')).toEqual([{ kind: 'end' }]);+ expect(changes('ROLLBACK')).toEqual([{ kind: 'end' }]);+ expect(changes('ROLLBACK TO SAVEPOINT s1')).toEqual([]);+ expect(changes('RESET statement_timeout')).toEqual([{ kind: 'reset' }]);+ expect(changes('RESET ALL')).toEqual([{ kind: 'reset' }]);+ expect(changes('DISCARD ALL')).toEqual([{ kind: 'reset' }]);+ expect(changes("DO $$ BEGIN PERFORM set_config('statement_timeout','0',false); END $$")).toEqual([]);+ expect(changes("SELECT CASE WHEN true THEN 1 END FROM pages")).toEqual([]);+ });+});++describe('poolHealthOptions: one budget caps both silence and total age', () => {+ test('inflight_max equals inflight_timeout, inflight_grace is the grace in seconds, and grace off disables both', () => {+ withEnv({ GBRAIN_PG_STUCK_GRACE_MS: '2000' }, () => {+ const options = poolHealthOptions(undefined, '3000');+ expect(options.inflight_timeout).toBe(5);+ expect(options.inflight_max).toBe(5);+ expect(options.inflight_grace).toBe(2);+ });+ withEnv({ GBRAIN_PG_STUCK_GRACE_MS: 'off' }, () => {+ const options = poolHealthOptions(undefined, '3000');+ expect(options.inflight_timeout).toBeNull();+ expect(options.inflight_max).toBeNull();+ expect(options.inflight_grace).toBeNull();+ });+ });+});++const ROOT = join(import.meta.dir, '..', 'src');+const RAISER = /set_config\s*\(\s*'statement_timeout'|\bSET\s+(?:LOCAL\s+|SESSION\s+)?statement_timeout\b/i;++function sourceFiles(dir: string): string[] {+ return readdirSync(dir).flatMap(name => {+ const path = join(dir, name);+ return statSync(path).isDirectory() ? sourceFiles(path) : path.endsWith('.ts') ? [path] : [];+ });+}++/** The SQL string literal on `line` that holds the statement_timeout change, with interpolations as numbers. */+function sqlLiteral(line: string): string {+ const at = line.search(RAISER);+ const before = line.slice(0, at);+ const open = Math.max(before.lastIndexOf('`'), before.lastIndexOf('"'));+ let literal: string;+ if (open >= 0) {+ const end = line.indexOf(line[open]!, at);+ literal = line.slice(open + 1, end > 0 ? end : undefined);+ } else if (line.indexOf('`', at) > 0) {+ literal = line.slice(0, line.indexOf('`', at));+ } else {+ const end = line.indexOf("'", at);+ literal = line.slice(before.lastIndexOf("'") + 1, end > 0 ? end : undefined);+ }+ return literal.replace(/\$\{[^}]*\}/g, '1000');+}++/** A literal that reads as SQL (prose that names the setting, such as an error message, is not a change). */+const isSql = (literal: string) => /^\s*(SET|SELECT|BEGIN|START|WITH|set_config)\b/i.test(literal);++/** Why the driver cannot read this statement_timeout change, or null when it can. */+function unreadable(literal: string): string | null {+ const found = changes(literal, Array.from({ length: 9 }, () => '1000'));+ if (!found.some(c => c.kind === 'set')) return 'no statement_timeout change the driver can read';+ if (found.some(c => c.kind === 'unknown')) return 'a statement_timeout value the driver cannot read';+ return null;+}++describe('guard: every statement_timeout change in gbrain reaches the driver budget', () => {+ test('the guard itself flags a change the driver cannot read', () => {+ expect(unreadable(sqlLiteral(`await tx.executeRaw("SELECT set_config('statement_timeout', current_setting('app.t'), true)");`))).not.toBeNull();+ expect(unreadable(sqlLiteral(`await tx.executeRaw("SET LOCAL statement_timeout = 'later'");`))).not.toBeNull();+ expect(unreadable(sqlLiteral("await conn.executeRaw(`SET LOCAL statement_timeout = '${perBatchTimeoutSec}s'`);"))).toBeNull();+ });++ test('no src/ path raises or lifts statement_timeout in a form the per-statement budget misses', () => {+ const offenders: string[] = [];+ let seen = 0;+ for (const file of sourceFiles(ROOT)) {+ const lines = readFileSync(file, 'utf8').split('\n');+ lines.forEach((line, i) => {+ const trimmed = line.trim();+ if (!RAISER.test(line) || /^(\/\/|\*|\/\*)/.test(trimmed)) return;+ if (/\bALTER\s+(ROLE|DATABASE|SYSTEM)\b/i.test(line)) return;+ const literal = sqlLiteral(line);+ if (!isSql(literal)) return;+ seen += 1;+ const why = unreadable(literal);+ if (why) offenders.push(`${relative(join(ROOT, '..'), file)}:${i + 1}: ${why}: ${trimmed}`);+ });+ }+ expect(seen).toBeGreaterThan(20);+ expect(offenders).toEqual([]);+ });+});diff --git a/test/serve-health-6543.test.ts b/test/serve-health-6543.test.tsindex 5c8f4d70a2..4c5ae671ba 100644--- a/test/serve-health-6543.test.ts+++ b/test/serve-health-6543.test.ts@@ -36,7 +36,7 @@ import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, timport { withEnv } from './helpers/with-env.ts';import { waitFor } from './helpers/wait-for.ts';-interface FakeState { oldest?: number; applied?: string; appName?: string; prepare?: boolean; maxPipeline?: number; url?: string; executeRaw?: () => Promise<unknown>; disconnect?: () => Promise<void> }+interface FakeState { oldest?: number; overBudget?: number; applied?: string; appName?: string; prepare?: boolean; maxPipeline?: number; url?: string; executeRaw?: () => Promise<unknown>; disconnect?: () => Promise<void> }function fakeEngine(state: FakeState = {}) {const probes: string[] = [];const engine = {@@ -53,7 +53,7 @@ function fakeEngine(state: FakeState = {}) {disconnect: state.disconnect ?? (() => Promise.resolve()),getPoolDiagnostics: () => ({poisonedDiscards: 0, stuckDiscards: 0, buildFailures: 0, desyncDiscards: 0,- pool: driverPoolStats({ pool: { max: 4, open: 3, busy: 1, full: 0, reserved: 0, connecting: 0, closed: 0, ended: 0, queued: 0, inflight_oldest_ms: state.oldest ?? 0, completed: 1 } }),+ pool: driverPoolStats({ pool: { max: 4, open: 3, busy: 1, full: 0, reserved: 0, connecting: 0, closed: 0, ended: 0, queued: 0, inflight_oldest_ms: state.oldest ?? 0, completed: 1, ...(state.overBudget !== undefined ? { inflight_over_budget_ms: state.overBudget } : {}) } }),}),} as unknown as BrainEngine;return { engine, probes };@@ -140,6 +140,15 @@ describe('/health?deep=1 codes', () => {expect(result.body.fix).toContain('transport');});+ test('#6543 A4: with per-statement budgets, a long statement within its own declared budget is not over budget; one past it is', async () => {+ const declared = await probeDeepHealth(fakeEngine({ oldest: 900_000, overBudget: 0 }).engine, 'postgres', '1.2.3', 100, 330_000, healthy);+ expect(declared.ok).toBe(true);+ expect(declared.body.pool).toMatchObject({ inflight_oldest_ms: 900_000, inflight_over_budget_ms: 0 });+ const past = await probeDeepHealth(fakeEngine({ oldest: 900_000, overBudget: 900_000 }).engine, 'postgres', '1.2.3', 100, 330_000, healthy);+ if (past.ok) throw new Error('expected 503');+ expect(past.body.code).toBe('pool_inflight_over_budget');+ });+test('a probe that times out or fails carries deep_health_probe_failed with its reason', async () => {const timedOut = await probeDeepHealth(fakeEngine({ executeRaw: () => new Promise(() => {}) }).engine, 'postgres', '1.2.3', 20, 330_000, healthy);if (timedOut.ok) throw new Error('expected 503');diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.jsindex 3a3ea36cc8..41437f1e3a 100644--- a/vendor/postgres/cf/src/connection.js+++ b/vendor/postgres/cf/src/connection.js@@ -78,7 +78,8 @@ 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)+ , inflightTimer = budgetTimer('idle')+ , ageTimer = budgetTimer('age')let socket = null, cancelMessage@@ -116,12 +117,17 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, nonce = null, query = null, queryStart = 0+ , received = 0+ , localBudget = undefined+ , sessionBudget = undefined+ , recovering = null, final = nullconst connection = {queue: queues.closed,idleTimer,inflightSince: 0,+ inflightCap: 0,connect(query) {initial = queryreconnect()@@ -186,6 +192,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosebuild(q)mayPipeline = mayPipeline || q.options.onexecute(connection)+ noteBudget(q)lastWritten = qlastExecuted = qreturn write(toBuffer(q))@@ -231,16 +238,76 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose// 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.+ //+ // GBrain (#6543 A4): a second clock, `ageTimer`, is not restarted by received bytes, so a statement that keeps+ // streaming (or keeps receiving notices) past its budget is retired too (`reason: 'age'`; `'idle'` when nothing came+ // back). Both budgets are derived per statement from the statement_timeout the operation itself declared on this+ // connection (`SET [LOCAL] statement_timeout`, `set_config('statement_timeout', ...)`, tracked client-side so it+ // holds behind a transaction-mode pooler that never applies it): max(the pool's budget, the declared timeout) plus+ // `inflight_grace`, and none at all for a declared timeout of 0 (an index build, a bulk copy).function armInflight() {queryStart = connection.inflightSince = performance.now()+ received = 0+ query.inflightCaps || (query.inflightCaps = inflightCaps())+ connection.inflightCap = query.inflightCaps.ageinflightTimer.start()+ ageTimer.start()}- function inflightTimedOut() {+ function budgetTimer(kind) {+ let handle = null+ return {+ cancel() {+ handle && (clearTimeout(handle), handle = null)+ },+ start() {+ handle && clearTimeout(handle)+ const ms = query && query.inflightCaps ? query.inflightCaps[kind] : 0+ handle = ms ? setTimeout(() => (handle = null, inflightTimedOut(kind)), ms) : null+ }+ }+ }++ function inflightCaps() {+ const declared = localBudget !== undefined ? localBudget : sessionBudget+ if (declared === 0)+ return { idle: 0, age: 0 }+ const raised = declared === undefined ? 0 : declared + (options.inflight_grace || 0) * 1000+ return {+ idle: options.inflight_timeout ? Math.max(options.inflight_timeout * 1000, raised) : 0,+ age: options.inflight_max ? Math.max(options.inflight_max * 1000, raised) : 0+ }+ }++ // The statement_timeout changes a statement makes on this connection; a later statement is budgeted by them.+ function noteBudget(q) {+ const text = q.string || ''+ if (localBudget === undefined && sessionBudget === undefined && !/statement_timeout/i.test(text))+ return+ for (const change of statementTimeoutChanges(text, q.parameters)) {+ change.kind === 'end'+ ? localBudget = undefined+ : change.kind === 'reset'+ ? localBudget = sessionBudget = undefined+ : change.kind === 'set' && (change.local ? localBudget = change.ms : (sessionBudget = change.ms, localBudget = undefined))+ }+ q.inflightCaps = inflightCaps()+ if (q === query) {+ connection.inflightCap = q.inflightCaps.age+ inflightTimer.start()+ ageTimer.start()+ }+ }++ function inflightTimedOut(kind = 'idle') {if (!query)return- const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query) }+ inflightTimer.cancel()+ ageTimer.cancel()+ const reason = kind === 'age' && received > 0 ? 'age' : 'idle'+ const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query), reason, budget_ms: query.inflightCaps ? query.inflightCaps[kind] : 0 }const s = socket+ recovering = recovering || 'stuck'error(Errors.connection('CONNECTION_STUCK', options, socket))query = nullconnection.inflightSince = 0@@ -374,7 +441,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function data(x) {- query && inflightTimer.start()+ query && (received += x.length, inflightTimer.start())if (incomings) {incomings.push(x)remaining -= x.length@@ -472,9 +539,18 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosecancelError = errstream && (stream.destroy(err), stream = null)query && queryError(query, err)+ initial && recovering && recoveryFailed(err)initial && (queryError(initial, err), initial = null)}+ // GBrain (#6543 A6): a connection retired by an incident (stuck, desync, closed under statements) that completes a+ // new startup is `recovered`; one whose reconnect fails is `recovery_failed` (it stays marked until one succeeds).+ function recoveryFailed(err) {+ try {+ options.onrecoveryfailed && options.onrecoveryfailed({ connection: id, cause: recovering, code: String(err && err.code || 'CONNECTION_ERROR') })+ } catch (_) {}+ }+function queryError(query, err) {if (query.reserve)return query.reject(err)@@ -530,7 +606,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloselifeTimer.cancel()connectTimer.cancel()inflightTimer.cancel()- connection.inflightSince = 0+ ageTimer.cancel()+ connection.inflightSince = connection.inflightCap = 0+ localBudget = sessionBudget = undefinedsocket.removeAllListeners()socket = null@@ -550,6 +628,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn reconnect()}+ // GBrain (#6543 A6): a socket that closed under statements is a recovery the next completed startup reports.+ ;(query || sent.length) && (recovering = recovering || 'closed')!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))// GBrain (#6543): the dead socket's ErrorResponse (a FATAL 57P01, a pooler's XX000) and its partial result belonged// to statements that just failed. Left in place, the replacement connection's startup ReadyForQuery handed that@@ -618,9 +698,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction desynced(x) {const s = socketconst info = { message: String.fromCharCode(x), connection: id, statement: lastExecuted ? statementText(lastExecuted) : '' }+ recovering = recovering || 'desync'error(Errors.connection('CONNECTION_DESYNC', options, socket))+ inflightTimer.cancel()+ ageTimer.cancel()query = null- connection.inflightSince = 0+ connection.inflightSince = connection.inflightCap = 0ondesync(connection, info)terminate()if (s && !s.destroyed) {@@ -675,7 +758,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction ReadyForQuery(x) {connection.status = x[5]query && query === lastWritten && (lastWritten = null)- connection.inflightSince = 0+ connection.inflightSince = connection.inflightCap = 0+ // A transaction that ended takes its SET LOCAL statement_timeout with it.+ x[5] === 73 && !sent.length && (localBudget = undefined)if (query) {options.shared.completed++if (errorResponse) {@@ -701,6 +786,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseresult = new Result()connectTimer.cancel()inflightTimer.cancel()+ ageTimer.cancel()if (initial) {if (target_session_attrs) {@@ -719,6 +805,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseinitial && !reserving && execute(initial)options.shared.retries = retries = 0initial = null+ if (recovering) {+ const cause = recovering+ recovering = null+ try {+ options.onrecovered && options.onrecovered({ connection: id, cause })+ } catch (_) {}+ }if (!reserving)return}@@ -1223,6 +1316,59 @@ function xor(a, b) {return buffer}+// GBrain (#6543 A4): what one statement does to the connection's statement_timeout, in order: `set` (`local`, `ms`;+// 0 disables it, undefined is DEFAULT), `reset` (RESET statement_timeout / RESET ALL / DISCARD ALL), `end` (a+// transaction began or ended, which drops a SET LOCAL), and `unknown` for a change whose value cannot be read here.+// Dollar-quoted bodies are skipped, so a function body's BEGIN/END is not a transaction boundary.+const budgetSyntax = /(?:^|;)\s*(begin|start\s+transaction|commit|end|abort|rollback(?!\s+(?:to|prepared)\b))\b|\bset\s+(local\s+|session\s+)?statement_timeout\s*(?:=|\bto\b)\s*('(?:[^']|'')*'|[^\s;)]+)|\breset\s+(?:statement_timeout|all)\b|\bdiscard\s+all\b|\bset_config\s*\(\s*'statement_timeout'\s*,\s*('(?:[^']|'')*'|\$\d+)\s*,\s*([^)\s]+)\s*\)/gi++function statementTimeoutChanges(text, parameters) {+ const changes = []+ const plain = String(text || '').replace(/\$([A-Za-z_][A-Za-z0-9_]*)?\$[\s\S]*?\$\1\$/g, ' ')+ budgetSyntax.lastIndex = 0+ let m+ while ((m = budgetSyntax.exec(plain))) {+ if (m[1]) {+ changes.push({ kind: 'end' })+ } else if (m[3] !== undefined) {+ const ms = timeoutMs(m[3], parameters)+ changes.push(Number.isNaN(ms) ? { kind: 'unknown' } : { kind: 'set', local: /^local/i.test(m[2] || ''), ms })+ } else if (m[4] !== undefined) {+ const ms = timeoutMs(m[4], parameters)+ const local = parameterValue(m[5], parameters)+ changes.push(Number.isNaN(ms) || local === undefined ? { kind: 'unknown' } : { kind: 'set', local: /^(t|true|on|1)$/i.test(local), ms })+ } else {+ changes.push({ kind: 'reset' })+ }+ }+ return changes+}++function parameterValue(raw, parameters) {+ const p = /^\$(\d+)$/.exec(raw.trim())+ if (p) {+ const v = parameters && parameters[p[1] - 1]+ return v === null || v === undefined ? undefined : String(v)+ }+ const v = raw.trim()+ return /^'.*'$/s.test(v) ? v.slice(1, -1).replace(/''/g, "'") : v+}++function timeoutMs(raw, parameters) {+ const v = parameterValue(raw, parameters)+ if (v === undefined)+ return NaN+ if (/^default$/i.test(v.trim()))+ return undefined+ const m = /^\s*(\d+(?:\.\d+)?)\s*(us|ms|s|min|h|d)?\s*$/i.exec(v)+ if (!m)+ return NaN+ const unit = (m[2] || 'ms').toLowerCase()+ return Math.round(+m[1] * { us: 0.001, ms: 1, s: 1000, min: 60000, h: 3600000, d: 86400000 }[unit])+}++Connection.statementTimeoutChanges = statementTimeoutChanges+function timer(fn, seconds) {seconds = typeof seconds === 'function' ? seconds() : secondsif (!seconds)diff --git a/vendor/postgres/cf/src/index.js b/vendor/postgres/cf/src/index.jsindex ae8b031749..b04150f5ad 100644--- a/vendor/postgres/cf/src/index.js+++ b/vendor/postgres/cf/src/index.js@@ -86,6 +86,8 @@ function Postgres(a, b) {ended: ended.length,queued: queries.length,inflight_oldest_ms: connections.reduce((age, c) => c.inflightSince ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),+ // GBrain (#6543 A4): the oldest head statement past its own budget (the cap the driver retires it at), 0 when none is.+ inflight_over_budget_ms: connections.reduce((age, c) => c.inflightSince && c.inflightCap && now - c.inflightSince > c.inflightCap ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),completed: options.shared.completed}}@@ -631,7 +633,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-linequery.sslrootcert === 'system' && (query.ssl = 'verify-full')- const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout']+ const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout', 'inflight_max', 'inflight_grace']const defaults = {max : globalThis.Cloudflare ? 3 : 10,ssl : false,@@ -641,6 +643,8 @@ function parseOptions(a, b) {max_lifetime : max_lifetime,max_pipeline : 100,inflight_timeout: null,+ inflight_max : null,+ inflight_grace : null,backoff : backoff,keep_alive : 60,prepare : true,@@ -683,6 +687,8 @@ function parseOptions(a, b) {onstuck : o.onstuck,onbuilderror : o.onbuilderror,ondesync : o.ondesync,+ onrecovered : o.onrecovered,+ onrecoveryfailed: o.onrecoveryfailed,shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),onparameter : o.onparameter,socket : o.socket,diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.jsindex ad0cbd0c28..16f1373b64 100644--- a/vendor/postgres/cjs/src/connection.js+++ b/vendor/postgres/cjs/src/connection.js@@ -76,7 +76,8 @@ 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)+ , inflightTimer = budgetTimer('idle')+ , ageTimer = budgetTimer('age')let socket = null, cancelMessage@@ -114,12 +115,17 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, nonce = null, query = null, queryStart = 0+ , received = 0+ , localBudget = undefined+ , sessionBudget = undefined+ , recovering = null, final = nullconst connection = {queue: queues.closed,idleTimer,inflightSince: 0,+ inflightCap: 0,connect(query) {initial = queryreconnect()@@ -184,6 +190,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosebuild(q)mayPipeline = mayPipeline || q.options.onexecute(connection)+ noteBudget(q)lastWritten = qlastExecuted = qreturn write(toBuffer(q))@@ -229,16 +236,76 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose// 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.+ //+ // GBrain (#6543 A4): a second clock, `ageTimer`, is not restarted by received bytes, so a statement that keeps+ // streaming (or keeps receiving notices) past its budget is retired too (`reason: 'age'`; `'idle'` when nothing came+ // back). Both budgets are derived per statement from the statement_timeout the operation itself declared on this+ // connection (`SET [LOCAL] statement_timeout`, `set_config('statement_timeout', ...)`, tracked client-side so it+ // holds behind a transaction-mode pooler that never applies it): max(the pool's budget, the declared timeout) plus+ // `inflight_grace`, and none at all for a declared timeout of 0 (an index build, a bulk copy).function armInflight() {queryStart = connection.inflightSince = performance.now()+ received = 0+ query.inflightCaps || (query.inflightCaps = inflightCaps())+ connection.inflightCap = query.inflightCaps.ageinflightTimer.start()+ ageTimer.start()}- function inflightTimedOut() {+ function budgetTimer(kind) {+ let handle = null+ return {+ cancel() {+ handle && (clearTimeout(handle), handle = null)+ },+ start() {+ handle && clearTimeout(handle)+ const ms = query && query.inflightCaps ? query.inflightCaps[kind] : 0+ handle = ms ? setTimeout(() => (handle = null, inflightTimedOut(kind)), ms) : null+ }+ }+ }++ function inflightCaps() {+ const declared = localBudget !== undefined ? localBudget : sessionBudget+ if (declared === 0)+ return { idle: 0, age: 0 }+ const raised = declared === undefined ? 0 : declared + (options.inflight_grace || 0) * 1000+ return {+ idle: options.inflight_timeout ? Math.max(options.inflight_timeout * 1000, raised) : 0,+ age: options.inflight_max ? Math.max(options.inflight_max * 1000, raised) : 0+ }+ }++ // The statement_timeout changes a statement makes on this connection; a later statement is budgeted by them.+ function noteBudget(q) {+ const text = q.string || ''+ if (localBudget === undefined && sessionBudget === undefined && !/statement_timeout/i.test(text))+ return+ for (const change of statementTimeoutChanges(text, q.parameters)) {+ change.kind === 'end'+ ? localBudget = undefined+ : change.kind === 'reset'+ ? localBudget = sessionBudget = undefined+ : change.kind === 'set' && (change.local ? localBudget = change.ms : (sessionBudget = change.ms, localBudget = undefined))+ }+ q.inflightCaps = inflightCaps()+ if (q === query) {+ connection.inflightCap = q.inflightCaps.age+ inflightTimer.start()+ ageTimer.start()+ }+ }++ function inflightTimedOut(kind = 'idle') {if (!query)return- const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query) }+ inflightTimer.cancel()+ ageTimer.cancel()+ const reason = kind === 'age' && received > 0 ? 'age' : 'idle'+ const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query), reason, budget_ms: query.inflightCaps ? query.inflightCaps[kind] : 0 }const s = socket+ recovering = recovering || 'stuck'error(Errors.connection('CONNECTION_STUCK', options, socket))query = nullconnection.inflightSince = 0@@ -372,7 +439,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function data(x) {- query && inflightTimer.start()+ query && (received += x.length, inflightTimer.start())if (incomings) {incomings.push(x)remaining -= x.length@@ -470,9 +537,18 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosecancelError = errstream && (stream.destroy(err), stream = null)query && queryError(query, err)+ initial && recovering && recoveryFailed(err)initial && (queryError(initial, err), initial = null)}+ // GBrain (#6543 A6): a connection retired by an incident (stuck, desync, closed under statements) that completes a+ // new startup is `recovered`; one whose reconnect fails is `recovery_failed` (it stays marked until one succeeds).+ function recoveryFailed(err) {+ try {+ options.onrecoveryfailed && options.onrecoveryfailed({ connection: id, cause: recovering, code: String(err && err.code || 'CONNECTION_ERROR') })+ } catch (_) {}+ }+function queryError(query, err) {if (query.reserve)return query.reject(err)@@ -528,7 +604,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloselifeTimer.cancel()connectTimer.cancel()inflightTimer.cancel()- connection.inflightSince = 0+ ageTimer.cancel()+ connection.inflightSince = connection.inflightCap = 0+ localBudget = sessionBudget = undefinedsocket.removeAllListeners()socket = null@@ -548,6 +626,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn reconnect()}+ // GBrain (#6543 A6): a socket that closed under statements is a recovery the next completed startup reports.+ ;(query || sent.length) && (recovering = recovering || 'closed')!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))// GBrain (#6543): the dead socket's ErrorResponse (a FATAL 57P01, a pooler's XX000) and its partial result belonged// to statements that just failed. Left in place, the replacement connection's startup ReadyForQuery handed that@@ -616,9 +696,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction desynced(x) {const s = socketconst info = { message: String.fromCharCode(x), connection: id, statement: lastExecuted ? statementText(lastExecuted) : '' }+ recovering = recovering || 'desync'error(Errors.connection('CONNECTION_DESYNC', options, socket))+ inflightTimer.cancel()+ ageTimer.cancel()query = null- connection.inflightSince = 0+ connection.inflightSince = connection.inflightCap = 0ondesync(connection, info)terminate()if (s && !s.destroyed) {@@ -673,7 +756,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction ReadyForQuery(x) {connection.status = x[5]query && query === lastWritten && (lastWritten = null)- connection.inflightSince = 0+ connection.inflightSince = connection.inflightCap = 0+ // A transaction that ended takes its SET LOCAL statement_timeout with it.+ x[5] === 73 && !sent.length && (localBudget = undefined)if (query) {options.shared.completed++if (errorResponse) {@@ -699,6 +784,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseresult = new Result()connectTimer.cancel()inflightTimer.cancel()+ ageTimer.cancel()if (initial) {if (target_session_attrs) {@@ -717,6 +803,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseinitial && !reserving && execute(initial)options.shared.retries = retries = 0initial = null+ if (recovering) {+ const cause = recovering+ recovering = null+ try {+ options.onrecovered && options.onrecovered({ connection: id, cause })+ } catch (_) {}+ }if (!reserving)return}@@ -1221,6 +1314,59 @@ function xor(a, b) {return buffer}+// GBrain (#6543 A4): what one statement does to the connection's statement_timeout, in order: `set` (`local`, `ms`;+// 0 disables it, undefined is DEFAULT), `reset` (RESET statement_timeout / RESET ALL / DISCARD ALL), `end` (a+// transaction began or ended, which drops a SET LOCAL), and `unknown` for a change whose value cannot be read here.+// Dollar-quoted bodies are skipped, so a function body's BEGIN/END is not a transaction boundary.+const budgetSyntax = /(?:^|;)\s*(begin|start\s+transaction|commit|end|abort|rollback(?!\s+(?:to|prepared)\b))\b|\bset\s+(local\s+|session\s+)?statement_timeout\s*(?:=|\bto\b)\s*('(?:[^']|'')*'|[^\s;)]+)|\breset\s+(?:statement_timeout|all)\b|\bdiscard\s+all\b|\bset_config\s*\(\s*'statement_timeout'\s*,\s*('(?:[^']|'')*'|\$\d+)\s*,\s*([^)\s]+)\s*\)/gi++function statementTimeoutChanges(text, parameters) {+ const changes = []+ const plain = String(text || '').replace(/\$([A-Za-z_][A-Za-z0-9_]*)?\$[\s\S]*?\$\1\$/g, ' ')+ budgetSyntax.lastIndex = 0+ let m+ while ((m = budgetSyntax.exec(plain))) {+ if (m[1]) {+ changes.push({ kind: 'end' })+ } else if (m[3] !== undefined) {+ const ms = timeoutMs(m[3], parameters)+ changes.push(Number.isNaN(ms) ? { kind: 'unknown' } : { kind: 'set', local: /^local/i.test(m[2] || ''), ms })+ } else if (m[4] !== undefined) {+ const ms = timeoutMs(m[4], parameters)+ const local = parameterValue(m[5], parameters)+ changes.push(Number.isNaN(ms) || local === undefined ? { kind: 'unknown' } : { kind: 'set', local: /^(t|true|on|1)$/i.test(local), ms })+ } else {+ changes.push({ kind: 'reset' })+ }+ }+ return changes+}++function parameterValue(raw, parameters) {+ const p = /^\$(\d+)$/.exec(raw.trim())+ if (p) {+ const v = parameters && parameters[p[1] - 1]+ return v === null || v === undefined ? undefined : String(v)+ }+ const v = raw.trim()+ return /^'.*'$/s.test(v) ? v.slice(1, -1).replace(/''/g, "'") : v+}++function timeoutMs(raw, parameters) {+ const v = parameterValue(raw, parameters)+ if (v === undefined)+ return NaN+ if (/^default$/i.test(v.trim()))+ return undefined+ const m = /^\s*(\d+(?:\.\d+)?)\s*(us|ms|s|min|h|d)?\s*$/i.exec(v)+ if (!m)+ return NaN+ const unit = (m[2] || 'ms').toLowerCase()+ return Math.round(+m[1] * { us: 0.001, ms: 1, s: 1000, min: 60000, h: 3600000, d: 86400000 }[unit])+}++Connection.statementTimeoutChanges = statementTimeoutChanges+function timer(fn, seconds) {seconds = typeof seconds === 'function' ? seconds() : secondsif (!seconds)diff --git a/vendor/postgres/cjs/src/index.js b/vendor/postgres/cjs/src/index.jsindex dc7e234da4..93eb66dae2 100644--- a/vendor/postgres/cjs/src/index.js+++ b/vendor/postgres/cjs/src/index.js@@ -85,6 +85,8 @@ function Postgres(a, b) {ended: ended.length,queued: queries.length,inflight_oldest_ms: connections.reduce((age, c) => c.inflightSince ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),+ // GBrain (#6543 A4): the oldest head statement past its own budget (the cap the driver retires it at), 0 when none is.+ inflight_over_budget_ms: connections.reduce((age, c) => c.inflightSince && c.inflightCap && now - c.inflightSince > c.inflightCap ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),completed: options.shared.completed}}@@ -630,7 +632,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-linequery.sslrootcert === 'system' && (query.ssl = 'verify-full')- const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout']+ const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout', 'inflight_max', 'inflight_grace']const defaults = {max : globalThis.Cloudflare ? 3 : 10,ssl : false,@@ -640,6 +642,8 @@ function parseOptions(a, b) {max_lifetime : max_lifetime,max_pipeline : 100,inflight_timeout: null,+ inflight_max : null,+ inflight_grace : null,backoff : backoff,keep_alive : 60,prepare : true,@@ -682,6 +686,8 @@ function parseOptions(a, b) {onstuck : o.onstuck,onbuilderror : o.onbuilderror,ondesync : o.ondesync,+ onrecovered : o.onrecovered,+ onrecoveryfailed: o.onrecoveryfailed,shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),onparameter : o.onparameter,socket : o.socket,diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.jsindex 84f8a5878e..9fc39c2cb6 100644--- a/vendor/postgres/src/connection.js+++ b/vendor/postgres/src/connection.js@@ -76,7 +76,8 @@ 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)+ , inflightTimer = budgetTimer('idle')+ , ageTimer = budgetTimer('age')let socket = null, cancelMessage@@ -114,12 +115,17 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, nonce = null, query = null, queryStart = 0+ , received = 0+ , localBudget = undefined+ , sessionBudget = undefined+ , recovering = null, final = nullconst connection = {queue: queues.closed,idleTimer,inflightSince: 0,+ inflightCap: 0,connect(query) {initial = queryreconnect()@@ -184,6 +190,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosebuild(q)mayPipeline = mayPipeline || q.options.onexecute(connection)+ noteBudget(q)lastWritten = qlastExecuted = qreturn write(toBuffer(q))@@ -229,16 +236,76 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose// 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.+ //+ // GBrain (#6543 A4): a second clock, `ageTimer`, is not restarted by received bytes, so a statement that keeps+ // streaming (or keeps receiving notices) past its budget is retired too (`reason: 'age'`; `'idle'` when nothing came+ // back). Both budgets are derived per statement from the statement_timeout the operation itself declared on this+ // connection (`SET [LOCAL] statement_timeout`, `set_config('statement_timeout', ...)`, tracked client-side so it+ // holds behind a transaction-mode pooler that never applies it): max(the pool's budget, the declared timeout) plus+ // `inflight_grace`, and none at all for a declared timeout of 0 (an index build, a bulk copy).function armInflight() {queryStart = connection.inflightSince = performance.now()+ received = 0+ query.inflightCaps || (query.inflightCaps = inflightCaps())+ connection.inflightCap = query.inflightCaps.ageinflightTimer.start()+ ageTimer.start()}- function inflightTimedOut() {+ function budgetTimer(kind) {+ let handle = null+ return {+ cancel() {+ handle && (clearTimeout(handle), handle = null)+ },+ start() {+ handle && clearTimeout(handle)+ const ms = query && query.inflightCaps ? query.inflightCaps[kind] : 0+ handle = ms ? setTimeout(() => (handle = null, inflightTimedOut(kind)), ms) : null+ }+ }+ }++ function inflightCaps() {+ const declared = localBudget !== undefined ? localBudget : sessionBudget+ if (declared === 0)+ return { idle: 0, age: 0 }+ const raised = declared === undefined ? 0 : declared + (options.inflight_grace || 0) * 1000+ return {+ idle: options.inflight_timeout ? Math.max(options.inflight_timeout * 1000, raised) : 0,+ age: options.inflight_max ? Math.max(options.inflight_max * 1000, raised) : 0+ }+ }++ // The statement_timeout changes a statement makes on this connection; a later statement is budgeted by them.+ function noteBudget(q) {+ const text = q.string || ''+ if (localBudget === undefined && sessionBudget === undefined && !/statement_timeout/i.test(text))+ return+ for (const change of statementTimeoutChanges(text, q.parameters)) {+ change.kind === 'end'+ ? localBudget = undefined+ : change.kind === 'reset'+ ? localBudget = sessionBudget = undefined+ : change.kind === 'set' && (change.local ? localBudget = change.ms : (sessionBudget = change.ms, localBudget = undefined))+ }+ q.inflightCaps = inflightCaps()+ if (q === query) {+ connection.inflightCap = q.inflightCaps.age+ inflightTimer.start()+ ageTimer.start()+ }+ }++ function inflightTimedOut(kind = 'idle') {if (!query)return- const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query) }+ inflightTimer.cancel()+ ageTimer.cancel()+ const reason = kind === 'age' && received > 0 ? 'age' : 'idle'+ const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query), reason, budget_ms: query.inflightCaps ? query.inflightCaps[kind] : 0 }const s = socket+ recovering = recovering || 'stuck'error(Errors.connection('CONNECTION_STUCK', options, socket))query = nullconnection.inflightSince = 0@@ -372,7 +439,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function data(x) {- query && inflightTimer.start()+ query && (received += x.length, inflightTimer.start())if (incomings) {incomings.push(x)remaining -= x.length@@ -470,9 +537,18 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosecancelError = errstream && (stream.destroy(err), stream = null)query && queryError(query, err)+ initial && recovering && recoveryFailed(err)initial && (queryError(initial, err), initial = null)}+ // GBrain (#6543 A6): a connection retired by an incident (stuck, desync, closed under statements) that completes a+ // new startup is `recovered`; one whose reconnect fails is `recovery_failed` (it stays marked until one succeeds).+ function recoveryFailed(err) {+ try {+ options.onrecoveryfailed && options.onrecoveryfailed({ connection: id, cause: recovering, code: String(err && err.code || 'CONNECTION_ERROR') })+ } catch (_) {}+ }+function queryError(query, err) {if (query.reserve)return query.reject(err)@@ -528,7 +604,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloselifeTimer.cancel()connectTimer.cancel()inflightTimer.cancel()- connection.inflightSince = 0+ ageTimer.cancel()+ connection.inflightSince = connection.inflightCap = 0+ localBudget = sessionBudget = undefinedsocket.removeAllListeners()socket = null@@ -548,6 +626,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn reconnect()}+ // GBrain (#6543 A6): a socket that closed under statements is a recovery the next completed startup reports.+ ;(query || sent.length) && (recovering = recovering || 'closed')!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))// GBrain (#6543): the dead socket's ErrorResponse (a FATAL 57P01, a pooler's XX000) and its partial result belonged// to statements that just failed. Left in place, the replacement connection's startup ReadyForQuery handed that@@ -616,9 +696,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction desynced(x) {const s = socketconst info = { message: String.fromCharCode(x), connection: id, statement: lastExecuted ? statementText(lastExecuted) : '' }+ recovering = recovering || 'desync'error(Errors.connection('CONNECTION_DESYNC', options, socket))+ inflightTimer.cancel()+ ageTimer.cancel()query = null- connection.inflightSince = 0+ connection.inflightSince = connection.inflightCap = 0ondesync(connection, info)terminate()if (s && !s.destroyed) {@@ -673,7 +756,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction ReadyForQuery(x) {connection.status = x[5]query && query === lastWritten && (lastWritten = null)- connection.inflightSince = 0+ connection.inflightSince = connection.inflightCap = 0+ // A transaction that ended takes its SET LOCAL statement_timeout with it.+ x[5] === 73 && !sent.length && (localBudget = undefined)if (query) {options.shared.completed++if (errorResponse) {@@ -699,6 +784,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseresult = new Result()connectTimer.cancel()inflightTimer.cancel()+ ageTimer.cancel()if (initial) {if (target_session_attrs) {@@ -717,6 +803,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseinitial && !reserving && execute(initial)options.shared.retries = retries = 0initial = null+ if (recovering) {+ const cause = recovering+ recovering = null+ try {+ options.onrecovered && options.onrecovered({ connection: id, cause })+ } catch (_) {}+ }if (!reserving)return}@@ -1221,6 +1314,59 @@ function xor(a, b) {return buffer}+// GBrain (#6543 A4): what one statement does to the connection's statement_timeout, in order: `set` (`local`, `ms`;+// 0 disables it, undefined is DEFAULT), `reset` (RESET statement_timeout / RESET ALL / DISCARD ALL), `end` (a+// transaction began or ended, which drops a SET LOCAL), and `unknown` for a change whose value cannot be read here.+// Dollar-quoted bodies are skipped, so a function body's BEGIN/END is not a transaction boundary.+const budgetSyntax = /(?:^|;)\s*(begin|start\s+transaction|commit|end|abort|rollback(?!\s+(?:to|prepared)\b))\b|\bset\s+(local\s+|session\s+)?statement_timeout\s*(?:=|\bto\b)\s*('(?:[^']|'')*'|[^\s;)]+)|\breset\s+(?:statement_timeout|all)\b|\bdiscard\s+all\b|\bset_config\s*\(\s*'statement_timeout'\s*,\s*('(?:[^']|'')*'|\$\d+)\s*,\s*([^)\s]+)\s*\)/gi++function statementTimeoutChanges(text, parameters) {+ const changes = []+ const plain = String(text || '').replace(/\$([A-Za-z_][A-Za-z0-9_]*)?\$[\s\S]*?\$\1\$/g, ' ')+ budgetSyntax.lastIndex = 0+ let m+ while ((m = budgetSyntax.exec(plain))) {+ if (m[1]) {+ changes.push({ kind: 'end' })+ } else if (m[3] !== undefined) {+ const ms = timeoutMs(m[3], parameters)+ changes.push(Number.isNaN(ms) ? { kind: 'unknown' } : { kind: 'set', local: /^local/i.test(m[2] || ''), ms })+ } else if (m[4] !== undefined) {+ const ms = timeoutMs(m[4], parameters)+ const local = parameterValue(m[5], parameters)+ changes.push(Number.isNaN(ms) || local === undefined ? { kind: 'unknown' } : { kind: 'set', local: /^(t|true|on|1)$/i.test(local), ms })+ } else {+ changes.push({ kind: 'reset' })+ }+ }+ return changes+}++function parameterValue(raw, parameters) {+ const p = /^\$(\d+)$/.exec(raw.trim())+ if (p) {+ const v = parameters && parameters[p[1] - 1]+ return v === null || v === undefined ? undefined : String(v)+ }+ const v = raw.trim()+ return /^'.*'$/s.test(v) ? v.slice(1, -1).replace(/''/g, "'") : v+}++function timeoutMs(raw, parameters) {+ const v = parameterValue(raw, parameters)+ if (v === undefined)+ return NaN+ if (/^default$/i.test(v.trim()))+ return undefined+ const m = /^\s*(\d+(?:\.\d+)?)\s*(us|ms|s|min|h|d)?\s*$/i.exec(v)+ if (!m)+ return NaN+ const unit = (m[2] || 'ms').toLowerCase()+ return Math.round(+m[1] * { us: 0.001, ms: 1, s: 1000, min: 60000, h: 3600000, d: 86400000 }[unit])+}++Connection.statementTimeoutChanges = statementTimeoutChanges+function timer(fn, seconds) {seconds = typeof seconds === 'function' ? seconds() : secondsif (!seconds)diff --git a/vendor/postgres/src/index.js b/vendor/postgres/src/index.jsindex 6718a17dd8..5bfd92f51f 100644--- a/vendor/postgres/src/index.js+++ b/vendor/postgres/src/index.js@@ -85,6 +85,8 @@ function Postgres(a, b) {ended: ended.length,queued: queries.length,inflight_oldest_ms: connections.reduce((age, c) => c.inflightSince ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),+ // GBrain (#6543 A4): the oldest head statement past its own budget (the cap the driver retires it at), 0 when none is.+ inflight_over_budget_ms: connections.reduce((age, c) => c.inflightSince && c.inflightCap && now - c.inflightSince > c.inflightCap ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),completed: options.shared.completed}}@@ -630,7 +632,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-linequery.sslrootcert === 'system' && (query.ssl = 'verify-full')- const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout']+ const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout', 'inflight_max', 'inflight_grace']const defaults = {max : globalThis.Cloudflare ? 3 : 10,ssl : false,@@ -640,6 +642,8 @@ function parseOptions(a, b) {max_lifetime : max_lifetime,max_pipeline : 100,inflight_timeout: null,+ inflight_max : null,+ inflight_grace : null,backoff : backoff,keep_alive : 60,prepare : true,@@ -682,6 +686,8 @@ function parseOptions(a, b) {onstuck : o.onstuck,onbuilderror : o.onbuilderror,ondesync : o.ondesync,+ onrecovered : o.onrecovered,+ onrecoveryfailed: o.onrecoveryfailed,shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),onparameter : o.onparameter,socket : o.socket,diff --git a/vendor/postgres/types/index.d.ts b/vendor/postgres/types/index.d.tsindex b77d74e109..0d487167c6 100644--- a/vendor/postgres/types/index.d.ts+++ b/vendor/postgres/types/index.d.ts@@ -131,8 +131,21 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {* @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 (#6543): seconds a head statement may run in total, whatever the server keeps sending, before the+ * connection is retired with `CONNECTION_STUCK` (`reason: 'age'`). A statement after a declared+ * `statement_timeout` above the budget gets that timeout plus `inflight_grace`; a declared 0 disables both clocks.+ * @default null+ */+ inflight_max: number | null;+ /** GBrain (#6543): seconds added to a declared statement_timeout that raises a statement's budget. @default null */+ inflight_grace: number | null;+ /** GBrain: called once per connection the in-flight watchdog retired; `reason` is `age` when bytes kept arriving, else `idle`. */+ onstuck: (stuck: { age_ms: number; queued: number; statement: string; reason: 'age' | 'idle'; budget_ms: number }) => void;+ /** GBrain (#6543): a connection retired by an incident (`stuck`, `desync`, `closed` under statements) completed a new startup. */+ onrecovered: (recovered: { connection: number; cause: 'stuck' | 'desync' | 'closed' }) => void;+ /** GBrain (#6543): the reconnect of a connection retired by an incident failed; it stays marked until one succeeds. */+ onrecoveryfailed: (failed: { connection: number; cause: 'stuck' | 'desync' | 'closed'; code: 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; `parameter` is the 1-based