Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(postgres): discard pooled connections left inside a transaction (#5730)

garrytanda9fafb2e86f
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 06fd5edf14..4c25404c4c 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -550,6 +550,33 @@ keep die-on-startup (that lane's repair is `gbrain pglite-repair`), and
mid-session outages ride the engine's own reconnect plus the per-call
classified envelopes.
+### Pool and transaction diagnostics
+
+These warn lines and errors come from the Postgres engine's connection pools.
+Each one names a stable code, its cause, a command and this anchor.
+
+<a id="pg-connection-poisoned"></a>**`pg_connection_poisoned`** (warn).
+A pooled connection came back to the pool inside a transaction (ReadyForQuery
+status `T`) or a failed one (`E`), usually because a caller released a reserved
+connection without `COMMIT` or `ROLLBACK`. The driver terminates that connection
+instead of reusing it, so later statements never run inside the leftover
+transaction and never fail with SQLSTATE `25P02`. Queued statements move to a
+fresh connection. The line names the status byte and the pool (`read` or
+`direct`) and carries no query text. `getPoolDiagnostics().poisonedDiscards`
+counts discards per engine. There is no opt-out. Nothing needs to be repaired;
+if the line repeats, run `gbrain doctor --json` and report the warn lines with
+the operations that preceded them. A pool created with `max: 1` keeps the
+driver's documented single-connection idiom (`BEGIN` as an ordinary query)
+for unreserved statements.
+
+<a id="backfill-rollback-failed"></a>**`backfill_rollback_failed`** (error).
+A `gbrain backfill` batch failed, and its `ROLLBACK` failed too. The run stops
+rather than retrying on a connection whose transaction state is unknown; the
+driver discards that connection. Nothing from the batch was committed and the
+checkpoint did not advance. The message names both errors (redacted, at most
+200 characters each). Fix the cause they name, then run
+`gbrain backfill <kind> --resume`.
+
## JSONB writes: never double-encode
Writing a JS value into a `jsonb` column has exactly two correct forms. Get this
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index 7d0e2a93f9..8992d7aeab 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/db-repair-receipts.ts` — the shared seam between `gbrain db-repair` (writer) and doctor's `db_repair_recurrence` check (reader — it must run in doctor's dead-DB filesystem lane, exactly when repairs are repeating). JSONL at `~/.gbrain/db-repair-receipts.jsonl`; row shape `{ts, brain_id, reason, action, outcome: 'applied'|'refused'|'diagnose'}` — only `applied` rows count toward the recurrence threshold (3+ same-reason per brain in 7 days). Redacted before write (the classifier redacts its own copy; actions are fixed strings), fail-open (a receipts problem never blocks a repair), capped at 200 rows ON EVERY WRITE (the recurrence check reads the file on every doctor run — it must not grow unbounded on exactly the machines having chronic problems) — EXCEPT `applied` rows inside an 8-day retention window, which are exempt from the flat cap (separately bounded at 200): a diagnose flood from an agent loop must never evict the cooldown/recurrence memory. The reader is per-line tolerant (one torn row never discards every other receipt). Also owns `rewriteCooldownBlocked` (24h per (reason, action), rewrite tier only).
-- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect()` returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the CLI teardown contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`.
+- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect(config, { onpoisoned })` passes the owner engine's poisoned-discard hook to the singleton pool and returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the CLI teardown contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`.
- `src/core/degraded-engine.ts` + `src/core/degraded-marker.ts` — degraded-mode serve, STARTUP-SCOPED by design: when Postgres is unreachable at `gbrain serve` startup, serve boots on `createDegradedEngine` (a concrete object whose method set is enumerated from PostgresEngine's prototype at construction — no dynamic `get` trap; `kind` is an explicit getter, read synchronously at ~29 branch sites; `disconnect()` is a no-op while dead so shutdown never triggers a reconnect) instead of dying. Every tool call attempts ONE reconnect (single-flight across concurrent callers, min-interval gated ~5s — no connect storms against a dying pooler); calls inside the window throw the STORED original error (stale-but-honest, refreshed on every real attempt) so MCP dispatch classifies the REAL error shape into the `database_error` envelope + marker. The `reconnect` callback is the FULL deferred connectEngine (config merge, gateway, migrations — guarded in cli.ts: a vanished config.json throws instead of connectEngine's process.exit killing the live server); first success swaps in the live engine permanently and fires recovery callbacks (serve re-runs deferred boot + sends `tools/list_changed` — clients that handshook degraded hold the reduced gate-hidden catalog and must refresh; the callback is a no-op once shutdown has started) — but the TRIGGERING call gets `DegradedRecoveredRetryError`, never a result: its source scope was resolved under the degraded fallback, so one client retry buys scope correctness (no call ever executes under the fallback scope against a live engine). Callers waiting on an in-flight attempt are latency-capped (`callerWaitMs`, default 2s — they get the stored error while the attempt finishes in the background, so a timeout-class failure can't stall the MCP handshake). Prototype GETTERS delegate too (throw the stored error while dead — never a silent `undefined`); `DEGRADED_LAST_ERROR` is a read-only accessor for the stored diagnosis (drives the HTTP `/health` degraded reason without consuming a reconnect). Serve-side degraded posture: source scope honors a validated `GBRAIN_SOURCE` (tier `env`) before seed_default, and `stdioVisibleTools` fail-closes every gated op WITHOUT touching the engine. The degraded gate keys on the RESOLVED brain's engine (a PGLite mount on a postgres host keeps die-on-startup). Mid-session outages ride `PostgresEngine.reconnect()` + per-call classified envelopes — degraded mode adds no mid-session state; PGLite startup failures keep die-on-startup (single-writer lock makes a lazy proxy wrong there; that lane's repair is pglite-repair). Kill switch `GBRAIN_SERVE_DEGRADED=0` (or `false`); structured `[gbrain-serve] DEGRADED/RECOVERED` stderr lines. `degraded-marker.ts` is the dependency-free seam (`Symbol.for`-registered markers + `isEngineDegraded`/`onEngineRecovered`/`degradedLastError`) so server.ts/serve.ts/http-transport.ts can ask about degraded state without importing the heavy Postgres engine module.
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index bb2b4e2c9c..a8c79d9ca0 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `patches/[email protected]` — auditable delta for the driver ownership and cancellation repair already applied to the shipped `vendor/postgres` ESM/CommonJS/workerd source (not an install hook; `bash vendor/update-postgres.sh --check` verifies it), consumed by `PostgresEngine.runUnsafe` through `#postgres`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`.
+- `patches/[email protected]` — auditable delta for the driver ownership and cancellation repair already applied to the shipped `vendor/postgres` ESM/CommonJS/workerd source (not an install hook; `bash vendor/update-postgres.sh --check` verifies it), consumed by `PostgresEngine.runUnsafe` through `#postgres`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. A pooled connection (pool `max` above 1) or a released reservation whose last ReadyForQuery status is not idle is terminated instead of reused, and the `onpoisoned(status)` option reports it (pinned by `test/e2e/postgres-poisoned-connection.test.ts`). See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`.
- `src/core/engine-sql/` — one SQL implementation per migrated storage domain (the domains are the `migrated` rows of `scripts/engine-sql-baseline.tsv`), run by both engines through one executor contract:
@@ -28,7 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/pool-budget.ts` + `src/core/persistence/pool-capacity.ts` — physical-pool shared long-hold ceilings retain one ordinary/control connection across engine clones; pool size one pauses canonical consumption with `writer_pool_capacity`. Publication concurrency is capped at two per actual Postgres pool and one per PGLite owner. `persistence/takes-prepare.ts` journals semantic takes with frozen dates/resolver identity and original/current holder ceilings; canonical row updates and receipt commit together. Publication retains the actual affected holders privately in authority JSON, so narrowed holder grants also hide committed/replayed receipts after input compaction.
-- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`.
+- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`. `PoisonedDiscardCounter` counts the driver's non-idle connection discards and writes one fixed-shape `pg_connection_poisoned` warn line each; the engine wires it into every pool it creates and reports it as `poisonedDiscards`.
- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The package-private `#postgres` import maps directly to the shipped cancellation-capable `vendor/postgres` source (the same source is embedded by compiled builds); `vendor/README.md` and the hash-verifying updater own provenance and regeneration. `postgres-engine/cancellation.ts` shares actual reserved-owner capability detection, typed `postgres_cancellation_unavailable` errors, and abort-bounded reservation with late-owner release; unsignalled diagnostic queries remain usable. Signalled SQL must retain cancellation/discard safety, including through transaction-mode poolers. The migrated storage domains' methods are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh Postgres adapter over `this.sql` on every access; RLS-scoped reads brand the `withScopedReadTransaction` handle with `scopedRead`), Postgres-only code stays under `src/core/postgres-engine/`, and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. `getEmbeddingsByChunkIds` (in `src/core/engine-sql/chunks.ts`, both engines) uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. The chunk SQL below lives once in `src/core/engine-sql/chunks.ts`; the engine resolves the active column and source scope, owns the retry/transaction wrapper and the RLS scope transaction, and passes them in. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap(conn)` BEFORE replaying SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (Postgres dialect hooks: `current_schema()` probes plus the Postgres-blob-only `dream_verdicts.expires_at` probe); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-lifecycle.test.ts` (concurrent-connect ownership, `db.disconnect()` detaching the singleton before awaiting `end()`, and the instance-reconnect `_reconnecting` guard). `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`).
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers every BrainEngine method whose SQL has not moved to `src/core/engine-sql/` (rows in `scripts/engine-sql-baseline.tsv`), written as parity twins of the PGLite methods (search arms, graph traversal caps, source-scoped stats and health, page lifecycle and soft delete, chunk writes, transaction routing). Migrated domains are one-line delegations over the private `engineSql` getter (a fresh adapter over `this.sql` on every access); reads that were RLS-scoped on master keep their own `withScopedReadTransaction` call and hand engine-sql `scopedRead(this.engineSqlOn(tx))`, an adapter over the scoped handle; `runUnsafe` forwards `prepare`/`simple` only when the engine-sql adapter sets them.
diff --git a/patches/[email protected] b/patches/[email protected]
index 99495d6b52..d632b06116 100644
--- a/patches/[email protected]
+++ b/patches/[email protected]
@@ -1,5 +1,5 @@
diff --git a/cjs/src/connection.js b/cjs/src/connection.js
-index 07f6716702ac888215c86ad6e0071aaf55ae519c..be36dfd08e084c7f1c181e42cd1c57d5213e3293 100644
+index 07f6716702ac888215c86ad6e0071aaf55ae519c..e5800bca79ea3e5d638176bcdfa6124dbb94e18b 100644
--- a/cjs/src/connection.js
+++ b/cjs/src/connection.js
@@ -78,6 +78,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
@@ -81,7 +81,15 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..be36dfd08e084c7f1c181e42cd1c57d5
if (initial)
return reconnect()
-@@ -564,10 +579,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -533,6 +548,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ }
+
+ function ReadyForQuery(x) {
++ connection.status = x[5]
+ if (query) {
+ if (errorResponse) {
+ query.retried
+@@ -564,10 +580,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return fetchArrayTypes()
}
@@ -96,7 +104,7 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..be36dfd08e084c7f1c181e42cd1c57d5
}
while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
-@@ -580,7 +597,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -580,7 +598,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
? !connection.reserved.release && x[5] === 73 // I
? ending
? terminate()
@@ -106,7 +114,7 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..be36dfd08e084c7f1c181e42cd1c57d5
: ending
? terminate()
diff --git a/cjs/src/index.js b/cjs/src/index.js
-index f09c61c7e998f411560b95c9a8e1ed6a97972c11..9dc0c7a2303941079f2c3c4e668105444a8ef1af 100644
+index f09c61c7e998f411560b95c9a8e1ed6a97972c11..c72e4135627296dd00179e30d02094d591047267 100644
--- a/cjs/src/index.js
+++ b/cjs/src/index.js
@@ -200,40 +200,134 @@ function Postgres(a, b) {
@@ -189,7 +197,7 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..9dc0c7a2303941079f2c3c4e66810544
+ if (!busy) {
+ if (releasing) {
+ c.reserved = null
-+ onopen(c)
++ onopen(c, true)
+ } else {
+ move(c, reserved)
+ }
@@ -309,10 +317,14 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..9dc0c7a2303941079f2c3c4e66810544
}
}
-@@ -399,6 +497,11 @@ function Postgres(a, b) {
+@@ -398,7 +496,14 @@ function Postgres(a, b) {
+ move(c, ended)
}
- function onopen(c) {
+- function onopen(c) {
++ function onopen(c, released) {
++ if (c.status && c.status !== 73 && (released || options.max !== 1)) // not I
++ return poisoned(c)
+ if (ending) {
+ while (queries.length)
+ queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))
@@ -321,8 +333,20 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..9dc0c7a2303941079f2c3c4e66810544
if (queries.length === 0)
return move(c, open)
-@@ -420,10 +523,20 @@ function Postgres(a, b) {
+@@ -418,12 +523,32 @@ function Postgres(a, b) {
+ : move(c, full)
+ }
++ function poisoned(c) {
++ if (c.queue === ended)
++ return
++ move(c, ended)
++ try {
++ options.onpoisoned && options.onpoisoned(String.fromCharCode(c.status))
++ } catch (_) {}
++ c.terminate()
++ }
++
function onclose(c, e) {
move(c, closed)
+ const reservation = c.reserved
@@ -343,6 +367,14 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..9dc0c7a2303941079f2c3c4e66810544
}
}
+@@ -491,6 +616,7 @@ function parseOptions(a, b) {
+ onnotice : o.onnotice,
+ onnotify : o.onnotify,
+ onclose : o.onclose,
++ onpoisoned : o.onpoisoned,
+ onparameter : o.onparameter,
+ socket : o.socket,
+ transform : parseTransform(o.transform || { undefined: undefined }),
diff --git a/cjs/src/query.js b/cjs/src/query.js
index 45327f2fabcdbf8f8ec5020675012c310c04fee6..1d092504ac1ce1fdac78cb0c4ef3a8aa957676e4 100644
--- a/cjs/src/query.js
@@ -400,7 +432,7 @@ index 8438f5da92cf7637d98a33491d75c75b1c817c25..c444310ff87b0ac81fd19cd3170a0ba6
const out = xs[index++]
diff --git a/src/connection.js b/src/connection.js
-index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..617335d1b039866e86cd63872eeaf9ef7039a13c 100644
+index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..9a61cd9dcc9772e843842284e516641cb55178d0 100644
--- a/src/connection.js
+++ b/src/connection.js
@@ -78,6 +78,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
@@ -482,7 +514,15 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..617335d1b039866e86cd63872eeaf9ef
if (initial)
return reconnect()
-@@ -564,10 +579,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -533,6 +548,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ }
+
+ function ReadyForQuery(x) {
++ connection.status = x[5]
+ if (query) {
+ if (errorResponse) {
+ query.retried
+@@ -564,10 +580,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return fetchArrayTypes()
}
@@ -497,7 +537,7 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..617335d1b039866e86cd63872eeaf9ef
}
while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
-@@ -580,7 +597,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -580,7 +598,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
? !connection.reserved.release && x[5] === 73 // I
? ending
? terminate()
@@ -507,7 +547,7 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..617335d1b039866e86cd63872eeaf9ef
: ending
? terminate()
diff --git a/src/index.js b/src/index.js
-index c7fba3dace20173f4cb13f3f138bb6d213b43683..4c9192680a0da45fe13e1f06f1d8d05dcbe5a8a1 100644
+index c7fba3dace20173f4cb13f3f138bb6d213b43683..e9af339e13ee79e38d13fe82733ed17dc7529b46 100644
--- a/src/index.js
+++ b/src/index.js
@@ -200,40 +200,134 @@ function Postgres(a, b) {
@@ -590,7 +630,7 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..4c9192680a0da45fe13e1f06f1d8d05d
+ if (!busy) {
+ if (releasing) {
+ c.reserved = null
-+ onopen(c)
++ onopen(c, true)
+ } else {
+ move(c, reserved)
+ }
@@ -710,10 +750,14 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..4c9192680a0da45fe13e1f06f1d8d05d
}
}
-@@ -399,6 +497,11 @@ function Postgres(a, b) {
+@@ -398,7 +496,14 @@ function Postgres(a, b) {
+ move(c, ended)
}
- function onopen(c) {
+- function onopen(c) {
++ function onopen(c, released) {
++ if (c.status && c.status !== 73 && (released || options.max !== 1)) // not I
++ return poisoned(c)
+ if (ending) {
+ while (queries.length)
+ queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))
@@ -722,8 +766,20 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..4c9192680a0da45fe13e1f06f1d8d05d
if (queries.length === 0)
return move(c, open)
-@@ -420,10 +523,20 @@ function Postgres(a, b) {
+@@ -418,12 +523,32 @@ function Postgres(a, b) {
+ : move(c, full)
+ }
++ function poisoned(c) {
++ if (c.queue === ended)
++ return
++ move(c, ended)
++ try {
++ options.onpoisoned && options.onpoisoned(String.fromCharCode(c.status))
++ } catch (_) {}
++ c.terminate()
++ }
++
function onclose(c, e) {
move(c, closed)
+ const reservation = c.reserved
@@ -744,6 +800,14 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..4c9192680a0da45fe13e1f06f1d8d05d
}
}
+@@ -491,6 +616,7 @@ function parseOptions(a, b) {
+ onnotice : o.onnotice,
+ onnotify : o.onnotify,
+ onclose : o.onclose,
++ onpoisoned : o.onpoisoned,
+ onparameter : o.onparameter,
+ socket : o.socket,
+ transform : parseTransform(o.transform || { undefined: undefined }),
diff --git a/src/query.js b/src/query.js
index 0d44a15cd9e42beaf11d4be6ccde60223e09508a..96967780bdb55671bdcdda0fd0bb6e718e0a0e78 100644
--- a/src/query.js
@@ -801,10 +865,22 @@ index c4ef97164f057db99dce1b9af3401dbb1af37e31..8fba891b879e8f5c7fdb03ea05907536
const out = xs[index++]
diff --git a/types/index.d.ts b/types/index.d.ts
-index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..5d8903e3246e1f596e717019db76e87008b25bfc 100644
+index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..19103a998359c7277cd966c246cf245aedec4297 100644
--- a/types/index.d.ts
+++ b/types/index.d.ts
-@@ -605,7 +605,7 @@ declare namespace postgres {
+@@ -119,6 +119,11 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {
+ */
+ publications: string
+ onclose: (connId: number) => void;
++ /**
++ * Called when a pooled or released connection is terminated instead of
++ * reused because its ReadyForQuery status was not idle ('T' or 'E').
++ */
++ onpoisoned: (status: string) => void;
+ backoff: boolean | ((attemptNum: number) => number);
+ max_lifetime: number | null;
+ keep_alive: number | null;
+@@ -605,7 +610,7 @@ declare namespace postgres {
writable(): Promise<Writable>;
execute(): this;
@@ -813,7 +889,7 @@ index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..5d8903e3246e1f596e717019db76e870
/**
* @deprecated `.stream` has been renamed to `.forEach`
-@@ -659,6 +659,7 @@ declare namespace postgres {
+@@ -659,6 +664,7 @@ declare namespace postgres {
| Fragment[]
interface UnsafeQueryOptions {
@@ -821,7 +897,7 @@ index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..5d8903e3246e1f596e717019db76e870
/**
* When executes query as prepared statement.
* @default false
-@@ -717,10 +718,11 @@ declare namespace postgres {
+@@ -717,10 +723,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>>;
@@ -834,7 +910,7 @@ index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..5d8903e3246e1f596e717019db76e870
savepoint<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 +730,7 @@ declare namespace postgres {
+@@ -728,6 +735,7 @@ declare namespace postgres {
}
interface ReservedSql<TTypes extends Record<string, unknown> = {}> extends Sql<TTypes> {
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txt
index 297c9c6866..a38224ca18 100644
--- a/scripts/e2e-backend-matrix.txt
+++ b/scripts/e2e-backend-matrix.txt
@@ -45,3 +45,4 @@ test/e2e/projection-recovery-parity.test.ts
test/e2e/takes-scorecard-parity.test.ts
test/e2e/evidence-delivery-parity.test.ts
test/e2e/apply-migrations-orchestration-lock.test.ts
+test/e2e/postgres-poisoned-connection.test.ts
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 7d376a30e5..db040f7166 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -337,6 +337,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/unsupported-embedding-identity-postgres.test.ts",
"test/e2e/fixture-reset-postgres.test.ts",
"test/e2e/persistence-chaos.test.ts",
+ "test/e2e/postgres-poisoned-connection.test.ts",
"test/e2e/db-lock-acquisition-token.test.ts",
"test/e2e/chunk-canonical-text-privacy.test.ts",
"test/e2e/engine-content-privacy.test.ts",
@@ -473,7 +474,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/link-source-check-repair.ts": ["test/e2e/link-source-check-repair-postgres.test.ts"],
"src/core/vector-index.ts": ["test/e2e/migration-vector-replay-postgres.test.ts"],
// MCP stdio + HTTP transports share dispatch.
- "src/mcp/**": ["test/e2e/http-transport.test.ts", "test/e2e/mcp-search-transport-matrix.test.ts"],
+ "src/mcp/**": ["test/e2e/http-transport.test.ts", "test/e2e/mcp-search-transport-matrix.test.ts", "test/e2e/token-usage-skip-locked.test.ts"],
// Integrity batch-load fast path.
"src/commands/integrity.ts": ["test/e2e/integrity-batch.test.ts"],
// Upgrade chains migration ledger; touches both runners. The bun-link arc
@@ -519,7 +520,10 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// (per the plan-eng-review E1 decision); the daemon + built-in sources
// + ingest_capture Minion handler all feed the in-process roundtrip
// E2E AND the HTTP contract E2E for the webhook route.
- "src/core/oauth-provider.ts": ["test/e2e/oauth-grant-transactions.test.ts", "test/e2e/serve-http-oauth.test.ts"],
+ "src/core/oauth-provider.ts": ["test/e2e/oauth-grant-transactions.test.ts", "test/e2e/serve-http-oauth.test.ts", "test/e2e/token-usage-skip-locked.test.ts"],
+ // #5730: non-idle pooled connections are discarded by the vendored driver.
+ "vendor/postgres/**": ["test/e2e/postgres-poisoned-connection.test.ts", "test/e2e/persistence-chaos.test.ts"],
+ "src/core/pool-gauge.ts": ["test/e2e/postgres-poisoned-connection.test.ts"],
"src/core/oauth-grants.ts": ["test/e2e/oauth-grant-transactions.test.ts", "test/e2e/serve-http-consent.test.ts"],
"src/core/grants/lifecycle.ts": ["test/e2e/oauth-grant-transactions.test.ts", "test/e2e/serve-http-consent.test.ts"],
"src/commands/serve-http-clients.ts": ["test/e2e/serve-http-consent.test.ts"],
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index f18e97205a..787efa1833 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2230 ratchet +2: pre-publication withdrawal validation;
src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)
src/core/operations.ts 331 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration
src/core/pglite-engine.ts 3225 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166)
-src/core/postgres-engine.ts 3252 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156)
+src/core/postgres-engine.ts 3258 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts)
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
src/core/types.ts 2105 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch
src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys
diff --git a/src/core/backfill-base.ts b/src/core/backfill-base.ts
index 09faaebafb..4791a04cff 100644
--- a/src/core/backfill-base.ts
+++ b/src/core/backfill-base.ts
@@ -23,6 +23,33 @@ import { isStatementTimeoutError, isRetryableConnError } from './retry-matcher.t
// halving control flow stays intact (orthogonal to withRetry's per-call retry
// shape) — the unification is at the sleep primitive only, per codex H-6.
import { abortableSleep } from './retry.ts';
+import { GBrainError } from './types.ts';
+import { redactConnectionInfo } from './audit/redact-connection-info.ts';
+
+function brief(err: unknown): string {
+ const code = (err as { code?: unknown } | null)?.code;
+ const message = redactConnectionInfo(err instanceof Error ? err.message : String(err)).slice(0, 200);
+ return typeof code === 'string' ? `${code} ${message}` : message;
+}
+
+/**
+ * #5730: a failed batch whose ROLLBACK also failed. The reserved connection's
+ * transaction state is unknown, so the run stops instead of retrying on it;
+ * the driver discards the connection when it is released. Nothing from the
+ * batch was committed and the checkpoint was not advanced.
+ */
+export class BackfillRollbackError extends GBrainError {
+ readonly code = 'backfill_rollback_failed';
+ constructor(name: string, batchError: unknown, rollbackError: unknown) {
+ super(
+ `Backfill ${name} stopped: ROLLBACK of a failed batch also failed`,
+ `batch error: ${brief(batchError)}; rollback error: ${brief(rollbackError)}`,
+ `gbrain backfill ${name} --resume`,
+ 'docs/ENGINES.md#backfill-rollback-failed',
+ );
+ this.name = 'BackfillRollbackError';
+ }
+}
export interface BackfillSpec<TRow = Record<string, unknown>> {
/** Stable identifier — used in checkpoint key + CLI dispatch. */
@@ -260,11 +287,10 @@ export async function runBackfill<TRow = Record<string, unknown>>(
try {
await engine.withReservedConnection(async conn => {
await conn.executeRaw(`BEGIN`);
+ let batchUpdated = 0;
try {
if (engine.kind === 'postgres') {
- await conn.executeRaw(`SET LOCAL statement_timeout = '${perBatchTimeoutSec}s'`).catch(() => {
- /* some Postgres tiers restrict SET LOCAL; falls through */
- });
+ await conn.executeRaw(`SET LOCAL statement_timeout = '${perBatchTimeoutSec}s'`);
}
for (const { id, updates } of computedUpdates) {
const setClauses: string[] = [];
@@ -280,15 +306,21 @@ export async function runBackfill<TRow = Record<string, unknown>>(
`UPDATE ${spec.table} SET ${setClauses.join(', ')} WHERE ${idCol} = $1`,
params,
);
- updated++;
+ batchUpdated++;
}
await conn.executeRaw(`COMMIT`);
+ updated += batchUpdated;
} catch (err) {
- await conn.executeRaw(`ROLLBACK`).catch(() => {});
+ try {
+ await conn.executeRaw(`ROLLBACK`);
+ } catch (rollbackErr) {
+ throw new BackfillRollbackError(spec.name, err, rollbackErr);
+ }
throw err;
}
});
} catch (err) {
+ if (err instanceof BackfillRollbackError) throw err;
errors++;
if (errors >= maxErrors) break;
if (isStatementTimeoutError(err)) {
diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.ts
index 28665230ae..b966803337 100644
--- a/src/core/connection-manager.ts
+++ b/src/core/connection-manager.ts
@@ -71,6 +71,8 @@ export interface ConnectionManagerOpts {
* not call .end() on disconnect(). Default false (we own both pools).
*/
readPoolOwnedExternally?: boolean;
+ /** #5730: told when the driver discards a pooled connection left inside a transaction. */
+ onpoisoned?: (pool: 'read' | 'direct', status: string) => void;
}
/** Default direct-pool size (P1 raised from 2 to 3). Override via env. */
@@ -348,6 +350,7 @@ export class ConnectionManager {
// Explicit (matches the postgres.js implicit default; GBRAIN_POOL_MAX_LIFETIME_S overrides).
max_lifetime: resolveMaxLifetimeSeconds(),
types: { bigint: postgres.BigInt },
+ onpoisoned: (status: string) => this.opts.onpoisoned?.('read', status),
};
const timeouts = resolveSessionTimeouts();
if (Object.keys(timeouts).length > 0) opts.connection = timeouts;
@@ -497,6 +500,7 @@ export class ConnectionManager {
// Always use prepared statements on the direct pool — no PgBouncer
// here, so the prepare-cache invalidation issue doesn't apply.
prepare: true,
+ onpoisoned: (status: string) => this.opts.onpoisoned?.('direct', status),
// Apply DDL session GUCs as connection startup parameters (durable
// through any intermediary pooling layer, same trick as
// resolveSessionTimeouts).
diff --git a/src/core/db.ts b/src/core/db.ts
index ce838b8ec9..a1c86a664e 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -265,7 +265,7 @@ export function getConnection(): ReturnType<typeof postgres> {
*
* Back-compat: callers that ignore the return value are unaffected.
*/
-export async function connect(config: EngineConfig): Promise<boolean> {
+export async function connect(config: EngineConfig, hooks: { onpoisoned?: (status: string) => void } = {}): Promise<boolean> {
if (sql) {
// Warn if a different URL is passed — the old connection is still in use
if (config.database_url && connectedUrl && config.database_url !== connectedUrl) {
@@ -301,6 +301,7 @@ export async function connect(config: EngineConfig): Promise<boolean> {
// during migrations + initSchema, and breaks stdout-parsing callers like
// `gbrain jobs submit --json | ...`). Opt back in with GBRAIN_PG_NOTICES=1.
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
+ onpoisoned: hooks.onpoisoned,
};
if (Object.keys(timeouts).length > 0) {
opts.connection = timeouts;
diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.ts
index 71836ea265..565d39a4af 100644
--- a/src/core/oauth-provider.ts
+++ b/src/core/oauth-provider.ts
@@ -932,12 +932,12 @@ export class GBrainOAuthProvider implements OAuthServerProvider {
// once per token per 60s, and NEVER blocks or fails verification (a
// slow/broken UPDATE used to hang or 401 every legacy-token request).
// Mirrors src/mcp/http-transport.ts validateToken; the SQL-level WHERE
- // keeps the debounce race-tolerant under concurrent requests.
+ // keeps the debounce race-tolerant under concurrent requests; SKIP LOCKED
+ // keeps a row lock held elsewhere from parking a pool slot (#5730).
this.sql`
- UPDATE access_tokens
- SET last_used_at = now()
- WHERE token_hash = ${tokenHash}
- AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds')
+ UPDATE access_tokens SET last_used_at = now()
+ WHERE id IN (SELECT id FROM access_tokens WHERE token_hash = ${tokenHash}
+ AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds') FOR UPDATE SKIP LOCKED)
`.catch(() => { /* fire-and-forget */ });
const name = legacyRows[0].name as string;
const permissions = coerceLegacyPermissions(legacyRows[0].permissions);
diff --git a/src/core/pool-gauge.ts b/src/core/pool-gauge.ts
index bb358c5ffc..3168873f6d 100644
--- a/src/core/pool-gauge.ts
+++ b/src/core/pool-gauge.ts
@@ -46,3 +46,29 @@ export class CheckoutGauge {
return { ...this.counts };
}
}
+
+/**
+ * #5730: pooled connections the vendored driver terminated instead of reusing
+ * because their ReadyForQuery status was not idle (`T` inside a transaction,
+ * `E` inside a failed one). Each discard is counted once and logged as one
+ * fixed-shape warn line; the status byte is the only driver-supplied value.
+ */
+export class PoisonedDiscardCounter {
+ private discards = 0;
+
+ get count(): number {
+ return this.discards;
+ }
+
+ record(pool: 'read' | 'direct', status: string): void {
+ this.discards += 1;
+ try { console.warn(formatPoisonedDiscardWarning(pool, status)); } catch { /* best-effort */ }
+ }
+}
+
+export function formatPoisonedDiscardWarning(pool: 'read' | 'direct', status: string): string {
+ const byte = /^[A-Z]$/.test(status) ? status : '?';
+ return `[gbrain] warn code=pg_connection_poisoned status=${byte} pool=${pool}` +
+ ` cause="a connection came back to the pool inside a transaction; it was discarded and replaced"` +
+ ` fix="gbrain doctor --json" docs=docs/ENGINES.md#pg-connection-poisoned`;
+}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 8abd7b1091..274a37f5c4 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -40,7 +40,7 @@ import {
type BatchAuditSite,
} from './retry.ts';
import { isConnectionEndedError } from './retry-matcher.ts';
-import { CheckoutGauge, type PoolGaugeSnapshot } from './pool-gauge.ts';
+import { CheckoutGauge, PoisonedDiscardCounter, type PoolGaugeSnapshot } from './pool-gauge.ts';
import {
valueHash,
normalizeDimension,
@@ -187,6 +187,8 @@ export class PostgresEngine implements BrainEngine {
* via the prototype chain (same process, same pools). Fail-open.
*/
private checkoutGauge = new CheckoutGauge();
+ private poisonedDiscards = new PoisonedDiscardCounter();
+ private readonly onPoisoned = (pool: 'read' | 'direct', status: string) => this.poisonedDiscards.record(pool, status);
/**
* #1471: module-singleton OWNERSHIP token. `true` only for the engine whose
* connect() actually created the shared db.ts `sql` singleton (returned
@@ -368,6 +370,7 @@ export class PostgresEngine implements BrainEngine {
// idempotent CREATE migrations flood stdout). Opt back in with
// GBRAIN_PG_NOTICES=1.
onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},
+ onpoisoned: (status: string) => this.onPoisoned('read', status),
};
if (Object.keys(timeouts).length > 0) {
opts.connection = timeouts;
@@ -387,6 +390,7 @@ export class PostgresEngine implements BrainEngine {
url,
parent: config.parentConnectionManager,
readPoolOwnedExternally: true, // we own _sql; manager just routes
+ onpoisoned: this.onPoisoned,
});
this.connectionManager.setReadPool(this._sql);
} else {
@@ -395,7 +399,7 @@ export class PostgresEngine implements BrainEngine {
// decided atomically inside connect() (no await between its null-check and
// pool assignment), so two concurrent module connects can't both claim
// ownership. Store the token; only the owner tears the singleton down.
- this._ownsModuleSingleton = await db.connect(config);
+ this._ownsModuleSingleton = await db.connect(config, { onpoisoned: status => this.onPoisoned('read', status) });
this._connectionStyle = 'module';
// v0.30.1: connection-manager wraps the module singleton.
@@ -404,6 +408,7 @@ export class PostgresEngine implements BrainEngine {
url,
parent: config.parentConnectionManager,
readPoolOwnedExternally: true, // db.ts owns the pool
+ onpoisoned: this.onPoisoned,
});
this.connectionManager.setReadPool(db.getConnection());
}
@@ -676,12 +681,13 @@ export class PostgresEngine implements BrainEngine {
* it optionally, same pattern as `engine.reconnect`). Fail-open: returns
* null instead of throwing.
*/
- getPoolDiagnostics(): { tracked: PoolGaugeSnapshot; poolMax: number | null } | null {
+ getPoolDiagnostics(): { tracked: PoolGaugeSnapshot; poolMax: number | null; poisonedDiscards: number } | null {
try {
const max = (this.sql as unknown as { options?: { max?: number } }).options?.max;
return {
tracked: this.checkoutGauge.snapshot(),
poolMax: typeof max === 'number' ? max : null,
+ poisonedDiscards: this.poisonedDiscards?.count ?? 0,
};
} catch {
return null;
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index da9934738a..b1c63b8bce 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -260,11 +260,11 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
const rowId = row.id as string;
const rowName = row.name as string;
// Debounced last_used_at update — only writes once per token per 60s.
- // SQL-level WHERE clause keeps this race-tolerant even under concurrent requests.
- sql`UPDATE access_tokens
- SET last_used_at = now()
- WHERE id = ${rowId}
- AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds')`
+ // SQL-level WHERE clause keeps this race-tolerant even under concurrent requests;
+ // SKIP LOCKED keeps a row lock held elsewhere from parking a pool slot (#5730).
+ sql`UPDATE access_tokens SET last_used_at = now()
+ WHERE id IN (SELECT id FROM access_tokens WHERE id = ${rowId}
+ AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds') FOR UPDATE SKIP LOCKED)`
.catch(() => { /* fire-and-forget */ });
// v0.28: extract per-token takes-holder allow-list. Fail-safe default
// is ['world'] — a token with no permissions row sees public claims only.
diff --git a/test/backfill-base.test.ts b/test/backfill-base.test.ts
index 832c5f1711..d21aa6f628 100644
--- a/test/backfill-base.test.ts
+++ b/test/backfill-base.test.ts
@@ -146,6 +146,71 @@ describe('runBackfill — error handling', () => {
});
});
+/**
+ * #5730: a write batch runs inside BEGIN on a reserved connection. Its
+ * statements are buffered and applied only on COMMIT, like a real backend,
+ * and `fail` injects one error per statement prefix.
+ */
+class TransactionalFakeEngine extends FakeEngine {
+ fail = new Map<string, Error>();
+ private pending: number[] | null = null;
+
+ override async executeRaw<T = unknown>(sql: string, params?: unknown[]): Promise<T[]> {
+ const injected = [...this.fail.entries()].find(([prefix]) => sql.startsWith(prefix));
+ if (injected) {
+ this.fail.delete(injected[0]);
+ throw injected[1];
+ }
+ if (sql === 'BEGIN') { this.pending = []; return []; }
+ if (sql === 'ROLLBACK') { this.pending = null; return []; }
+ if (sql === 'COMMIT') {
+ for (const id of this.pending ?? []) await super.executeRaw(`UPDATE pages`, [id]);
+ this.pending = null;
+ return [];
+ }
+ if (sql.startsWith('UPDATE') && this.pending) { this.pending.push(params?.[0] as number); return []; }
+ return super.executeRaw<T>(sql, params);
+ }
+}
+
+const sqlError = (code: string, message: string) => Object.assign(new Error(message), { code });
+
+describe('runBackfill — transaction failures (#5730)', () => {
+ test('a failed ROLLBACK stops the run with a typed error naming both failures', async () => {
+ const engine = new TransactionalFakeEngine();
+ engine.rows = [{ id: 1, needs_backfill: true }];
+ engine.fail.set('UPDATE', sqlError('23505', 'duplicate key value'));
+ engine.fail.set('ROLLBACK', sqlError('08006', 'connection failure'));
+ const error = await runBackfill(engine as never, makeSpec(), { batchSize: 10 }).catch(e => e);
+ expect(error.name).toBe('BackfillRollbackError');
+ expect(error.code).toBe('backfill_rollback_failed');
+ expect(error.message).toContain('batch error: 23505 duplicate key value');
+ expect(error.message).toContain('rollback error: 08006 connection failure');
+ expect(error.fix).toBe('gbrain backfill test_backfill --resume');
+ expect(engine.rows[0].needs_backfill).toBe(true);
+ expect(engine.config.get('backfill.test_backfill.last_id')).toBeUndefined();
+ });
+
+ test('a failed SET LOCAL aborts the batch instead of running it in an aborted transaction', async () => {
+ const engine = new TransactionalFakeEngine();
+ engine.rows = [{ id: 1, needs_backfill: true }];
+ engine.fail.set('SET LOCAL', sqlError('42501', 'permission denied to set parameter'));
+ const error = await runBackfill(engine as never, makeSpec(), { batchSize: 10 }).catch(e => e);
+ expect(error?.code).toBe('42501');
+ expect(engine.rows[0].needs_backfill).toBe(true);
+ });
+
+ test('rows of a rolled-back batch are not counted as updated', async () => {
+ const engine = new TransactionalFakeEngine();
+ engine.rows = [{ id: 1, needs_backfill: true }, { id: 2, needs_backfill: true }];
+ engine.fail.set('COMMIT', sqlError('57014', 'canceling statement due to statement timeout'));
+ const result = await runBackfill(engine as never, makeSpec(), { batchSize: 10 });
+ expect(result.errors).toBe(1);
+ expect(result.updated).toBe(2);
+ expect(engine.rows.every(r => !r.needs_backfill)).toBe(true);
+ });
+});
+
describe('clearBackfillCheckpoint', () => {
test('removes the config key', async () => {
const engine = new FakeEngine();
diff --git a/test/e2e/postgres-poisoned-connection.test.ts b/test/e2e/postgres-poisoned-connection.test.ts
new file mode 100644
index 0000000000..512c31955d
--- /dev/null
+++ b/test/e2e/postgres-poisoned-connection.test.ts
@@ -0,0 +1,146 @@
+/**
+ * #5730: a pooled or released connection whose ReadyForQuery status is not idle
+ * (`T` in a transaction, `E` in a failed transaction) must never serve another
+ * caller. Before the driver fix such a connection returned to the pool, so one
+ * leaked transaction turned every later pooled statement into 25P02 until the
+ * process restarted.
+ *
+ * Protects: the next pooled statement after a leaked transaction runs outside
+ * it; the driver reports each discard through `onpoisoned`; the engine counts
+ * it in `getPoolDiagnostics().poisonedDiscards` and logs one redacted warn line.
+ * Regression that fails it: returning a non-idle connection to the pool on
+ * either the pooled ReadyForQuery path or the reserved-release path.
+ * Existing coverage (persistence-chaos) pins cancellation ownership only.
+ */
+import { afterEach, describe, expect, spyOn, test } from 'bun:test';
+import { createRequire } from 'node:module';
+import postgres from '#postgres';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+
+const url = process.env.DATABASE_URL;
+const opened: Array<{ end: (o?: { timeout?: number }) => Promise<void> }> = [];
+
+afterEach(async () => {
+ while (opened.length) await opened.pop()!.end({ timeout: 1 }).catch(() => {});
+});
+
+function pool(max: number, statuses: string[], driver: typeof postgres = postgres, appName = `gbrain-5730-${Math.random().toString(36).slice(2)}`) {
+ assertSafeE2eDatabaseUrl(url!);
+ const sql = driver(url!, {
+ max,
+ onnotice: () => {},
+ connection: { application_name: appName },
+ onpoisoned: (status: string) => { statuses.push(status); },
+ } as Parameters<typeof postgres>[1]);
+ opened.push(sql);
+ return { sql, appName };
+}
+
+function failure(query: PromiseLike<unknown>): Promise<{ code?: string }> {
+ return Promise.resolve(query).then(() => ({ code: 'resolved' }), (error: { code?: string }) => error);
+}
+
+async function autocommit(sql: postgres.Sql): Promise<boolean> {
+ const [a] = await sql`SELECT txid_current()::text AS x`;
+ const [b] = await sql`SELECT txid_current()::text AS x`;
+ return a.x !== b.x;
+}
+
+async function idleInTransaction(observer: postgres.Sql, appName: string): Promise<number> {
+ const [row] = await observer`
+ SELECT count(*)::int AS n FROM pg_stat_activity
+ WHERE application_name = ${appName} AND state LIKE 'idle in transaction%'`;
+ return row.n as number;
+}
+
+describe.skipIf(!url)('#5730 poisoned pooled connections are discarded', () => {
+ test('reservation released inside a failed transaction (pool of 1) does not poison the next query', async () => {
+ const statuses: string[] = [];
+ const { sql } = pool(1, statuses);
+ const reserved = await sql.reserve();
+ await reserved`BEGIN`;
+ expect((await failure(reserved`SELECT 1/0`)).code).toBe('22012');
+ reserved.release();
+ expect(await autocommit(sql)).toBe(true);
+ expect(statuses).toEqual(['E']);
+ });
+
+ test('a query queued behind the discarded connection runs on a fresh connection', async () => {
+ const statuses: string[] = [];
+ const { sql } = pool(1, statuses);
+ const reserved = await sql.reserve();
+ const queued = sql`SELECT 2 AS ok`.execute();
+ await reserved`BEGIN`;
+ reserved.release();
+ expect((await queued)[0]).toEqual({ ok: 2 });
+ expect(await autocommit(sql)).toBe(true);
+ expect(statuses).toEqual(['T']);
+ });
+
+ test('pooled connection left in a transaction by a rejected BEGIN never serves later statements', async () => {
+ const statuses: string[] = [];
+ const { sql, appName } = pool(2, statuses);
+ const observer = postgres(url!, { max: 1, onnotice: () => {} });
+ opened.push(observer);
+ expect((await failure(sql.unsafe('BEGIN'))).code).toBe('UNSAFE_TRANSACTION');
+ for (let i = 0; i < 6; i++) {
+ expect((await failure(sql`SELECT 1/0`)).code).toBe('22012');
+ const [row] = await sql`SELECT ${i}::int AS i`;
+ expect(row).toEqual({ i });
+ }
+ expect(await idleInTransaction(observer, appName)).toBe(0);
+ expect(statuses).toEqual(['T']);
+ });
+
+ test('CommonJS build applies the same discard', async () => {
+ const cjs = createRequire(import.meta.url)('#postgres') as typeof postgres;
+ expect(cjs).not.toBe(postgres);
+ const statuses: string[] = [];
+ const { sql } = pool(1, statuses, cjs);
+ const reserved = await sql.reserve();
+ await reserved`BEGIN`;
+ reserved.release();
+ expect(await autocommit(sql)).toBe(true);
+ expect(statuses).toEqual(['T']);
+ });
+
+ test('a max-1 pool keeps the documented raw BEGIN idiom', async () => {
+ const statuses: string[] = [];
+ const { sql } = pool(1, statuses);
+ await sql`BEGIN`;
+ const [a] = await sql`SELECT txid_current()::text AS x`;
+ const [b] = await sql`SELECT txid_current()::text AS x`;
+ await sql`COMMIT`;
+ expect(a.x).toBe(b.x);
+ expect(statuses).toEqual([]);
+ });
+
+ test('engine (pool of 2, the long-hold minimum) counts each discard once and logs one redacted warn line', async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const engine = new PostgresEngine();
+ await engine.connect({ engine: 'postgres', database_url: url!, poolSize: 2 });
+ const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ await engine.withReservedConnection(async conn => {
+ await conn.executeRaw('BEGIN');
+ expect((await failure(conn.executeRaw('SELECT 1/0'))).code).toBe('22012');
+ });
+ const ids = new Set<string>();
+ for (let i = 0; i < 4; i++) {
+ const rows = await engine.executeRaw<{ x: string }>('SELECT txid_current()::text AS x');
+ ids.add(rows[0].x);
+ }
+ expect(ids.size).toBe(4);
+ expect(engine.getPoolDiagnostics()?.poisonedDiscards).toBe(1);
+ const lines = warn.mock.calls.map(c => String(c[0])).filter(l => l.includes('pg_connection_poisoned'));
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toContain('status=E');
+ expect(lines[0]).not.toContain(url!);
+ expect(lines[0].length).toBeLessThanOrEqual(400);
+ } finally {
+ warn.mockRestore();
+ await engine.disconnect();
+ }
+ });
+});
diff --git a/test/e2e/token-usage-skip-locked.test.ts b/test/e2e/token-usage-skip-locked.test.ts
new file mode 100644
index 0000000000..7877488690
--- /dev/null
+++ b/test/e2e/token-usage-skip-locked.test.ts
@@ -0,0 +1,87 @@
+/**
+ * #5730: the debounced legacy-token `last_used_at` UPDATE is fire-and-forget,
+ * so a row lock held elsewhere never delayed verification, but the UPDATE
+ * itself parked a pooled connection on the lock until statement_timeout.
+ * Both sites (OAuth provider legacy fallback and the legacy HTTP transport)
+ * now skip a locked row.
+ *
+ * Protects: a locked token row leaves no backend waiting on that lock after
+ * authentication. Regression that fails it: dropping SKIP LOCKED from either
+ * UPDATE. Existing coverage checks the 60 s debounce only.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomBytes } from 'node:crypto';
+import postgres from '#postgres';
+import { startHttpTransport } from '../../src/mcp/http-transport.ts';
+import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../../src/core/sql-query.ts';
+import { hashToken } from '../../src/core/utils.ts';
+import { hasDatabase, setupDB, teardownDB, getEngine, getConn } from './helpers.ts';
+
+const describeE2E = hasDatabase() ? describe : describe.skip;
+
+describeE2E('#5730 token usage UPDATE skips a locked row', () => {
+ let locker: postgres.Sql;
+ let release: (() => void) | null = null;
+
+ beforeAll(async () => {
+ await setupDB();
+ locker = postgres(process.env.DATABASE_URL!, { max: 1, onnotice: () => {} });
+ });
+ afterEach(() => { release?.(); release = null; });
+ afterAll(async () => {
+ await locker?.end({ timeout: 1 });
+ await teardownDB();
+ });
+
+ async function seedLockedToken(): Promise<string> {
+ const token = 'gbrain_test_' + randomBytes(16).toString('hex');
+ await getConn().unsafe('INSERT INTO access_tokens (name, token_hash) VALUES ($1, $2)',
+ ['skip-locked-' + randomBytes(4).toString('hex'), hashToken(token)]);
+ let locked!: () => void;
+ const held = new Promise<void>(resolve => { locked = resolve; });
+ const done = new Promise<void>(resolve => { release = resolve; });
+ void locker.begin(async tx => {
+ await tx`SELECT id FROM access_tokens WHERE token_hash = ${hashToken(token)} FOR UPDATE`;
+ locked();
+ await done;
+ });
+ await held;
+ return token;
+ }
+
+ async function backendsWaitingOnTokenUpdate(): Promise<number> {
+ await Bun.sleep(400);
+ const rows = await getConn().unsafe(`
+ SELECT count(*)::int AS n FROM pg_stat_activity
+ WHERE wait_event_type = 'Lock' AND query ILIKE '%UPDATE access_tokens%'`);
+ return rows[0].n as number;
+ }
+
+ test('OAuth provider legacy-token fallback', async () => {
+ const engine = getEngine();
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const token = await seedLockedToken();
+ const started = Date.now();
+ const auth = await provider.verifyAccessToken(token);
+ expect(Date.now() - started).toBeLessThan(2_000);
+ expect(auth.token).toBe(token);
+ expect(await backendsWaitingOnTokenUpdate()).toBe(0);
+ });
+
+ test('legacy HTTP transport bearer validation', async () => {
+ const server = await startHttpTransport({ port: 0, engine: getEngine() as never });
+ try {
+ const token = await seedLockedToken();
+ const res = await fetch(`http://localhost:${(server as { port: number }).port}/mcp`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
+ });
+ expect(res.status).toBe(200);
+ expect(await backendsWaitingOnTokenUpdate()).toBe(0);
+ } finally {
+ (server as { stop: (force: boolean) => void }).stop(true);
+ }
+ });
+});
diff --git a/test/postgres-driver-vendor.test.ts b/test/postgres-driver-vendor.test.ts
index 8e6255922c..0f8e7941e0 100644
--- a/test/postgres-driver-vendor.test.ts
+++ b/test/postgres-driver-vendor.test.ts
@@ -33,6 +33,7 @@ describe('vendored Postgres driver packaging', () => {
expect(index).toContain('async function reserve({ signal } = {})');
expect(index).toContain('sql.discard = reservation.discard');
expect(index).toContain('completed.cancelPromise');
+ expect(index).toContain('return poisoned(c)');
}
});
});
diff --git a/vendor/README.md b/vendor/README.md
index 39d9642da6..4aff181daa 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -29,7 +29,10 @@ postinstall mutation of another package's node_modules is needed. The patch
file remains the auditable source of the delta, not an installation hook.
The patch adds abort-aware reservation, reserved/transaction-owner discard,
-CancelRequest settlement tracking and ownership/pipeline fences. Cancellation
+CancelRequest settlement tracking and ownership/pipeline fences. It also
+terminates, instead of reusing, a pooled connection or released reservation
+whose last ReadyForQuery status is not idle, and reports each discard through
+the `onpoisoned(status)` option (#5730). Cancellation
must settle or retire the connection before another query can own it. This
is necessary for worker admission, query timeout and lease-release safety.
See issues #5466 and #5560 and `test/e2e/persistence-chaos.test.ts`.
diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.js
index 1be82d1976..c893205f90 100644
--- a/vendor/postgres/cf/src/connection.js
+++ b/vendor/postgres/cf/src/connection.js
@@ -550,6 +550,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function ReadyForQuery(x) {
+ connection.status = x[5]
if (query) {
if (errorResponse) {
query.retried
diff --git a/vendor/postgres/cf/src/index.js b/vendor/postgres/cf/src/index.js
index 43b8b091a8..fa294e7960 100644
--- a/vendor/postgres/cf/src/index.js
+++ b/vendor/postgres/cf/src/index.js
@@ -274,7 +274,7 @@ function Postgres(a, b) {
if (!busy) {
if (releasing) {
c.reserved = null
- onopen(c)
+ onopen(c, true)
} else {
move(c, reserved)
}
@@ -497,7 +497,9 @@ function Postgres(a, b) {
move(c, ended)
}
- function onopen(c) {
+ function onopen(c, released) {
+ if (c.status && c.status !== 73 && (released || options.max !== 1)) // not I
+ return poisoned(c)
if (ending) {
while (queries.length)
queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))
@@ -522,6 +524,16 @@ function Postgres(a, b) {
: move(c, full)
}
+ function poisoned(c) {
+ if (c.queue === ended)
+ return
+ move(c, ended)
+ try {
+ options.onpoisoned && options.onpoisoned(String.fromCharCode(c.status))
+ } catch (_) {}
+ c.terminate()
+ }
+
function onclose(c, e) {
move(c, closed)
const reservation = c.reserved
@@ -605,6 +617,7 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
+ onpoisoned : o.onpoisoned,
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.js
index be36dfd08e..e5800bca79 100644
--- a/vendor/postgres/cjs/src/connection.js
+++ b/vendor/postgres/cjs/src/connection.js
@@ -548,6 +548,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function ReadyForQuery(x) {
+ connection.status = x[5]
if (query) {
if (errorResponse) {
query.retried
diff --git a/vendor/postgres/cjs/src/index.js b/vendor/postgres/cjs/src/index.js
index 9dc0c7a230..c72e413562 100644
--- a/vendor/postgres/cjs/src/index.js
+++ b/vendor/postgres/cjs/src/index.js
@@ -273,7 +273,7 @@ function Postgres(a, b) {
if (!busy) {
if (releasing) {
c.reserved = null
- onopen(c)
+ onopen(c, true)
} else {
move(c, reserved)
}
@@ -496,7 +496,9 @@ function Postgres(a, b) {
move(c, ended)
}
- function onopen(c) {
+ function onopen(c, released) {
+ if (c.status && c.status !== 73 && (released || options.max !== 1)) // not I
+ return poisoned(c)
if (ending) {
while (queries.length)
queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))
@@ -521,6 +523,16 @@ function Postgres(a, b) {
: move(c, full)
}
+ function poisoned(c) {
+ if (c.queue === ended)
+ return
+ move(c, ended)
+ try {
+ options.onpoisoned && options.onpoisoned(String.fromCharCode(c.status))
+ } catch (_) {}
+ c.terminate()
+ }
+
function onclose(c, e) {
move(c, closed)
const reservation = c.reserved
@@ -604,6 +616,7 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
+ onpoisoned : o.onpoisoned,
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.js
index 617335d1b0..9a61cd9dcc 100644
--- a/vendor/postgres/src/connection.js
+++ b/vendor/postgres/src/connection.js
@@ -548,6 +548,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function ReadyForQuery(x) {
+ connection.status = x[5]
if (query) {
if (errorResponse) {
query.retried
diff --git a/vendor/postgres/src/index.js b/vendor/postgres/src/index.js
index 4c9192680a..e9af339e13 100644
--- a/vendor/postgres/src/index.js
+++ b/vendor/postgres/src/index.js
@@ -273,7 +273,7 @@ function Postgres(a, b) {
if (!busy) {
if (releasing) {
c.reserved = null
- onopen(c)
+ onopen(c, true)
} else {
move(c, reserved)
}
@@ -496,7 +496,9 @@ function Postgres(a, b) {
move(c, ended)
}
- function onopen(c) {
+ function onopen(c, released) {
+ if (c.status && c.status !== 73 && (released || options.max !== 1)) // not I
+ return poisoned(c)
if (ending) {
while (queries.length)
queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))
@@ -521,6 +523,16 @@ function Postgres(a, b) {
: move(c, full)
}
+ function poisoned(c) {
+ if (c.queue === ended)
+ return
+ move(c, ended)
+ try {
+ options.onpoisoned && options.onpoisoned(String.fromCharCode(c.status))
+ } catch (_) {}
+ c.terminate()
+ }
+
function onclose(c, e) {
move(c, closed)
const reservation = c.reserved
@@ -604,6 +616,7 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
+ onpoisoned : o.onpoisoned,
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
diff --git a/vendor/postgres/types/index.d.ts b/vendor/postgres/types/index.d.ts
index 5d8903e324..19103a9983 100644
--- a/vendor/postgres/types/index.d.ts
+++ b/vendor/postgres/types/index.d.ts
@@ -119,6 +119,11 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {
*/
publications: string
onclose: (connId: number) => void;
+ /**
+ * Called when a pooled or released connection is terminated instead of
+ * reused because its ReadyForQuery status was not idle ('T' or 'E').
+ */
+ onpoisoned: (status: string) => void;
backoff: boolean | ((attemptNum: number) => number);
max_lifetime: number | null;
keep_alive: number | null;