Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): a cancelled statement a transaction-mode pooler never completes is discarded client-side at the settle window; the consumer phase ends deadline_exceeded and keeps ticking (#6278)

garrytan3de15a55814d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 89f7387926..d9157e290f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,43 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.114.0] - 2026-10-08
+
+**A write owner no longer parks forever on a database round-trip that a transaction-mode pooler never completes.**
+
+On the managed brain behind the #6278 report, one `gbrain sync` with no lanes and no `serve` still stopped after 45 pages: the consumer's `expired_claims` statement sat with its Postgres backend in `ClientRead` through Supavisor's transaction pooler (port 6543), the owner's 5 s phase deadline fired, but the cancel request never reached the backend and the awaited promise never settled, so the owner was parked until the watchdog. The same command on the session-mode URL (port 5432) drained cleanly. Now a cancelled statement that is still unsettled `GBRAIN_CANCEL_SETTLE_MS` (default 2000 ms) after its cancel request has its reserved connection discarded, which settles the promise client-side; the phase ends `deadline_exceeded`, the consumer keeps ticking and the catch-up continues.
+
+### How to use it
+
+```bash
+gbrain sync --source <id> --no-pull --no-embed # nothing to change
+gbrain doctor --only persistence_session_timeouts --json # names a transaction-mode pooler URL and the session-mode alternative
+GBRAIN_CANCEL_SETTLE_MS=5000 gbrain serve # a longer settle window if a slow pooler honours cancels late
+```
+
+### What you see
+
+| Where | What changed |
+|---|---|
+| A consumer phase whose statement never completes | Ends as `deadline_exceeded` once (the connection is discarded after the settle window), never as `storage_error` / `CONNECTION_DESTROYED`; the next tick runs and the drain proceeds. |
+| A preparation read ended that way | Classified as the preparation deadline (released `preparation_deadline`, counted toward `preparation_stalled`), with the step and `waiting_on: db` on the claim. |
+| doctor `persistence_session_timeouts` | Warns `transaction_mode_pooler` when the configured URL is a transaction-mode pooler even if the session timeout reaches the server, and names the port 5432 session-mode URL as the alternative for the persistence owner. |
+
+### Things to watch
+
+- **Interim mitigation that works today:** point the persistence owner (`gbrain sync`, `gbrain serve`) at the session-mode URL of the same pooler (Supabase: port 5432). That is the configuration the reporter measured as the longest clean drain in weeks.
+- **A discarded connection is a reconnect**, not a lost write: the statement's request stays claimed or queued and is retried on the next tick; the pooler's backend is released when the client socket closes.
+
+### Itemized changes
+
+- `src/core/postgres-engine.ts`: `runUnsafe` arms a settle timer after `cancel()`; a statement still pending at `cancelSettleMs()` has its reserved connection discarded (`CONNECTION_DESTROYED`), once. `GBRAIN_CANCEL_SETTLE_MS` (>= 100) overrides the 2 s default.
+- `src/core/persistence/consumer.ts`: a phase past its deadline that ends with 57014, `CONNECTION_DESTROYED` or `CONNECTION_CLOSED` throws `PhaseDeadlineError` (`code: deadline_exceeded`); `report()` records it under the phase without a second log line.
+- `src/core/persistence/bounded-reads.ts` and `coordinator.ts`: a discarded connection after the budget is the preparation deadline, never `storage_error` or `database_contention`.
+- Doctor `persistence_session_timeouts` gains the `transaction_mode_pooler` warning (`resolvePrepare(url) === false`).
+- Tests: `test/postgres-engine-cancel-settle.test.ts` (never-settling statement is discarded at the window; a honoured cancel is not), `test/persistence-consumer-log.test.ts` (the consumer logs one `deadline_exceeded`, no `storage_error`, and ticks again), `test/e2e/persistence-pooler-wedge-postgres.test.ts` (a wedged `expired_claims` statement inside a real 60-page managed catch-up: cancel swallowed, discarded at the window, the run drains `synced`; hangs on the previous release).
+
+Refs #6278 (the mechanism behind the never-settling `preparing` wedge); the two-consumer and direct-URL work continues in #6317.
+
## [0.60.113.0] - 2026-10-08
**Fence repair and chronicle now run while a sync is in progress, and a refused owner check says exactly which host or state is in the way.**
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 0177344ce9..7117ae0cc0 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -665,6 +665,14 @@ one after `n` milliseconds (a saturated pool or pooler, not a slow query); and
`loop_lag_ms` is the longest event-loop delay during the phase (a busy or
starved process). The same fields appear in the consumer's status snapshot
under `phase`. Unfinished work stays tracked and is retried; nothing is lost. Run `gbrain sources writer status --json` to see what is waiting.
+A `deadline_exceeded` phase is also how a round-trip a transaction-mode pooler
+(Supavisor port 6543, PgBouncer) never completed ends: the backend sits in
+`ClientRead`, the cancel request the deadline sends may never reach it, so
+`GBRAIN_CANCEL_SETTLE_MS` (default 2000) after the cancel the owner discards
+that reserved connection, the statement settles client-side, and the next tick
+runs. The connection end is not reported as `storage_error`; doctor's
+`persistence_session_timeouts` names a transaction-mode URL, and the
+session-mode URL of the same pooler (Supabase: port 5432) avoids the class.
`phase=preparation` lines name a write whose preparation ran past its budget:
`reason=deadline_exceeded` (the claim is released with `blocked_reason`
`preparation_deadline` and one attempt is counted; the budget is
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index dc891f4a5f..02f0f065f3 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -35,7 +35,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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`. `onCheckout(listener)` (exposed as `PostgresEngine.onCheckout`) fires after a connection is actually obtained: signalled raw reserve resolution, transaction-callback entry and `withReservedConnection` reserve resolution; it never fires for a call still waiting (pinned by `test/e2e/postgres-checkout-observer.test.ts`).
-- `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. Every search transaction (keyword, keyword chunks, CJK, title, the vector attempts and the vector `hasMore` witness) also passes `jitOff` and runs with `jit = off` (`postgres-engine/search-settings.ts`): the correlated visibility subplans push these short reads past the JIT cost thresholds, and LLVM compilation, not execution, dominated their latency on large brains. Inside a caller's transaction the search runs in a savepoint and restores the caller's `jit` afterwards. Pinned by `test/e2e/search-query-contract-postgres.test.ts`. `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). When the DDL pool has more than one slot, `initSchema` reserves one backend and runs the advisory lock 42 acquire, the bootstrap, the schema replay and the unlock on it, releasing it in `finally` (checkout gauge only, no long-hold permit, so pending `transaction: false` migrations can still reserve); a one-slot pool is already a single backend and runs unreserved. Pinned by `test/e2e/postgres-initschema-advisory-lock.test.ts`. `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)`).
+- `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. Every search transaction (keyword, keyword chunks, CJK, title, the vector attempts and the vector `hasMore` witness) also passes `jitOff` and runs with `jit = off` (`postgres-engine/search-settings.ts`): the correlated visibility subplans push these short reads past the JIT cost thresholds, and LLVM compilation, not execution, dominated their latency on large brains. Inside a caller's transaction the search runs in a savepoint and restores the caller's `jit` afterwards. Pinned by `test/e2e/search-query-contract-postgres.test.ts`. `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). When the DDL pool has more than one slot, `initSchema` reserves one backend and runs the advisory lock 42 acquire, the bootstrap, the schema replay and the unlock on it, releasing it in `finally` (checkout gauge only, no long-hold permit, so pending `transaction: false` migrations can still reserve); a one-slot pool is already a single backend and runs unreserved. Pinned by `test/e2e/postgres-initschema-advisory-lock.test.ts`. `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)`). #6278 PR 1.5: `runUnsafe` arms a settle timer after a signalled statement's `cancel()`; a statement still pending `cancelSettleMs()` later (`GBRAIN_CANCEL_SETTLE_MS`, default 2000) has its reserved connection discarded so the awaiting caller settles with `CONNECTION_DESTROYED` instead of parking on a round-trip a transaction-mode pooler never completed (backend in `ClientRead`).
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.
- `src/core/snapshot-schema-inputs.ts` — the inputs of the PGLite snapshot schema hash (`computeSnapshotSchemaHash` in `pglite-engine.ts` hashes each file's raw bytes). Computed, not hand-kept: the static import closure (`import`, `export ... from`; type-only imports skipped) of `SNAPSHOT_SCHEMA_ROOTS` (`pglite-schema.ts`, `schema-migrations/registry.generated.ts`, `migrate.ts`, `engine-sql/bootstrap.ts`) plus `SNAPSHOT_SCHEMA_LEAVES`; every literal dynamic `import()` inside the closure must be classified as a leaf or in `SNAPSHOT_DYNAMIC_IMPORTS_NOT_HASHED`. Pure (the caller supplies file access). `test/snapshot-inputs-closure.test.ts` names any missing file and checks every `pglite-snapshot-*` CI cache key covers the same inputs.
diff --git a/llms-full.txt b/llms-full.txt
index f5e32a1d8d..8dc65b8f35 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5710,6 +5710,14 @@ one after `n` milliseconds (a saturated pool or pooler, not a slow query); and
`loop_lag_ms` is the longest event-loop delay during the phase (a busy or
starved process). The same fields appear in the consumer's status snapshot
under `phase`. Unfinished work stays tracked and is retried; nothing is lost. Run `gbrain sources writer status --json` to see what is waiting.
+A `deadline_exceeded` phase is also how a round-trip a transaction-mode pooler
+(Supavisor port 6543, PgBouncer) never completed ends: the backend sits in
+`ClientRead`, the cancel request the deadline sends may never reach it, so
+`GBRAIN_CANCEL_SETTLE_MS` (default 2000) after the cancel the owner discards
+that reserved connection, the statement settles client-side, and the next tick
+runs. The connection end is not reported as `storage_error`; doctor's
+`persistence_session_timeouts` names a transaction-mode URL, and the
+session-mode URL of the same pooler (Supabase: port 5432) avoids the class.
`phase=preparation` lines name a write whose preparation ran past its budget:
`reason=deadline_exceeded` (the claim is released with `blocked_reason`
`preparation_deadline` and one attempt is counted; the budget is
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9d6a91a0fd..2586e3923d 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2202 ratchet +2: pre-publication withdrawal validation;
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 340 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; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row
src/core/pglite-engine.ts 2998 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move)
-src/core/postgres-engine.ts 2953 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); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts)
+src/core/postgres-engine.ts 2976 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); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed
src/core/search/hybrid.ts 1615 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; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts
src/core/types.ts 2239 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +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; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields)
src/core/minions/queue.ts 2528 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; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
diff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.ts
index 87d72ac0ed..afd78d6583 100644
--- a/src/commands/doctor/checks/persistence-requests.ts
+++ b/src/commands/doctor/checks/persistence-requests.ts
@@ -5,7 +5,7 @@ import { oneYearCapacity, readJournalLimits, journalLimitKey } from '../../../co
import { claimStall, claimStateOf, MAX_CLAIM_CONFIG_KEY, readMaxClaimMs } from '../../../core/persistence/claim-phase.ts';
import { preparationBudgetMs } from '../../../core/persistence/preparation-budget.ts';
import { readPreparationPolicy } from '../../../core/persistence/switches.ts';
-import { resolveSessionTimeouts } from '../../../core/db.ts';
+import { resolvePrepare, resolveSessionTimeouts } from '../../../core/db.ts';
import { agentFix, checkError } from '../check-fix.ts';
const WINDOW_DAYS = 7;
@@ -175,13 +175,20 @@ export async function sessionTimeoutsCheck(engine: BrainEngine): Promise<Check>
try {
const [row] = await engine.executeRaw<{ statement_timeout: string }>('SHOW statement_timeout');
const applied = row?.statement_timeout ?? null;
- const details = { configured, applied, docs };
- if (applied !== '0') return { name: 'persistence_session_timeouts', status: 'ok', details, message: `The session statement_timeout (${applied}) reaches the server.` };
+ // #6278: the live stall ran through a transaction-mode pooler (Supavisor :6543), which can also leave a cancelled
+ // round-trip incomplete (backend in ClientRead). The engine settles those client-side; the pooler mode is still worth naming.
+ const url = process.env.GBRAIN_DATABASE_URL ?? process.env.DATABASE_URL ?? '';
+ const pooler = url !== '' && resolvePrepare(url) === false;
+ const poolerNote = pooler ? ' The configured URL is a transaction-mode pooler (prepared statements off): a cancel request may not reach the backend, so a cut-off statement is '
+ + 'discarded client-side after GBRAIN_CANCEL_SETTLE_MS (default 2000). The session-mode URL of the same pooler (Supabase: port 5432) avoids both limits for the persistence owner.' : '';
+ const details = { configured, applied, docs, ...(pooler ? { pooler: 'transaction_mode' } : {}) };
+ if (applied !== '0') return { name: 'persistence_session_timeouts', status: pooler ? 'warn' : 'ok', details: pooler ? { ...details, reason: 'transaction_mode_pooler' } : details,
+ message: `The session statement_timeout (${applied}) reaches the server.${poolerNote}` };
return { name: 'persistence_session_timeouts', status: 'warn', details: { ...details, reason: 'session_timeouts_not_applied' },
message: `session_timeouts_not_applied: gbrain configured statement_timeout=${configured} as a connection startup parameter, but SHOW statement_timeout through the configured URL `
+ 'reads 0. A transaction-mode pooler (PgBouncer, Supavisor) drops startup parameters, so statements outside a transaction have no server-side bound; GBRAIN_STATEMENT_TIMEOUT is '
+ 'ignored there. Preparation reads are bounded by their own transaction-local timeout (the preparation budget covers the gap); a long autocommit statement elsewhere still runs '
- + `until it finishes. To restore the session default, set it on the role: ALTER ROLE <gbrain role> SET statement_timeout = '${configured}' (the pooler cannot be told to keep it).` };
+ + `until it finishes. To restore the session default, set it on the role: ALTER ROLE <gbrain role> SET statement_timeout = '${configured}' (the pooler cannot be told to keep it).${poolerNote}` };
} catch (error) {
return checkError('persistence_session_timeouts', 'read the session statement_timeout', error, { details: { configured, health: 'unknown', docs } });
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 4107631571..ed1196ee27 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -323,6 +323,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.112.0', text: 'New keys `persistence.sync_preparation_ms` (120000), `persistence.maintenance_preparation_ms` (120000), `persistence.preparation_ceiling_ms` (600000) and `persistence.max_preparation_attempts` (2) bound write preparation, and `gbrain config set` refuses a value out of range; the `preparation_deadlines` write switch (`gbrain config set persistence.preparation_deadlines false`) restores the old behavior exactly (only `remember`, `put_page` and `edit_page` keep a 30 s budget; nothing is counted or held). `persistence.max_claim_ms` keeps its doctor meaning. Migration v220 adds `persistence_requests.preparation_attempts`; restart every `gbrain serve`, jobs worker and autopilot on the new version, because an older owner never gives up a stuck preparation.' },
{ since: '0.60.112.0', text: 'Fact-fence adoption (the extract_facts cycle phase and the v0.32.2 backfill) now writes the fence\'s parsed text back into `facts.fact`: a legacy claim with surrounding whitespace or CRLF line endings is adopted with that whitespace trimmed and its line endings folded to LF (the row keeps its id, vectors and provenance). A claim the fence codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or one its page already carries stays a legacy row, active and searchable, and is reported as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: …)` and under doctor `fence_integrity` `unrenderable_legacy_facts`. Only the pages still holding such rows skip destructive fact reconciliation (the whole source skipped before), and the cycle summary names them while keeping the reconcile counts of the other pages.' },
{ since: '0.60.112.0', text: 'A managed maintenance write on a page whose body or timeline already carries a fence defect no adoption clears (for example a second facts fence in the timeline) is now refused at submission with its fence reason, so the cycle skips that page in `failed_pages` instead of failing a request on every pass; doctor `fence_integrity` counts the stored defect as a repair candidate.' },
+ // #6278 PR 1.5
+ { since: '0.60.113.0', text: 'A cancelled database statement that a transaction-mode pooler never completes (its backend stuck in `ClientRead`) is now ended client-side `GBRAIN_CANCEL_SETTLE_MS` (2000 ms) after the cancel request by discarding that reserved connection; the owner\'s phase ends `deadline_exceeded` instead of parking until the watchdog, and a preparation read ended this way counts as the preparation deadline.' },
// #6278 PR 2
{ since: '0.60.113.0', text: '`gbrain repair fences` and the maintenance `fence_repair` phase now run while a managed sync of the source is in progress: only a file a write in flight or the running sync\'s frozen manifest still names waits as `sync_in_progress` (a held file does not), and every other candidate, held files included, is repaired and committed during the catch-up. The busy check is repeated when each item is applied and when its write is admitted, and fails closed when it cannot be read.' },
{ since: '0.60.113.0', text: 'An `owner_unavailable` refusal from fence repair, chronicle, fact-fence adoption or any other maintenance writer now carries a `reason`: `host_mismatch` (both host ids\' first 8 characters, the local `host.json` path for local callers only, `retryable: false`), `transfer_in_progress` or `clone_in_progress` (`fix.next: wait`, 30 s), `binding_missing`, `incarnation_changed`, `local_path_missing` or `coordination_path_missing`; a fence hold records the same reason instead of a bare `owner_unavailable`. Nothing claims or transfers ownership to run maintenance; `gbrain errors owner_unavailable` lists the reasons.' },
diff --git a/src/core/persistence/bounded-reads.ts b/src/core/persistence/bounded-reads.ts
index 205f1c21f3..b72707e3ef 100644
--- a/src/core/persistence/bounded-reads.ts
+++ b/src/core/persistence/bounded-reads.ts
@@ -42,6 +42,12 @@ export class PreparationDeadlineError extends Error {
}
}
+/** Whether `error` is the client ending a round-trip the pooler never completed (`runUnsafe`'s settle discard). */
+export function isConnectionEnd(error: unknown): error is { code: string } {
+ const code = (error as { code?: unknown } | null)?.code;
+ return code === 'CONNECTION_DESTROYED' || code === 'CONNECTION_CLOSED';
+}
+
/** Whether `error` is the server ending a statement at a timeout (ours, or a shorter session one). */
export function isStatementTimeout(error: unknown): error is { code: string } {
const code = (error as { code?: unknown } | null)?.code;
@@ -59,9 +65,11 @@ export function boundedReads(engine: BrainEngine, clock: ClaimPhaseClock | undef
// The clock's signal ends only the wait for a free connection (a saturated pool); the statement itself ends at the bound.
return await target.executeRaw(sql, params, { ...opts, timeoutMs: Math.max(1, deadlineAt - Date.now()), ...(clock!.signal ? { signal: clock!.signal } : {}) });
} catch (error) {
- if (!isStatementTimeout(error)) throw error;
+ // A connection the engine discarded after the budget's cancel (a pooler that never completed the round-trip) is the deadline too.
+ const discarded = isConnectionEnd(error) && (clock!.signal?.aborted || Date.now() >= deadlineAt);
+ if (!isStatementTimeout(error) && !discarded) throw error;
if (clock!.signal?.aborted) throw clock!.signal.reason;
- throw new PreparationDeadlineError(clock!.step, error.code, error);
+ throw new PreparationDeadlineError(clock!.step, (error as { code: string }).code, error);
}
};
const value = Reflect.get(target, key, target);
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 7a17031a8f..b0bc194390 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -90,6 +90,19 @@ export const LANE_BUSY = Symbol('gbrain.laneBusy');
/** `clock` (#6278): the claim's phase clock, for `enterClaimStep` at the preparer's await boundaries. */
export type PrepareMutation = (engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal, clock?: ClaimPhaseClock) => Promise<PreparedMutation>;
+/** #6278: a consumer phase ended by its own deadline (server cancel or client-side discard), never a storage fault. */
+export class PhaseDeadlineError extends Error {
+ readonly code = 'deadline_exceeded';
+ constructor(readonly phase: string, cause: unknown) {
+ super(`Consumer phase ${phase} did not finish within its deadline.`, { cause });
+ this.name = 'PhaseDeadlineError';
+ }
+}
+const PHASE_DEADLINE_CODES = new Set(['57014', 'CONNECTION_DESTROYED', 'CONNECTION_CLOSED']);
+function isPhaseDeadlineOutcome(error: { name?: unknown; code?: unknown } | null): boolean {
+ return !!error && (error.name === 'AbortError' || typeof error.code === 'string' && PHASE_DEADLINE_CODES.has(error.code));
+}
+
export class PersistenceConsumer {
private stopping = false;
private timer: ReturnType<typeof setTimeout> | undefined;
@@ -624,12 +637,22 @@ export class PersistenceConsumer {
&& /^(?:57014: )?canceling statement due to user request$/.test(cancelled.message))) {
throw this.abort.signal.reason;
}
- this.lastPhaseError = name; this.lastPhaseTiming = this.timingText(observation, startedAt); throw error;
+ this.lastPhaseError = name; this.lastPhaseTiming = this.timingText(observation, startedAt);
+ // #6278: past the phase deadline, the statement's end (the server's 57014, or the client-side discard of a
+ // round-trip a pooler never completed) is the deadline itself: the tick moves on instead of reporting storage_error.
+ if (observation.deadline_exceeded && isPhaseDeadlineOutcome(cancelled)) throw new PhaseDeadlineError(name, error);
+ throw error;
}
finally { clearTimeout(timer); this.abort.signal.removeEventListener('abort', stop); this.phaseObservation = undefined; }
}
private report(error: unknown): void {
if (this.stopping && error === this.abort.signal.reason) return;
+ if (error instanceof PhaseDeadlineError) {
+ // The timer already logged deadline_exceeded for this phase; record it and let the next tick run.
+ this.lastError = { code: 'deadline_exceeded', at: new Date().toISOString(), phase: error.phase };
+ this.lastPhaseError = undefined; this.lastPhaseTiming = undefined;
+ return;
+ }
const code = (error as { code?: unknown })?.code;
this.lastError = { code: typeof code === 'string' && (/^[A-Z0-9]{5}$/.test(code) || isWriteErrorCode(code)) ? code : 'storage_error', at: new Date().toISOString(),
...(this.lastPhaseError ? { phase: this.lastPhaseError } : {}) };
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 2417607c09..2994e0a685 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -157,6 +157,8 @@ export function preparationAbortReason(error: unknown, signal?: AbortSignal): Pr
if (!own) return null;
if (error === signal!.reason || e?.name === 'AbortError') return own;
if (e?.code === '57014' && typeof e.message === 'string' && /canceling statement due to user request/.test(e.message)) return own;
+ // #6278: the engine discards a reserved connection whose cancel a pooler never completed; after our abort that end is ours.
+ if (e?.code === 'CONNECTION_DESTROYED' || e?.code === 'CONNECTION_CLOSED') return own;
return null;
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 108f27a595..b43b373768 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -134,6 +134,17 @@ import { searchKeywordCJK as searchKeywordCJKImpl } from './engine-sql/cjk-searc
import * as titlesImpl from './engine-sql/titles.ts';
import type { CjkKeywordCtx } from './search/cjk-keyword-sql.ts';
import { postgresExecutor, type RunUnsafeOpts } from './engine-sql/dialect-postgres.ts';
+
+/**
+ * #6278: how long a cancelled statement may stay unsettled after its cancel request before the reserved
+ * connection is discarded to settle it client-side. A transaction-mode pooler (Supavisor :6543) may not
+ * forward the cancel, leaving the backend in ClientRead where no server timeout applies.
+ */
+export const DEFAULT_CANCEL_SETTLE_MS = 2_000;
+export function cancelSettleMs(): number {
+ const raw = Number(process.env.GBRAIN_CANCEL_SETTLE_MS);
+ return Number.isFinite(raw) && raw >= 100 ? raw : DEFAULT_CANCEL_SETTLE_MS;
+}
import type { SqlExecutor } from './engine-sql/executor.ts';
import { scopedRead, unscopedExecutor } from './engine-sql/brands.ts';
@@ -2716,7 +2727,8 @@ export class PostgresEngine implements BrainEngine {
let reserved: postgres.ReservedSql | undefined;
let pending: ReturnType<typeof conn.unsafe> | undefined;
let cancellation: Promise<void> | undefined;
- let retired = false;
+ let retired = false, settled = false, discarded = false;
+ let settleTimer: ReturnType<typeof setTimeout> | undefined;
let owner: postgres.TransactionSql | postgres.ReservedSql = conn as unknown as postgres.TransactionSql;
signal?.addEventListener('abort', onAbort, { once: true });
try {
@@ -2731,18 +2743,29 @@ export class PostgresEngine implements BrainEngine {
// describe round trip plus an execute round trip.
const driverOpts = { cancelFence: !!signal, prepare: opts?.prepare ?? true, ...(opts?.simple === undefined ? {} : { simple: opts.simple }) };
pending = conn.unsafe(sql, params as Parameters<typeof conn.unsafe>[1], driverOpts);
- return await pending as unknown as T[];
+ try { return await pending as unknown as T[]; } finally { settled = true; }
} finally {
signal?.removeEventListener('abort', onAbort);
+ clearTimeout(settleTimer);
try {
if (cancellation) await cancellation;
- if (retired) owner.discard();
+ if (retired && !discarded) owner.discard();
} finally { reserved?.release(); }
}
function onAbort() {
if (!pending || cancellation) return;
try { cancellation = pending.cancel().catch(() => { retired = true; }); }
catch { retired = true; }
+ // #6278: a transaction-mode pooler may swallow the cancel request and leave the backend in ClientRead,
+ // so the statement never settles on its own. Past the settle window the reserved connection is
+ // discarded, which rejects the statement client-side (CONNECTION_DESTROYED) and frees the awaiting caller.
+ const statement = pending;
+ settleTimer = setTimeout(() => {
+ if (settled) return;
+ retired = true; discarded = true;
+ try { owner.discard(); } catch { /* the reservation is already gone */ }
+ }, cancelSettleMs());
+ statement.then(() => { settled = true; }, () => { settled = true; });
}
})();
}
diff --git a/test/e2e/persistence-pooler-wedge-postgres.test.ts b/test/e2e/persistence-pooler-wedge-postgres.test.ts
new file mode 100644
index 0000000000..0ea7157458
--- /dev/null
+++ b/test/e2e/persistence-pooler-wedge-postgres.test.ts
@@ -0,0 +1,130 @@
+/**
+ * #6278 (PR 1.5): a consumer round-trip a transaction-mode pooler never
+ * completes must settle client-side, and the catch-up must go on.
+ *
+ * The live report: through Supavisor :6543 the consumer's `expired_claims`
+ * CTE sat with its backend in `ClientRead`; the 5 s phase deadline fired, the
+ * cancel request never reached the backend, and the awaited promise never
+ * settled, so the whole owner parked until the watchdog. Here the pool's
+ * `reserve()` is wrapped so that one `expired_claims` statement behaves like
+ * that wedge: it never settles, its `cancel()` resolves without ending it,
+ * and only `discard()` (what `runUnsafe` does after the settle window)
+ * rejects it. Everything else runs against the real Postgres.
+ *
+ * Fails before the fix: the sync never returns (the test times out). After:
+ * the phase ends `deadline_exceeded`, the consumer keeps ticking and the
+ * 60-page catch-up drains `synced` with no `storage_error` report.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { performSync } from '../../src/commands/sync/perform.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { resetWriteSwitches } from '../../src/core/persistence/switches.ts';
+import { hasDatabase } from './helpers.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-pooler-wedge-e2e-'));
+let engine: BrainEngine | undefined;
+let closePostgres: (() => Promise<void>) | undefined;
+const sources: string[] = [];
+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
+async function fixture(e: BrainEngine, count: number) {
+ const id = `wedge-${randomUUID().replace(/-/g, '').slice(0, 20)}`; sources.push(id);
+ const root = join(home, id); mkdirSync(root); git(root, 'init', '-q');
+ for (let i = 0; i < count; i++) {
+ const full = join(root, 'notes', `n${String(i).padStart(3, '0')}.md`); mkdirSync(join(full, '..'), { recursive: true });
+ writeFileSync(full, `---\ntitle: Note ${i}\n---\nA durable observation number ${i}.\n`);
+ }
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+ await e.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await e.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
+ await claimWorktree(e, id, root);
+ await e.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root };
+}
+
+interface Reserved { unsafe: (sql: string, params?: unknown[], opts?: unknown) => Promise<unknown[]> & { cancel?: () => Promise<void> }; discard?: () => void; release: () => void }
+type Pool = ((...args: unknown[]) => unknown) & { reserve: (opts?: unknown) => Promise<Reserved> };
+
+/** Wedges the first `expired_claims` statement the consumer issues through a reserved connection; counts cancels and discards. */
+function wedgeExpiredClaims(pool: Pool) {
+ const originalReserve = pool.reserve;
+ const seen = { wedged: 0, cancels: 0, discards: 0, settledBy: null as null | 'cancel' | 'discard' };
+ pool.reserve = async (opts?: unknown) => {
+ const reserved = await originalReserve.call(pool, opts);
+ if (seen.wedged > 0) return reserved;
+ const originalUnsafe = reserved.unsafe.bind(reserved);
+ const originalDiscard = reserved.discard?.bind(reserved);
+ let reject: ((error: unknown) => void) | undefined;
+ reserved.unsafe = (sql: string, params?: unknown[], unsafeOpts?: unknown) => {
+ if (seen.wedged > 0 || !sql.startsWith('WITH expired AS')) return originalUnsafe(sql, params, unsafeOpts);
+ seen.wedged++;
+ const statement = new Promise<unknown[]>((_, rej) => { reject = rej; }) as Promise<unknown[]> & { cancel: () => Promise<void> };
+ // The pooler swallows the cancel: it resolves, the backend stays in ClientRead, the statement never ends on its own.
+ statement.cancel = async () => { seen.cancels++; };
+ return statement;
+ };
+ reserved.discard = () => {
+ seen.discards++;
+ if (reject) { seen.settledBy ??= 'discard'; reject(Object.assign(new Error('write CONNECTION_DESTROYED'), { code: 'CONNECTION_DESTROYED' })); reject = undefined; }
+ originalDiscard?.();
+ };
+ return reserved;
+ };
+ return { seen, restore: () => { pool.reserve = originalReserve; } };
+}
+
+beforeAll(async () => {
+ if (!hasDatabase()) return;
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!, 'instance', 12); engine = pg.engine; closePostgres = pg.close;
+ resetWriteSwitches();
+}, 120_000);
+afterAll(async () => {
+ if (engine) await withEnv({ GBRAIN_HOME: home }, async () => {
+ await disposePersistenceConsumer(engine!); await engine!.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const id of sources) await engine!.executeRaw('DELETE FROM sources WHERE id=$1', [id]);
+ });
+ resetWriteSwitches();
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe.skipIf(!hasDatabase())('#6278 PR 1.5: a wedged consumer round-trip settles client-side and the catch-up drains', () => {
+ test('one expired_claims statement never completes: cancel is swallowed, the connection is discarded at the settle window, the phase ends deadline_exceeded and 60 pages still sync', async () =>
+ withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_CANCEL_SETTLE_MS: '300' }, async () => {
+ if (!engine) return;
+ const f = await fixture(engine, 60);
+ const pool = (engine as unknown as { sql: Pool }).sql;
+ const wedge = wedgeExpiredClaims(pool);
+ const lines: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ (process.stderr as unknown as { write: unknown }).write = (chunk: unknown) => { lines.push(String(chunk)); return true; };
+ const started = performance.now();
+ let result;
+ try {
+ result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 2 });
+ } finally {
+ (process.stderr as unknown as { write: unknown }).write = write;
+ wedge.restore();
+ }
+ expect(wedge.seen.wedged).toBe(1);
+ expect(wedge.seen.cancels).toBe(1);
+ expect(wedge.seen.discards).toBeGreaterThanOrEqual(1);
+ expect(wedge.seen.settledBy).toBe('discard');
+ expect(result.drain).toMatchObject({ outcome: 'synced' });
+ const rows = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [f.id]);
+ expect(rows.length).toBe(60);
+ expect(rows.every(row => row.state === 'committed')).toBe(true);
+ expect(lines.filter(line => line.includes('phase=expired_claims') && line.includes('reason=deadline_exceeded')).length).toBe(1);
+ expect(lines.filter(line => line.includes('reason=storage_error') || line.includes('CONNECTION_DESTROYED'))).toEqual([]);
+ // The wedge cost one phase deadline (5 s) plus the settle window, not the watchdog.
+ expect(performance.now() - started).toBeLessThan(120_000);
+ }), 180_000);
+});
diff --git a/test/persistence-consumer-log.test.ts b/test/persistence-consumer-log.test.ts
index 31833014cc..0ca4d9ecff 100644
--- a/test/persistence-consumer-log.test.ts
+++ b/test/persistence-consumer-log.test.ts
@@ -121,3 +121,44 @@ describe('#5801 connection-wait evidence on the consumer line', () => {
expect(line).not.toContain('first_conn_ms=');
});
});
+
+/** #6278: every statement parks until its signal aborts, then (as the engine's client-side discard does) rejects CONNECTION_DESTROYED. */
+function clientReadWedgeEngine(settleAfterAbortMs: number) {
+ let statements = 0;
+ const call = (..._args: unknown[]) => {
+ const signal = _args.find((arg): arg is { signal?: AbortSignal } => !!arg && typeof arg === 'object' && 'signal' in (arg as object))?.signal;
+ statements++;
+ return new Promise<never>((_, reject) => {
+ const end = () => setTimeout(() => reject(Object.assign(new Error('write CONNECTION_DESTROYED'), { code: 'CONNECTION_DESTROYED' })), settleAfterAbortMs);
+ if (signal?.aborted) end(); else signal?.addEventListener('abort', end, { once: true });
+ });
+ };
+ const target: Record<string, unknown> = { kind: 'postgres', onCheckout: () => () => undefined };
+ const engine = new Proxy(target, {
+ get(t, prop) {
+ if (prop in t) return t[prop as string];
+ if (prop === 'then') return undefined;
+ return call;
+ },
+ }) as unknown as BrainEngine;
+ return { engine, statements: () => statements };
+}
+
+describe('#6278 a round-trip the pooler never completes ends as the phase deadline, and the consumer keeps ticking', () => {
+ test('the phase logs deadline_exceeded once, the discarded connection is not reported as storage_error, and the next tick runs', async () => {
+ const { engine, statements } = clientReadWedgeEngine(30);
+ captureStderr();
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async () => { throw new Error('unused'); }, { hostId: crypto.randomUUID(), phaseMs: 100 });
+ try {
+ await consumer.tick();
+ const first = statements();
+ expect(first).toBeGreaterThan(0);
+ expect(consumer.status().last_error).toMatchObject({ code: 'deadline_exceeded' });
+ expect(stderr.filter(entry => entry.includes('reason=deadline_exceeded')).length).toBe(1);
+ expect(stderr.filter(entry => entry.includes('CONNECTION_DESTROYED') || entry.includes('reason=storage_error'))).toEqual([]);
+ // The consumer is not parked: a later tick issues statements again.
+ await consumer.tick();
+ expect(statements()).toBeGreaterThan(first);
+ } finally { await consumer.stop(); }
+ });
+});
diff --git a/test/persistence-session-timeouts-check.test.ts b/test/persistence-session-timeouts-check.test.ts
index b627d78ea2..210d726321 100644
--- a/test/persistence-session-timeouts-check.test.ts
+++ b/test/persistence-session-timeouts-check.test.ts
@@ -33,3 +33,14 @@ test('an applied timeout, a disabled one and PGLite are ok', async () => {
});
expect(await sessionTimeoutsCheck({ kind: 'pglite' } as BrainEngine)).toMatchObject({ status: 'ok', details: { configured: '5min', applied: null } });
});
+
+test('#6278: a transaction-mode pooler URL is named even when the timeout reaches the server, with the client-side settle and the session-mode URL', async () => {
+ await withEnv({ GBRAIN_STATEMENT_TIMEOUT: '10min', GBRAIN_DATABASE_URL: 'postgresql://user:[email protected]:6543/postgres', DATABASE_URL: undefined, GBRAIN_PREPARE: undefined }, async () => {
+ const check = await sessionTimeoutsCheck(postgres('10min'));
+ expect(check).toMatchObject({ status: 'warn', details: { applied: '10min', pooler: 'transaction_mode', reason: 'transaction_mode_pooler' } });
+ for (const text of ['transaction-mode pooler', 'GBRAIN_CANCEL_SETTLE_MS', 'port 5432']) expect(check.message).toContain(text);
+ });
+ await withEnv({ GBRAIN_STATEMENT_TIMEOUT: '10min', GBRAIN_DATABASE_URL: 'postgresql://user:[email protected]:5432/postgres', DATABASE_URL: undefined, GBRAIN_PREPARE: undefined }, async () => {
+ expect(await sessionTimeoutsCheck(postgres('10min'))).toMatchObject({ status: 'ok' });
+ });
+});
diff --git a/test/postgres-engine-cancel-settle.test.ts b/test/postgres-engine-cancel-settle.test.ts
new file mode 100644
index 0000000000..521fb63fe1
--- /dev/null
+++ b/test/postgres-engine-cancel-settle.test.ts
@@ -0,0 +1,115 @@
+/**
+ * #6278: a cancelled statement that never settles is discarded client-side.
+ *
+ * Through a transaction-mode pooler (Supavisor :6543) the cancel request a
+ * signalled `executeRaw` sends may never reach the backend, which then sits
+ * in `ClientRead` forever: no server timeout applies, `cancel()` resolves
+ * without ending the statement, and the awaiting caller (the consumer's
+ * `expired_claims` phase in the live report) parks on a promise that never
+ * settles. `runUnsafe` now discards the reserved connection once the
+ * statement is still unsettled `GBRAIN_CANCEL_SETTLE_MS` after the cancel,
+ * so the promise rejects (CONNECTION_DESTROYED) and the caller moves on.
+ *
+ * Hermetic: Object.create(PostgresEngine.prototype) with a fake pool whose
+ * reserved `unsafe()` never settles unless discarded. Fails before the fix:
+ * the awaited promise never settles and the test times out.
+ */
+import { describe, expect, test } from 'bun:test';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import { CheckoutGauge } from '../src/core/pool-gauge.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+interface Statement extends Promise<unknown[]> { cancel: () => Promise<void> }
+
+function hangingPool(log: string[], opts: { cancelEndsStatement: boolean }) {
+ let reject: ((error: unknown) => void) | undefined;
+ const pool = {
+ options: { max: 10 },
+ unsafe: async () => [],
+ reserve: async () => ({
+ unsafe: (sql: string) => {
+ log.push(`unsafe:${sql}`);
+ const statement = new Promise<unknown[]>((_, rej) => { reject = rej; }) as Statement;
+ statement.cancel = async () => {
+ log.push('cancel');
+ if (opts.cancelEndsStatement) reject?.(Object.assign(new Error('canceling statement due to user request'), { code: '57014' }));
+ };
+ return statement;
+ },
+ discard: () => { log.push('discard'); reject?.(Object.assign(new Error('write CONNECTION_DESTROYED'), { code: 'CONNECTION_DESTROYED' })); },
+ release: () => log.push('release'),
+ }),
+ };
+ return pool;
+}
+
+function makeEngine(pool: unknown): PostgresEngine {
+ const engine = Object.create(PostgresEngine.prototype) as PostgresEngine;
+ Object.defineProperty(engine, 'sql', { get: () => pool });
+ Object.defineProperty(engine, '_sql', { value: pool, writable: true });
+ Object.defineProperty(engine, 'checkoutGauge', { value: new CheckoutGauge(), writable: true });
+ Object.defineProperty(engine, 'connectionManager', { value: { peekReadPool: () => pool, isDualPoolActive: () => false } });
+ return engine;
+}
+
+const run = (engine: PostgresEngine, signal: AbortSignal) =>
+ (engine as unknown as { runUnsafe: (conn: unknown, sql: string, params: unknown[] | undefined, opts: { signal: AbortSignal }) => Promise<unknown[]> })
+ .runUnsafe((engine as unknown as { sql: unknown }).sql, 'WITH expired AS (SELECT 1) UPDATE persistence_requests SET state=state', [], { signal });
+
+describe('#6278: a cancelled statement the pooler never ends settles client-side', () => {
+
+ test('cancel resolves, the statement stays unsettled, the connection is discarded at the settle window and the caller gets CONNECTION_DESTROYED', async () => {
+ await withEnv({ GBRAIN_CANCEL_SETTLE_MS: '150' }, async () => {
+ const log: string[] = [];
+ const engine = makeEngine(hangingPool(log, { cancelEndsStatement: false }));
+ const abort = new AbortController();
+ const started = performance.now();
+ const pending = run(engine, abort.signal);
+ setTimeout(() => abort.abort({ code: 'deadline_exceeded' }), 20);
+ const error = await pending.then(() => null, e => e as { code?: string });
+ const elapsed = performance.now() - started;
+ expect(error?.code).toBe('CONNECTION_DESTROYED');
+ expect(log).toEqual(['unsafe:WITH expired AS (SELECT 1) UPDATE persistence_requests SET state=state', 'cancel', 'discard', 'release']);
+ // Settled within the window plus scheduling slack, not at the test timeout.
+ expect(elapsed).toBeLessThan(1_500);
+ expect(elapsed).toBeGreaterThanOrEqual(150);
+ });
+ });
+
+ test('a cancel the server honours ends the statement with 57014 before the settle window; nothing is discarded', async () => {
+ await withEnv({ GBRAIN_CANCEL_SETTLE_MS: '2000' }, async () => {
+ const log: string[] = [];
+ const engine = makeEngine(hangingPool(log, { cancelEndsStatement: true }));
+ const abort = new AbortController();
+ const started = performance.now();
+ const pending = run(engine, abort.signal);
+ setTimeout(() => abort.abort({ code: 'deadline_exceeded' }), 20);
+ const error = await pending.then(() => null, e => e as { code?: string });
+ expect(error?.code).toBe('57014');
+ expect(log).toEqual(['unsafe:WITH expired AS (SELECT 1) UPDATE persistence_requests SET state=state', 'cancel', 'release']);
+ expect(performance.now() - started).toBeLessThan(1_000);
+ });
+ });
+
+ test('a statement that finishes before the settle window never arms a discard', async () => {
+ await withEnv({ GBRAIN_CANCEL_SETTLE_MS: '150' }, async () => {
+ const log: string[] = [];
+ const pool = hangingPool(log, { cancelEndsStatement: false });
+ let resolveStatement: ((rows: unknown[]) => void) | undefined;
+ const reserved = await pool.reserve();
+ pool.reserve = async () => ({ ...reserved, unsafe: (sql: string) => {
+ log.push(`unsafe:${sql}`);
+ const statement = new Promise<unknown[]>(res => { resolveStatement = res; }) as Statement;
+ statement.cancel = async () => { log.push('cancel'); };
+ return statement;
+ } });
+ const engine = makeEngine(pool);
+ const abort = new AbortController();
+ const pending = run(engine, abort.signal);
+ setTimeout(() => { abort.abort({ code: 'deadline_exceeded' }); resolveStatement?.([{ ok: 1 }]); }, 20);
+ expect(await pending).toEqual([{ ok: 1 }]);
+ await Bun.sleep(250);
+ expect(log.filter(entry => entry === 'discard')).toEqual([]);
+ });
+ });
+});