Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search): cut the warm hybrid server stage at large-brain scale (GBRA-156)

garrytan82364a171441
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index c06d2bb9f4..4c4c3bf8e4 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/engine-sql/keyword-pages.ts` + `src/core/search/keyword-statement.ts` — the strict keyword count (`BrainEngine.countKeywordPages`) and the keyword-mode page query (`BrainEngine.searchKeywordPages`) for both engines. `buildKeywordMatch` is the ONE WHERE builder both statements read: `searchKeyword`'s strict match (websearch FTS on `content_chunks.search_vector`, or the CJK LIKE/ILIKE terms), never its OR retry, with the same page filters, hard excludes and `buildVisibilityClause` (private pages, safe chunks, so no private fence text). The match returns its WHERE params first and the score-only rank params after them (`whereParamCount`), so the count binds only what its WHERE reads (a CJK count bound the term-frequency params and failed on both engines; `test/sql-bind-placeholders.test.ts`). The count is `count(*)` over `SELECT DISTINCT page_id … LIMIT 10001`; a non-timeout count failure logs its SQLSTATE once per process (`keyword-paging.ts`); the page query takes each page's best chunk before paging (no global chunk cap) and orders by `(score DESC, page_id ASC)` with float8 scores so the keyset cursor round-trips. Postgres runs both inside `withScopedReadTransaction` with a statement timeout (the count's set from the caller's deadline); PGLite has none.
- `src/core/search/exact-scan.ts` + `src/core/ops/search-exact.ts` + `src/cli/search-exact-format.ts` — #7191: `search_exact` (CLI `gbrain search --exact`, routed in `cli/main.ts` before ranked-search flags parse): an unranked literal scan of `content_chunks.chunk_text` (words in order, any whitespace between, case-insensitive unless `case_sensitive`; the ARE comes from `phrasePattern`, with a LIKE prefilter on the longest word) in keyset batches of pages by id (`buildExactBatchStatement`), under ranked search's visibility (live page, unarchived source, quarantine, pinned questions, `chunkVisibleFilter`, source scope, private pages and the trust floor for untrusted callers, `safeChunksFilter` for remote) and the hard-excluded prefixes. `complete` is true only when the scope was scanned to the end with no `limit` or `deadline` stop and no unreadable page (`unchunked`, `projection_pending`, remote `unsealed`, `scan_timeout`); a Postgres statement timeout halves the batch, down to one page. `resume_after` continues a bounded scan. Registered `filtered` (`min_trust`, `stampPageTrust`), output redaction `retrieval`. Guide: [exact search](../../guides/exact-search.md). Tests: `test/search-exact.test.ts`, `test/e2e/search-exact-postgres.test.ts`.
-- `src/core/engine-sql/titles.ts` + `src/core/search/title-statement.ts` — the page-grain title arm (`BrainEngine.searchTitles`) for both engines: `buildSearchTitlesStatement` in `search/` (SQL composed outside engine-sql like `cjk-keyword-sql.ts`; also used by the plan-proof E2E `test/e2e/title-arm-postgres.test.ts`) and `searchTitles(scoped, query, opts, dialect)` in engine-sql, where `dialect` carries the engine differences kept from master (Postgres: 8s per-attempt `statement_timeout`, `enable_seqscan` off for the relaxed local re-run; PGLite: the timeline `stale` probe). Both orderings sort an exact-title key first (`lower(btrim(title, ' "''' || chr(160))) = normalizeAlias(query)`, bound separately from the websearch text so the OR fallback never rebinds it; #5889). The websearch text is read through `gbrain_fts_input($1)` (#6370), the same CJK/ASCII boundary split the index applies, so a glued title query matches. Safe-chunks callers match `pages.search_vector @@ q_a`, the websearch query with every lexeme labeled `:A` (weight A is the title alone), ranked on `ts_filter(search_vector, '{a}')`: served by `idx_pages_search`, title-only for negated and phrase terms, and following the stored `search_vector` language. Pages with a NULL `search_vector` are absent from the remote arm.
+- `src/core/engine-sql/titles.ts` + `src/core/search/title-statement.ts` — the page-grain title arm (`BrainEngine.searchTitles`) for both engines: `buildSearchTitlesStatement` in `search/` (SQL composed outside engine-sql like `cjk-keyword-sql.ts`; also used by the plan-proof E2E `test/e2e/title-arm-postgres.test.ts`) and `searchTitles(scoped, query, opts, dialect)` in engine-sql, where `dialect` carries the engine differences kept from master (Postgres: 8s per-attempt `statement_timeout`, `enable_seqscan` off for the relaxed local re-run; PGLite: the timeline `stale` probe). Both orderings sort an exact-title key first (`lower(btrim(title, ' "''' || chr(160))) = normalizeAlias(query)`, bound separately from the websearch text so the OR fallback never rebinds it; #5889). The websearch text is read through `gbrain_fts_input($1)` (#6370), the same CJK/ASCII boundary split the index applies, so a glued title query matches. Safe-chunks callers and every OR re-run match `ts_filter(search_vector, '{a}') @@ q` (weight A is the title alone) and rank on the same slice: served by the expression index `idx_pages_title_search` (GBRA-156, v267), which holds title lexemes only, so a term in timeline text never makes its page a candidate; title-only for negated and phrase terms, following the stored `search_vector` language. Postgres runs each attempt with the keyword statement's `work_mem` (`statementSettings`). Pages with a NULL `search_vector` are absent from the remote arm.
- `src/core/engine-sql/health.ts` — `BrainEngine.getHealth` once for both engines (`migrated health`). Three statements, no per-page rows returned: the counters (pages, chunks, links, embedding coverage, missing embeddings, dead links, entity link/timeline coverage), the linkable scope grouped by page type with islanded and with-timeline counts (the orphan policy rendered in SQL by `orphanExclusionSql`; the brain_score timeline grading applies per type), and `most_connected` as live, in-scope link endpoints grouped per entity page (ties break by slug in code-point order; a link whose far endpoint is soft-deleted does not count, #6940). The linkable groups are a separate statement because folding them into the counters crosses Postgres's JIT cost thresholds at about 20k pages. Per-page and per-link checks that misplan without planner statistics (PGLite before its first ANALYZE) are primary-key lookups the planner cannot reorder (scalar subqueries, a LATERAL fenced with `OFFSET 0`), so the statements stay linear with or without statistics. Scope rules: `sourceIds` > `sourceId` > brain-wide, duplicate ids count once, a link counts only when both endpoints are in scope, endpoint liveness in both directions, quarantined pages out of the entity denominators and the linkable scope. Entity pages (#4772) are the types the active schema pack(s) declare as entities, resolved per source by `HealthDeps.entityTypes` (`src/core/schema-pack/entity-types.ts`) and bound as `text[]` parameters (`entityTypePredicateSql`: one list, or a `CASE p.source_id` when sources' packs disagree); a pack that does not load binds an empty list and the result carries `entity_types_status: 'pack_unavailable'`, never the old hardcoded list. Reads take `LegacyUnscopedRead` (pool, no scope transaction). Engine deps are four functions (`embeddingColumn`, `countStalePagesForExtraction`, `getConfig`, `entityTypes`). Pinned field by field against the pre-F4a implementation (`test/helpers/legacy-get-health.ts`, whose `most_connected` was corrected for #6940 as an intended change) by `test/engine-sql-health-equality.test.ts` and `test/e2e/engine-sql-health-parity.test.ts` (direct Postgres and PgBouncer); the pack-driven entity predicate by `test/health-entity-types-pack.test.ts` and `test/e2e/health-entity-types-pack.test.ts`; `most_connected` liveness by `test/health-most-connected-liveness-6940.test.ts` (+ Postgres twin).
- `src/core/engine-sql/graph-rank.ts` — #7168: `rankEntitiesStatement(opts)`, the one `rank_entities` aggregate for both engines (a statement builder: the op runs it through `executeRaw` with its statement deadline, like `extractionLagStatement`). Edges are distinct `(from, to, link_type)` triples between live, in-scope endpoints (both endpoints scoped by `sourceIds`), self-links, non-ranking types (`rankingLinkSql`) and, unless `includeMentions`, mention rows excluded. Retired pages (`retiredPageSql`) fold into their `superseded_by`/`merged_into` target in the same source through a recursive chain over retired pages only, capped at `MAX_RETIREMENT_HOPS`; edges dedupe after folding and folded self-links drop. With `remote` every endpoint, chain hop, fold target and non-null link origin must be in scope, live, unquarantined, in an unarchived source and (with `excludePrivate`) not private, so a hidden target never folds. Ordered by the direction's count, then slug and source id (`COLLATE "C"`), LIMIT after folding. Tests: `test/rank-entities.test.ts`.
@@ -45,8 +45,8 @@ 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`). `formatBuildFailureWarning` appends `param=$n` (or `param=?` for an array element) to an `UNDEFINED_VALUE` line from the driver's `onbuilderror(code, statement, parameter)` (#6543).
-- `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` + a transaction-local `set_config` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection; the keyword-side bound (`searchKeyword`, `countKeywordPages`, `searchKeywordPages`, `searchTitles`, `searchKeywordChunks`, `_searchKeywordCJK`) is `search.keyword_statement_timeout_ms` (#6495; default 8000, range 1000-60000), resolved once per connection by `keywordStatementTimeoutSetting()` on the first keyword statement (`postgres-engine/keyword-statement-timeout.ts`: the `EngineConfig.keyword_statement_timeout_ms` value the engine connected with, else the DB plane's row read by one parameterless pool statement so no pg-types cache entry is described and `connect()` issues nothing for it, else the default; never a request parameter), with `countKeywordPages` keeping a caller's narrower `timeoutMs`. 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. `withScopedReadTransaction` applies every setting a search read needs (RLS `app.scopes`, `jit`, the caller's `settings`: `statement_timeout`, the relaxed arms' `enable_seqscan`, the vector scan settings from `vectorScanSettings`, a thunk read after BEGIN) in one `withSearchSettings` statement, `SELECT set_config('<name>', $n, true), …`, so a top-level read is BEGIN, settings, query, COMMIT; `statement_timeout` stays a literal name with a bound value so the vendored driver's #6543 budget reads it. Inside a caller's transaction the search runs in a savepoint, reads the caller's values in one statement and restores every one afterwards (a failed read rolls them back with the savepoint). Pinned by `test/search-settings-one-statement.test.ts` and `test/e2e/search-query-contract-postgres.test.ts`. `executeRaw(sql, params, { jitOff: true })` (`postgres-engine/jit-off-statement.ts`) gives single statements the same setting only when it pays: the server's `jit` is read once per pool, a JIT-off server runs the plain statement, and a JIT-on server runs `BEGIN; SET LOCAL jit = off`, the statement and `COMMIT` pipelined in the `runBoundedStatement` envelope (`postgres-engine/bounded-statement.ts`, which keeps `timeoutMs`/`deadlineAt` and the abort signal); inside a caller's transaction it reads, overrides and restores the caller's value. Pinned by `test/e2e/typed-search-jit-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`). For excludePrivate callers `searchKeyword` runs its full-text match in an `OFFSET 0` subquery (`search/keyword-chunk-match.ts`): inside the join the private-visibility subplans inflate every candidate plan's cost, so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (about 1.1 s for a common term at 250k chunks); local callers keep the unfenced, parallel-capable join. Rows, order and scores are pinned on both engines by `test/search/keyword-arm-ranking.test.ts` (golden `test/fixtures/keyword-arm-ranking.json`, which also pins one keyword statement per search and two when the strict query matches nothing and the OR fallback runs) and its Postgres twin `test/e2e/keyword-arm-ranking-postgres.test.ts`.
-- `src/core/search/connection-budget.ts` — per-op pooled-connection budget for `search` and `query`. `SEARCH_CONNECTION_LIMIT` (4) is the most connections one op holds at once. `withSearchConnectionBudget` opens the scope; the ops' `metered` wrapper in `src/core/ops/search.ts` and `dispatchToolCall` (`src/mcp/dispatch.ts`, so pre-op reads and the response-meta hook count too) both enter it, and a nested call shares the enclosing budget. `holdSearchConnection` is called at the engine's two connection seams, `PostgresEngine#transactionOn` (a top-level transaction, held until its COMMIT settles even when a read transaction answers early) and `runUnsafe` (one statement). Work inside a held slot runs outside the scope, so statements on a transaction's own connection never wait on a second slot. Outside a scope, and on PGLite, nothing waits. These reads use the ordinary read pool (the transaction pooler behind a split route), never the direct/session lane. Pinned on Postgres at the wire by `test/e2e/search-connection-budget-postgres.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` + a transaction-local `set_config` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection; the keyword-side bound (`searchKeyword`, `countKeywordPages`, `searchKeywordPages`, `searchTitles`, `searchKeywordChunks`, `_searchKeywordCJK`) is `search.keyword_statement_timeout_ms` (#6495; default 8000, range 1000-60000), resolved once per connection by `keywordStatementTimeoutSetting()` on the first keyword statement (`postgres-engine/keyword-statement-timeout.ts`: the `EngineConfig.keyword_statement_timeout_ms` value the engine connected with, else the DB plane's row read by one parameterless pool statement so no pg-types cache entry is described and `connect()` issues nothing for it, else the default; never a request parameter), with `countKeywordPages` keeping a caller's narrower `timeoutMs`. 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. `withScopedReadTransaction` applies every setting a search read needs (RLS `app.scopes`, `jit`, the caller's `settings`: `statement_timeout`, the relaxed arms' `enable_seqscan`, the vector scan settings from `vectorScanSettings`, a thunk read after BEGIN) in one `withSearchSettings` statement, `SELECT set_config('<name>', $n, true), …`, so a top-level read is BEGIN, settings, query, COMMIT; `statement_timeout` stays a literal name with a bound value so the vendored driver's #6543 budget reads it. Inside a caller's transaction the search runs in a savepoint, reads the caller's values in one statement and restores every one afterwards (a failed read rolls them back with the savepoint). A top-level read transaction opts in to `begin({ early: isPipelinableSearchRead })` (GBRA-156): its settings statement and its reads (single SELECT or WITH statements naming no write, lock, sequence or session setting) go out behind BEGIN before BEGIN's answer on any pool that pipelines inside a transaction, one round trip instead of two. Pinned by `test/search-settings-one-statement.test.ts` and `test/e2e/search-query-contract-postgres.test.ts`. `executeRaw(sql, params, { jitOff: true })` (`postgres-engine/jit-off-statement.ts`) gives single statements the same setting only when it pays: the server's `jit` is read once per pool, a JIT-off server runs the plain statement, and a JIT-on server runs `BEGIN; SET LOCAL jit = off`, the statement and `COMMIT` pipelined in the `runBoundedStatement` envelope (`postgres-engine/bounded-statement.ts`, which keeps `timeoutMs`/`deadlineAt` and the abort signal); inside a caller's transaction it reads, overrides and restores the caller's value. Pinned by `test/e2e/typed-search-jit-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`). For excludePrivate callers `searchKeyword` runs its full-text match in an `OFFSET 0` subquery (`search/keyword-chunk-match.ts`): inside the join the private-visibility subplans inflate every candidate plan's cost, so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (about 1.1 s for a common term at 250k chunks); local callers keep the unfenced, parallel-capable join. Rows, order and scores are pinned on both engines by `test/search/keyword-arm-ranking.test.ts` (golden `test/fixtures/keyword-arm-ranking.json`, which also pins one keyword statement per search and two when the strict query matches nothing and the OR fallback runs) and its Postgres twin `test/e2e/keyword-arm-ranking-postgres.test.ts`.
+- `src/core/search/connection-budget.ts` — per-op pooled-connection budget for `search` and `query`. `SEARCH_CONNECTION_LIMIT` (4) is the most connections one op holds at once. `withSearchConnectionBudget` opens the scope; the ops' `metered` wrapper in `src/core/ops/search.ts` and `dispatchToolCall` (`src/mcp/dispatch.ts`, so pre-op reads and the response-meta hook count too) both enter it, and a nested call shares the enclosing budget. `holdSearchConnection` is called at the engine's two connection seams, `PostgresEngine#transactionOn` (a top-level transaction, held until its COMMIT settles even when a read transaction answers early) and `runUnsafe` (one statement). Work inside a held slot runs outside the scope, so statements on a transaction's own connection never wait on a second slot. A read started under `withUrgentSearchConnections` (hybrid search's lexical, relational and vector arms, `hybrid/arms.ts`) takes the next free slot ahead of waiting ordinary reads (the keyword count and entity resolution an op starts early for its response; GBRA-156, `test/search-connection-budget-urgent.test.ts`). Outside a scope, and on PGLite, nothing waits. These reads use the ordinary read pool (the transaction pooler behind a split route), never the direct/session lane. Pinned on Postgres at the wire by `test/e2e/search-connection-budget-postgres.test.ts`.
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/patches/[email protected] b/patches/[email protected]
index 21e558795a..bd4d4afede 100644
--- a/patches/[email protected]
+++ b/patches/[email protected]
@@ -689,7 +689,7 @@ index 07f6716..2978d0b 100644
seconds = typeof seconds === 'function' ? seconds() : seconds
if (!seconds)
diff --git a/cjs/src/index.js b/vendor/postgres/cjs/src/index.js
-index f09c61c..4709ad4 100644
+index f09c61c7e..ef672e7c9 100644
--- a/cjs/src/index.js
+++ b/vendor/postgres/cjs/src/index.js
@@ -62,10 +62,36 @@ function Postgres(a, b) {
@@ -730,7 +730,7 @@ index f09c61c..4709ad4 100644
Object.assign(sql, {
get parameters() { return options.parameters },
largeObject: largeObject.bind(null, sql),
-@@ -200,58 +226,233 @@ function Postgres(a, b) {
+@@ -200,58 +226,242 @@ function Postgres(a, b) {
return await sql`select pg_notify(${ channel }, ${ '' + payload })`
}
@@ -937,19 +937,28 @@ index f09c61c..4709ad4 100644
+ const first = typeof options === 'object' && options.first && sql.options.transaction_pipeline > sql.options.max_pipeline
+ ? options.first
+ : null
++ // GBrain (GBRA-156): `{ early }` sends every statement it accepts, in order, behind BEGIN before BEGIN's answer,
++ // on any pool that pipelines inside a transaction (a pipelining pool, or transaction_pipeline behind a pooler that
++ // does not). The first statement it refuses, and every later one, waits for the answer. If BEGIN fails the accepted
++ // statements run in autocommit, so `early` must accept only reads and transaction-local set_config, never a write.
++ const early = typeof options === 'object' && options.early
++ && (sql.options.transaction_pipeline > sql.options.max_pipeline || sql.options.max_pipeline > 0)
++ ? options.early
++ : null
+ typeof options === 'object' && (options = options.mode || '')
let savepoints = 0
, connection
, prepare = null
+ , opening = null
+ , firstSeen = false
++ , held = false
+ , written
try {
- await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
- return await Promise.race([
+ const begun = sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
-+ if (!first) {
++ if (!first && !early) {
+ await begun
+ return await Promise.race([
+ scope(connection, fn),
@@ -985,7 +994,7 @@ index f09c61c..4709ad4 100644
let uncaughtError
, result
-@@ -281,6 +482,8 @@ function Postgres(a, b) {
+@@ -281,6 +491,8 @@ function Postgres(a, b) {
return result
function savepoint(name, fn) {
@@ -994,7 +1003,7 @@ index f09c61c..4709ad4 100644
if (name && Array.isArray(name.raw))
return savepoint(sql => sql.apply(sql, arguments))
-@@ -290,18 +493,29 @@ function Postgres(a, b) {
+@@ -290,18 +502,33 @@ function Postgres(a, b) {
function handler(q) {
q.catch(e => uncaughtError || (uncaughtError = e))
@@ -1003,17 +1012,21 @@ index f09c61c..4709ad4 100644
- : c.execute(q) || move(c, full)
+ if (!reservation || c.reserved !== reservation)
+ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
-+ // GBrain (#6930): while BEGIN is unanswered only an accepted first statement is sent; the rest wait, in order. It
-+ // is accepted on its text (`$n` for each argument, as statementText builds it) only when every argument is a
-+ // parameter value: a fragment (a query, a helper, an identifier) would carry SQL the test never saw.
++ // GBrain (#6930, GBRA-156): while BEGIN is unanswered only accepted statements are sent (the first one for
++ // `first`; each one until one is refused for `early`); the rest wait, in order. A statement is accepted on its
++ // text (`$n` for each argument, as statementText builds it) only when every argument is a parameter value: a
++ // fragment (a query, a helper, an identifier) would carry SQL the test never saw.
+ if (opening) {
+ const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
-+ const early = !firstSeen
++ const test = early || !firstSeen && first
++ const sent = !held && test
+ && q.args.every(x => !(x instanceof Query || x instanceof Builder || x instanceof Identifier || Array.isArray(x) && x.some(y => y instanceof Query)))
-+ && first(strings.reduce((a, s, i) => a + '$' + i + s))
++ && test(strings.reduce((a, s, i) => a + '$' + i + s))
+ firstSeen = true
-+ if (!early)
++ if (!sent) {
++ held = true
+ return opening.then(() => handler(q), q.reject)
++ }
+ }
+ reservation.enqueue(q)
}
@@ -1030,7 +1043,7 @@ index f09c61c..4709ad4 100644
}
}
-@@ -351,7 +565,7 @@ function Postgres(a, b) {
+@@ -351,7 +578,7 @@ function Postgres(a, b) {
return new Promise((resolve, reject) => {
query.state
? query.active
@@ -1039,7 +1052,7 @@ index f09c61c..4709ad4 100644
: query.cancelled = { resolve, reject }
: (
queries.remove(query),
-@@ -362,6 +576,25 @@ function Postgres(a, b) {
+@@ -362,6 +589,25 @@ function Postgres(a, b) {
})
}
@@ -1065,7 +1078,7 @@ index f09c61c..4709ad4 100644
async function end({ timeout = null } = {}) {
if (ending)
return ending
-@@ -398,7 +631,14 @@ function Postgres(a, b) {
+@@ -398,7 +644,14 @@ function Postgres(a, b) {
move(c, ended)
}
@@ -1081,7 +1094,7 @@ index f09c61c..4709ad4 100644
if (queries.length === 0)
return move(c, open)
-@@ -418,12 +658,50 @@ function Postgres(a, b) {
+@@ -418,12 +671,50 @@ function Postgres(a, b) {
: move(c, full)
}
@@ -1133,7 +1146,7 @@ index f09c61c..4709ad4 100644
}
}
-@@ -444,7 +722,7 @@ function parseOptions(a, b) {
+@@ -444,7 +735,7 @@ function parseOptions(a, b) {
'timeout' in o && (console.log('The timeout option is deprecated, use idle_timeout instead'), o.idle_timeout = o.timeout) // eslint-disable-line
query.sslrootcert === 'system' && (query.ssl = 'verify-full')
@@ -1142,7 +1155,7 @@ index f09c61c..4709ad4 100644
const defaults = {
max : globalThis.Cloudflare ? 3 : 10,
ssl : false,
-@@ -453,6 +731,10 @@ function parseOptions(a, b) {
+@@ -453,6 +744,10 @@ function parseOptions(a, b) {
connect_timeout : 30,
max_lifetime : max_lifetime,
max_pipeline : 100,
@@ -1153,7 +1166,7 @@ index f09c61c..4709ad4 100644
backoff : backoff,
keep_alive : 60,
prepare : true,
-@@ -491,11 +773,19 @@ function parseOptions(a, b) {
+@@ -491,11 +786,19 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
@@ -1934,7 +1947,7 @@ index 1b1cccd..28f3e50 100644
seconds = typeof seconds === 'function' ? seconds() : seconds
if (!seconds)
diff --git a/src/index.js b/vendor/postgres/src/index.js
-index c7fba3d..abf09ed 100644
+index c7fba3dac..f93237cbd 100644
--- a/src/index.js
+++ b/vendor/postgres/src/index.js
@@ -62,10 +62,36 @@ function Postgres(a, b) {
@@ -1975,7 +1988,7 @@ index c7fba3d..abf09ed 100644
Object.assign(sql, {
get parameters() { return options.parameters },
largeObject: largeObject.bind(null, sql),
-@@ -200,58 +226,233 @@ function Postgres(a, b) {
+@@ -200,58 +226,242 @@ function Postgres(a, b) {
return await sql`select pg_notify(${ channel }, ${ '' + payload })`
}
@@ -2182,19 +2195,28 @@ index c7fba3d..abf09ed 100644
+ const first = typeof options === 'object' && options.first && sql.options.transaction_pipeline > sql.options.max_pipeline
+ ? options.first
+ : null
++ // GBrain (GBRA-156): `{ early }` sends every statement it accepts, in order, behind BEGIN before BEGIN's answer,
++ // on any pool that pipelines inside a transaction (a pipelining pool, or transaction_pipeline behind a pooler that
++ // does not). The first statement it refuses, and every later one, waits for the answer. If BEGIN fails the accepted
++ // statements run in autocommit, so `early` must accept only reads and transaction-local set_config, never a write.
++ const early = typeof options === 'object' && options.early
++ && (sql.options.transaction_pipeline > sql.options.max_pipeline || sql.options.max_pipeline > 0)
++ ? options.early
++ : null
+ typeof options === 'object' && (options = options.mode || '')
let savepoints = 0
, connection
, prepare = null
+ , opening = null
+ , firstSeen = false
++ , held = false
+ , written
try {
- await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
- return await Promise.race([
+ const begun = sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
-+ if (!first) {
++ if (!first && !early) {
+ await begun
+ return await Promise.race([
+ scope(connection, fn),
@@ -2230,7 +2252,7 @@ index c7fba3d..abf09ed 100644
let uncaughtError
, result
-@@ -281,6 +482,8 @@ function Postgres(a, b) {
+@@ -281,6 +491,8 @@ function Postgres(a, b) {
return result
function savepoint(name, fn) {
@@ -2239,7 +2261,7 @@ index c7fba3d..abf09ed 100644
if (name && Array.isArray(name.raw))
return savepoint(sql => sql.apply(sql, arguments))
-@@ -290,18 +493,29 @@ function Postgres(a, b) {
+@@ -290,18 +502,33 @@ function Postgres(a, b) {
function handler(q) {
q.catch(e => uncaughtError || (uncaughtError = e))
@@ -2248,17 +2270,21 @@ index c7fba3d..abf09ed 100644
- : c.execute(q) || move(c, full)
+ if (!reservation || c.reserved !== reservation)
+ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
-+ // GBrain (#6930): while BEGIN is unanswered only an accepted first statement is sent; the rest wait, in order. It
-+ // is accepted on its text (`$n` for each argument, as statementText builds it) only when every argument is a
-+ // parameter value: a fragment (a query, a helper, an identifier) would carry SQL the test never saw.
++ // GBrain (#6930, GBRA-156): while BEGIN is unanswered only accepted statements are sent (the first one for
++ // `first`; each one until one is refused for `early`); the rest wait, in order. A statement is accepted on its
++ // text (`$n` for each argument, as statementText builds it) only when every argument is a parameter value: a
++ // fragment (a query, a helper, an identifier) would carry SQL the test never saw.
+ if (opening) {
+ const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
-+ const early = !firstSeen
++ const test = early || !firstSeen && first
++ const sent = !held && test
+ && q.args.every(x => !(x instanceof Query || x instanceof Builder || x instanceof Identifier || Array.isArray(x) && x.some(y => y instanceof Query)))
-+ && first(strings.reduce((a, s, i) => a + '$' + i + s))
++ && test(strings.reduce((a, s, i) => a + '$' + i + s))
+ firstSeen = true
-+ if (!early)
++ if (!sent) {
++ held = true
+ return opening.then(() => handler(q), q.reject)
++ }
+ }
+ reservation.enqueue(q)
}
@@ -2275,7 +2301,7 @@ index c7fba3d..abf09ed 100644
}
}
-@@ -351,7 +565,7 @@ function Postgres(a, b) {
+@@ -351,7 +578,7 @@ function Postgres(a, b) {
return new Promise((resolve, reject) => {
query.state
? query.active
@@ -2284,7 +2310,7 @@ index c7fba3d..abf09ed 100644
: query.cancelled = { resolve, reject }
: (
queries.remove(query),
-@@ -362,6 +576,25 @@ function Postgres(a, b) {
+@@ -362,6 +589,25 @@ function Postgres(a, b) {
})
}
@@ -2310,7 +2336,7 @@ index c7fba3d..abf09ed 100644
async function end({ timeout = null } = {}) {
if (ending)
return ending
-@@ -398,7 +631,14 @@ function Postgres(a, b) {
+@@ -398,7 +644,14 @@ function Postgres(a, b) {
move(c, ended)
}
@@ -2326,7 +2352,7 @@ index c7fba3d..abf09ed 100644
if (queries.length === 0)
return move(c, open)
-@@ -418,12 +658,50 @@ function Postgres(a, b) {
+@@ -418,12 +671,50 @@ function Postgres(a, b) {
: move(c, full)
}
@@ -2378,7 +2404,7 @@ index c7fba3d..abf09ed 100644
}
}
-@@ -444,7 +722,7 @@ function parseOptions(a, b) {
+@@ -444,7 +735,7 @@ function parseOptions(a, b) {
'timeout' in o && (console.log('The timeout option is deprecated, use idle_timeout instead'), o.idle_timeout = o.timeout) // eslint-disable-line
query.sslrootcert === 'system' && (query.ssl = 'verify-full')
@@ -2387,7 +2413,7 @@ index c7fba3d..abf09ed 100644
const defaults = {
max : globalThis.Cloudflare ? 3 : 10,
ssl : false,
-@@ -453,6 +731,10 @@ function parseOptions(a, b) {
+@@ -453,6 +744,10 @@ function parseOptions(a, b) {
connect_timeout : 30,
max_lifetime : max_lifetime,
max_pipeline : 100,
@@ -2398,7 +2424,7 @@ index c7fba3d..abf09ed 100644
backoff : backoff,
keep_alive : 60,
prepare : true,
-@@ -491,11 +773,19 @@ function parseOptions(a, b) {
+@@ -491,11 +786,19 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
@@ -2489,7 +2515,7 @@ index 7c7c2b9..d462498 100644
return '$' + (types.push(
diff --git a/types/index.d.ts b/vendor/postgres/types/index.d.ts
-index 13c3432..03a1023 100644
+index 13c3432f7..1c4a50bbb 100644
--- a/types/index.d.ts
+++ b/vendor/postgres/types/index.d.ts
@@ -119,6 +119,63 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {
@@ -2582,7 +2608,7 @@ index 13c3432..03a1023 100644
end(options?: { timeout?: number | undefined } | undefined): Promise<void>;
-@@ -716,11 +776,19 @@ declare namespace postgres {
+@@ -716,11 +776,21 @@ 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>>;
@@ -2590,8 +2616,10 @@ index 13c3432..03a1023 100644
+ * GBrain (#6930): with transaction_pipeline in force, the first statement `first` accepts (its text, `$n` for
+ * parameters) is sent behind BEGIN before BEGIN's answer. If BEGIN fails it runs in autocommit, so `first` must
+ * accept only a read or a transaction-local set_config, never a write.
++ * GBrain (GBRA-156): on any pool that pipelines inside a transaction, every statement `early` accepts, in order, is
++ * sent behind BEGIN before BEGIN's answer; the first it refuses, and every later one, waits. The same rule applies.
+ */
-+ begin<T>(options: { mode?: string; first?: (statement: string) => boolean }, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
++ begin<T>(options: { mode?: string; first?: (statement: string) => boolean; early?: (statement: string) => boolean }, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
- reserve(): Promise<ReservedSql<TTypes>>
+ reserve(options?: { signal?: AbortSignal }): Promise<ReservedSql<TTypes>>
@@ -2603,7 +2631,7 @@ index 13c3432..03a1023 100644
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 +796,8 @@ declare namespace postgres {
+@@ -728,6 +798,8 @@ declare namespace postgres {
}
interface ReservedSql<TTypes extends Record<string, unknown> = {}> extends Sql<TTypes> {
diff --git a/scripts/bench/production-soak/README.md b/scripts/bench/production-soak/README.md
index c1b20ea52d..df6b9342b6 100644
--- a/scripts/bench/production-soak/README.md
+++ b/scripts/bench/production-soak/README.md
@@ -15,6 +15,7 @@ Weekly (and on dispatch) in `.github/workflows/production-soak.yml`; never in th
| `lib.ts` | Topology: Postgres, a session-mode PgBouncer capped at 25 clients (the 26th is refused, the EMAXCONNSESSION shape), a transaction-mode PgBouncer, and toxiproxy latency in front of both. `database_url` is the transaction lane and `GBRAIN_DIRECT_DATABASE_URL` the session lane. |
| `soak.ts` | The production topology for `--hours`: one resident `gbrain serve --http` that owns sync (`sync.on_commit=true`), one `gbrain jobs work`, MCP stdio readers (warm, remote callers), CLI readers (cold), an external writer committing named paths every few minutes, put/remember through CLI and MCP, `extract --stale` and `embed --stale`, and samplers. |
| `scoreboard.ts` | Turns `events.jsonl` into `scoreboard.json` and `scoreboard.md`; `--combine <dir>` merges cells. |
+| `stage-probe.ts` | On a loaded brain (`--work` with `ready.json`): one warm stdio `gbrain serve` behind the topology at `--rtt-ms`, the mock embedder and reranker, and `--n` search calls whose `_meta.retrieval.timings` (stage and part medians) are written to `<out>/calls.jsonl` and summarized; `--trace` also records every statement (`GBRAIN_SQL_TRACE`). Where the server stage of a warm search spends its time at scale. |
| `run.sh`, `vm-setup.sh`, `ubicloud.sh` | One cell end to end; VM bootstrap; one Ubicloud VM per latency with an expiring name. |
## Scoreboard
diff --git a/scripts/bench/production-soak/stage-probe.ts b/scripts/bench/production-soak/stage-probe.ts
new file mode 100644
index 0000000000..5307c84072
--- /dev/null
+++ b/scripts/bench/production-soak/stage-probe.ts
@@ -0,0 +1,70 @@
+#!/usr/bin/env bun
+/**
+ * Warm search stage probe on a loaded production-soak brain (GBRA-156): the
+ * soak topology at --rtt-ms, the loopback mock provider with --embed-ms and
+ * --rerank-ms, one stdio `gbrain serve` (a warm MCP caller), and --n search
+ * calls whose `_meta.retrieval.timings` (stages_ms and parts_ms) are written
+ * to <out>/calls.jsonl with the wall time. --trace records GBRAIN_SQL_TRACE.
+ *
+ * bun scripts/bench/production-soak/stage-probe.ts --fixture ~/soak/fixture --work ~/soak/work --out ~/probe \
+ * [--rtt-ms 66] [--n 40] [--warmup 5] [--embed-ms 200] [--rerank-ms 300] [--trace]
+ */
+import { appendFileSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import postgres from '#postgres';
+import { startMockProviders } from '../retrieval-scale/mock-providers.ts';
+import { McpClient, spawnChild } from '../sync-freshness-lib.ts';
+import { childEnv, REPO, startTopology, writeConfig } from './lib.ts';
+
+const argv = process.argv.slice(2);
+const flag = (name: string, fallback = '') => { const i = argv.indexOf('--' + name); return i >= 0 ? argv[i + 1]! : fallback; };
+const FIXTURE = resolve(flag('fixture')), WORK = resolve(flag('work')), OUT = resolve(flag('out'));
+const RTT = Number(flag('rtt-ms', '66')), N = Number(flag('n', '40')), WARMUP = Number(flag('warmup', '5'));
+const EMBED = Number(flag('embed-ms', '200')), RERANK = Number(flag('rerank-ms', '300')), TRACE = argv.includes('--trace');
+const manifest = JSON.parse(readFileSync(join(FIXTURE, 'manifest.json'), 'utf8'));
+const ready = JSON.parse(readFileSync(join(WORK, 'ready.json'), 'utf8'));
+const HOME = join(WORK, 'home');
+
+async function queries(directUrl: string): Promise<string[]> {
+ const sql = postgres(directUrl, { max: 1, onnotice: () => {} });
+ const rows = await sql.unsafe("SELECT p.title, left(c.chunk_text, 600) AS text FROM pages p JOIN content_chunks c ON c.page_id = p.id AND c.chunk_index = 0 WHERE p.deleted_at IS NULL AND p.frontmatter->>'visibility' IS NULL AND p.type <> 'chat' ORDER BY md5(p.id::text) LIMIT 200") as Array<{ title: string; text: string }>;
+ await sql.end();
+ return rows.map((r, i) => {
+ const words = r.text.replace(/[^a-z\s]/gi, ' ').split(/\s+/).filter(w => w.length > 3);
+ const k = 2 + (i % 3), at = (i * 7919) % Math.max(1, words.length - k);
+ const name = i % 3 === 0 ? r.title.split(/\s+/).slice(0, 2).join(' ') : '';
+ return [name, ...words.slice(at, at + k)].filter(Boolean).join(' ') || r.title;
+ });
+}
+
+rmSync(OUT, { recursive: true, force: true });
+mkdirSync(OUT, { recursive: true });
+const topo = await startTopology(WORK, undefined, undefined, true);
+await topo.setRtt(0);
+const qs = await queries(topo.direct(ready.db));
+await topo.setRtt(RTT);
+const mock = startMockProviders({ manifest: { seed: manifest.options.seed, chunks: manifest.pages * 4, pages: manifest.pages, dims: 1536 }, embedMs: EMBED, rerankMs: RERANK });
+writeConfig(HOME, topo.txn(ready.db), mock.url);
+const env = childEnv(HOME, mock.url, { GBRAIN_DIRECT_DATABASE_URL: topo.session(ready.db), ...(TRACE ? { GBRAIN_SQL_TRACE: join(OUT, 'trace-serve.jsonl') } : {}) });
+const child = spawnChild([process.execPath, join(REPO, 'src', 'cli.ts'), 'serve'], { cwd: HOME, env, logFile: join(OUT, 'serve.log'), stdin: true });
+const client = new McpClient(child);
+await client.init();
+for (let i = 0; i < WARMUP + N; i++) {
+ const query = qs[i % qs.length]!;
+ const t0 = performance.timeOrigin + performance.now();
+ const r = await client.request('tools/call', { name: 'search', arguments: { query } }, 120_000);
+ const t1 = performance.timeOrigin + performance.now();
+ if (i < WARMUP) continue;
+ const timings = r.result?._meta?.retrieval?.timings;
+ appendFileSync(join(OUT, 'calls.jsonl'), JSON.stringify({ i, query_words: query.split(' ').length, t0, t1, ms: Math.round(t1 - t0), error: r.error ? String(JSON.stringify(r.error)).slice(0, 200) : undefined, timings }) + '\n');
+}
+child.kill();
+mock.stop();
+const rows = readFileSync(join(OUT, 'calls.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l));
+const med = (xs: number[]) => { const s = xs.filter(x => typeof x === 'number').sort((a, b) => a - b); return s.length ? s[Math.floor((s.length - 1) / 2)] : null; };
+const keys = new Set<string>();
+for (const r of rows) { for (const k of Object.keys(r.timings?.stages_ms ?? {})) keys.add(k); for (const [s, parts] of Object.entries(r.timings?.parts_ms ?? {})) for (const p of Object.keys(parts as object)) keys.add(s + '.' + p); }
+const val = (r: any, k: string) => k.includes('.') ? r.timings?.parts_ms?.[k.split('.')[0]!]?.[k.split('.')[1]!] : r.timings?.stages_ms?.[k];
+console.log('wall p50', med(rows.map(r => r.ms)), 'total p50', med(rows.map(r => r.timings?.total_ms)), 'other p50', med(rows.map(r => r.timings?.other_ms)), 'errors', rows.filter(r => r.error).length);
+for (const k of [...keys].sort()) console.log(k.padEnd(32), 'p50', med(rows.map(r => val(r, k))), 'max', Math.max(...rows.map(r => val(r, k) ?? 0)));
+process.exit(0);
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 14d0b6b5a8..fbdc5f513e 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,7 +16,7 @@ src/commands/sync.ts 550 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3337 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due; +5 #7241: CycleOpts.onPhaseStart and its best-effort call in timePhase, so the autopilot-cycle job writes its current phase to minion_jobs.progress
src/core/cycle/synthesize.ts 3232 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites); +2 GBRA-161 PR 4 (#7065): the synthesize phase activates each synthesized transcript's outputs as its generation (activateSynthesisGenerations import and call site; logic in cycle/synthesize-generations.ts)
src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guard
-src/core/engine.ts 2848 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +9 GBRA-177: TakesListOpts.oldestFirst/sinceOnOrBefore/ungradedFirst for the grade_takes window (interface fields cannot move; SQL in engine-sql/takes.ts): 2832 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move
+src/core/engine.ts 2855 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +9 GBRA-177: TakesListOpts.oldestFirst/sinceOnOrBefore/ungradedFirst for the grade_takes window (interface fields cannot move; SQL in engine-sql/takes.ts): 2832 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move; +7 GBRA-156: TransactionOptions.pipelineEarly (search read bodies go out behind BEGIN; predicate in postgres-engine/search-settings.ts); interface fields cannot move
src/core/import-file.ts 2075 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation; +9 #7172: kept chunk rows move to their new index and a bounded managed publication defers its chunk replacement (logic in page-state/chunk-moves.ts and page-state/projections.ts continueDeferredProjection); merge v0.60.332.0: #7172 and master growth compose at 2075
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 244 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); 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; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import
diff --git a/src/core/engine-sql/titles.ts b/src/core/engine-sql/titles.ts
index 14e4bc6a39..e0a04b300d 100644
--- a/src/core/engine-sql/titles.ts
+++ b/src/core/engine-sql/titles.ts
@@ -58,6 +58,8 @@ import type { ScopedReadRunner } from './cjk-search.ts';
*/
export type SearchTitlesRunDialect = Omit<SearchTitlesDialect, 'chunkManifest'> & {
chunkManifest?: (exec: ScopedRead) => Promise<boolean>;
+ /** Transaction-local settings for every attempt (Postgres: the keyword statement's work_mem, so a common term's bitmap stays exact). */
+ statementSettings?: Readonly<Record<string, string>>;
};
export async function searchTitles(
@@ -79,6 +81,7 @@ export async function searchTitles(
const preferIndex = relaxed && dialect.relaxedPrefersIndex && !statement.safeChunks;
const settings = {
...(dialect.statementTimeout ? { statement_timeout: dialect.statementTimeout } : {}),
+ ...dialect.statementSettings,
...(preferIndex ? { enable_seqscan: 'off' } : {}),
};
const params = [...statement.params];
diff --git a/src/core/engine.ts b/src/core/engine.ts
index f05b39d30e..fe2ee98548 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -146,6 +146,13 @@ export interface TransactionOptions {
* (`isPersistenceDeclaration`). Ignored by PGLite and inside a transaction.
*/
pipelineFirst?: (statement: string) => boolean;
+ /**
+ * GBRA-156: Postgres on a pool that pipelines inside a transaction sends every statement this accepts, in order,
+ * behind BEGIN before BEGIN's answer; the first it refuses, and every later one, waits for the answer. If BEGIN fails
+ * the accepted statements run in autocommit, so pass only a test that accepts reads and transaction-local
+ * set_config (`isPipelinableSearchRead`). Ignored by PGLite and inside a transaction.
+ */
+ pipelineEarly?: (statement: string) => boolean;
}
/** Input row for addLinksBatch. Optional fields default to '' (matches NOT NULL DDL). */
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 3097330709..8ae4c78b96 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -647,6 +647,7 @@ CREATE INDEX IF NOT EXISTS idx_files_hash ON files(content_hash);
ALTER TABLE pages ADD COLUMN IF NOT EXISTS search_vector tsvector;
CREATE INDEX IF NOT EXISTS idx_pages_search ON pages USING GIN(search_vector);
+CREATE INDEX IF NOT EXISTS idx_pages_title_search ON pages USING GIN (ts_filter(search_vector, '{a}'));
CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET search_path = pg_catalog, public AS \$\$
DECLARE
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 5973505740..3eac28fb68 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -125,7 +125,7 @@ import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from
import { PageMissingError } from './engine-errors.ts';
import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';
import { acquireInitSchemaAdvisoryLock } from './postgres-engine/init-schema-lock.ts';
-import { SEARCH_JIT_OFF, withSearchJitOff, withSearchSettings, type SearchSettings } from './postgres-engine/search-settings.ts';
+import { isPipelinableSearchRead, SEARCH_JIT_OFF, withSearchJitOff, withSearchSettings, type SearchSettings } from './postgres-engine/search-settings.ts';
import { loadKeywordStatementTimeout } from './postgres-engine/keyword-statement-timeout.ts';
import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';
import * as factsImpl from './engine-sql/facts.ts';
@@ -406,7 +406,7 @@ export class PostgresEngine implements BrainEngine {
answered = true;
resolve(result);
return result;
- }).catch(error => { if (!answered) reject(error); });
+ }, { pipelineEarly: isPipelinableSearchRead }).catch(error => { if (!answered) reject(error); });
});
}
@@ -689,7 +689,9 @@ export class PostgresEngine implements BrainEngine {
if (!this._pageTransaction) this.checkoutGauge.acquire('tx');
try {
// GBRA-156: the pool's begin takes `first`; a nested transaction's begin (a savepoint) takes only the callback.
- const begin = (run: (handle: unknown) => Promise<unknown>) => opts?.pipelineFirst && !this._pageTransaction ? conn.begin({ first: opts.pipelineFirst }, run) : conn.begin(run);
+ const begin = (run: (handle: unknown) => Promise<unknown>) => this._pageTransaction ? conn.begin(run)
+ : opts?.pipelineEarly ? conn.begin({ early: opts.pipelineEarly }, run)
+ : opts?.pipelineFirst ? conn.begin({ first: opts.pipelineFirst }, run) : conn.begin(run);
return await holdSearchConnection(() => withCommitChecks(checks => withTransactionAbort(opts?.signal, attach => withHeldPageKeys(this._pageTransaction ? this._heldPageKeys : null, held => begin(async (handle) => {
attach(handle as Discardable);
if (!this._pageTransaction) this.checkoutGauge.checkedOut();
@@ -1222,7 +1224,7 @@ export class PostgresEngine implements BrainEngine {
(read, settings) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true, settings }),
query,
opts,
- { statementTimeout: await this.keywordStatementTimeoutSetting(), relaxedPrefersIndex: true, staleProbe: false, chunkManifest: exec => chunkManifestReads(this, exec) },
+ { statementTimeout: await this.keywordStatementTimeoutSetting(), statementSettings: KEYWORD_STATEMENT_SETTINGS, relaxedPrefersIndex: true, staleProbe: false, chunkManifest: exec => chunkManifestReads(this, exec) },
);
}
diff --git a/src/core/postgres-engine/search-settings.ts b/src/core/postgres-engine/search-settings.ts
index 6c2ce43c93..cb75cb912c 100644
--- a/src/core/postgres-engine/search-settings.ts
+++ b/src/core/postgres-engine/search-settings.ts
@@ -59,6 +59,22 @@ export function searchSettingsStatement(settings: SearchSettings): { sql: string
};
}
+const SETTINGS_STATEMENT = /^SELECT set_config\('[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)?', \$\d+, true\)(, set_config\('[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)?', \$\d+, true\))*$/;
+const READ_START = /^\s*(--[^\n]*\n\s*)*(select|with)\b/i;
+const NOT_A_PLAIN_READ = /;|\b(insert|update|delete|merge|truncate|copy|lock|call|do|nextval|setval|set_config|pg_notify|pg_advisory\w*|pg_try_advisory\w*|txid_current|pg_current_xact_id|lo_\w+|dblink\w*)\b|\bfor\s+(no\s+key\s+|key\s+)?share\b/i;
+
+/**
+ * GBRA-156: what a search read transaction may send behind BEGIN before BEGIN's answer (`TransactionOptions.pipelineEarly`).
+ * If BEGIN fails, an accepted statement runs in autocommit, so this accepts the settings statement
+ * `searchSettingsStatement` builds (transaction-local, a no-op outside a transaction) and single SELECT or WITH
+ * statements (after any leading line comments) that name no write, lock, sequence, notification or session-setting keyword. A refusal costs only the
+ * round trip: the statement waits for BEGIN's answer, as every statement did before.
+ */
+export function isPipelinableSearchRead(statement: string): boolean {
+ if (SETTINGS_STATEMENT.test(statement)) return true;
+ return READ_START.test(statement) && !NOT_A_PLAIN_READ.test(statement);
+}
+
/** `SELECT current_setting('<name>', true) AS "<name>", …`: the caller's values, one row. */
function currentSettingsStatement(keys: string[]): string {
return `SELECT ${keys.map(name => `current_setting('${name}', true) AS "${name}"`).join(', ')}`;
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 5392093c71..f4dbe77c17 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -1173,6 +1173,8 @@ CREATE INDEX IF NOT EXISTS idx_file_migration_ledger_status
ALTER TABLE pages ADD COLUMN IF NOT EXISTS search_vector tsvector;
CREATE INDEX IF NOT EXISTS idx_pages_search ON pages USING GIN(search_vector);
+-- GBRA-156 (v267): the title arm's title-only predicate reads the weight-A slice (the title alone).
+CREATE INDEX IF NOT EXISTS idx_pages_title_search ON pages USING GIN (ts_filter(search_vector, '{a}'));
-- Function to rebuild search_vector for a page
-- #2704: compiled_truth (unbounded whole-page body) deliberately NOT
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 713bc06f24..0446a17bcc 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 266;
+export const LATEST_SCHEMA_VERSION = 267;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 0026ae9b18..2df9303dd2 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -267,6 +267,7 @@ import { v263 } from './v263-try-jsonb-function.ts';
import { v264 } from './v264-set-based-fact-insert-guards.ts';
import { v265 } from './v265-derived-generations.ts';
import { v266 } from './v266-derived-generation-activations.ts';
+import { v267 } from './v267-pages-title-search-index.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -532,4 +533,5 @@ export const MIGRATIONS: Migration[] = [
v264,
v265,
v266,
+ v267,
];
diff --git a/src/core/schema-migrations/v267-pages-title-search-index.ts b/src/core/schema-migrations/v267-pages-title-search-index.ts
new file mode 100644
index 0000000000..5b60aef79d
--- /dev/null
+++ b/src/core/schema-migrations/v267-pages-title-search-index.ts
@@ -0,0 +1,32 @@
+import type { Migration } from './types.ts';
+import { buildIndexOnline, migrationNotice } from './helpers.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// GBRA-156: the title arm's title-only predicate (remote callers and every OR
+// re-run, engine-sql/titles.ts) matches the weight-A slice of
+// pages.search_vector, which carries the title and only the title at weight A.
+// idx_pages_search indexes the whole vector, and a GIN index cannot check a
+// weight, so a term in timeline text (weight C) made its page a candidate that
+// the heap recheck then threw away: at 600k pages about nine of every ten
+// candidates of a typical OR re-run. This expression index holds only the
+// title lexemes, so the predicate `ts_filter(search_vector, '{a}') @@ q` reads
+// title matches alone. Built online (CONCURRENTLY on Postgres); an interrupted
+// build leaves an INVALID index that the next initSchema drops and rebuilds.
+export const PAGES_TITLE_SEARCH_INDEX = {
+ name: 'idx_pages_title_search',
+ table: 'pages',
+ sql: "CREATE INDEX IF NOT EXISTS idx_pages_title_search ON pages USING GIN (ts_filter(search_vector, '{a}'))",
+};
+
+export const v267: Migration = {
+ version: 267,
+ name: 'pages_title_search_index',
+ idempotent: true,
+ transaction: false,
+ sql: '',
+ handler: async engine => {
+ await buildIndexOnline(engine, 267, PAGES_TITLE_SEARCH_INDEX, { notice: migrationNotice });
+ },
+};
diff --git a/src/core/search/collapse.ts b/src/core/search/collapse.ts
index d208bacdba..0366f51e6c 100644
--- a/src/core/search/collapse.ts
+++ b/src/core/search/collapse.ts
@@ -130,26 +130,52 @@ export interface PageFacts { target: string | null; body: string | null; bodyCha
/**
* Per page id: the frontmatter redirect target, the body's length (bounded prefix: a body under the bound is whole),
- * and, for the head, an identity hash of a substantial body and its leading words. Ids already in `cache` are not read again.
+ * and, for `bodyIds`, an identity hash of a substantial body and its leading words. Every id gets an entry: a page
+ * the read does not return has no facts.
*/
-async function readPageFacts(engine: Pick<BrainEngine, 'executeRaw'>, allIds: number[], bodyIds: number[], cache: Map<number, PageFacts>): Promise<Map<number, PageFacts>> {
+async function readFactRows(engine: Pick<BrainEngine, 'executeRaw'>, ids: number[], bodyIds: number[]): Promise<Map<number, PageFacts>> {
+ const body = `btrim(COALESCE(${boundedBodyPrefixSql('p')}, ''))`;
+ const rows = await engine.executeRaw<{ id: number; target: string | null; body: string | null; body_chars: number | null; lead: string | null }>(
+ `SELECT p.id,
+ COALESCE(NULLIF(btrim(p.frontmatter->>'redirect_to'), ''), NULLIF(btrim(p.frontmatter->>'redirect'), ''),
+ NULLIF(btrim(p.frontmatter->>'merged_into'), ''),
+ CASE WHEN ${STATUS_REDIRECT} THEN NULLIF(btrim(p.frontmatter->>'superseded_by'), '') END) AS target,
+ length(${body}) AS body_chars,
+ CASE WHEN p.id = ANY($2::int[]) AND length(${body}) >= ${IDENTICAL_BODY_MIN_CHARS} THEN md5(${body}) END AS body,
+ CASE WHEN p.id = ANY($2::int[]) THEN left(${body}, ${OVERLAP_PREFIX_CHARS}) END AS lead
+ FROM pages p WHERE p.id = ANY($1::int[])`,
+ [ids, bodyIds],
+ );
+ const facts = new Map<number, PageFacts>(ids.map(id => [id, { target: null, body: null, bodyChars: null, words: null }]));
+ for (const r of rows) facts.set(Number(r.id), { target: r.target, body: r.body, bodyChars: r.body_chars === null ? null : Number(r.body_chars), words: wordSet(r.lead) });
+ return facts;
+}
+
+/**
+ * GBRA-156: the facts of every page in `ids`, body identity included, read now. Hybrid search starts it for the fused
+ * pages beside the post-fusion reads; collapseResults then takes its pages' entries from it (body identity only for
+ * the pages it compares, as its own read would) instead of a round trip of its own. Null when the read fails.
+ */
+export function prefetchPageFacts(engine: Pick<BrainEngine, 'executeRaw'>, ids: number[]): Promise<Map<number, PageFacts> | null> {
+ const valid = [...new Set(ids)].filter(id => Number.isSafeInteger(id) && id > 0);
+ return valid.length ? readFactRows(engine, valid, valid).catch(() => null) : Promise.resolve(null);
+}
+
+/** The facts of `allIds` into `cache` (ids already there are not read again; `prefetched` entries are not read at all). */
+async function readPageFacts(engine: Pick<BrainEngine, 'executeRaw'>, allIds: number[], bodyIds: number[], cache: Map<number, PageFacts>,
+ prefetched?: Promise<Map<number, PageFacts> | null>): Promise<Map<number, PageFacts>> {
const ids = allIds.filter(id => !cache.has(id));
if (ids.length === 0) return cache;
- const body = `btrim(COALESCE(${boundedBodyPrefixSql('p')}, ''))`;
+ const early = prefetched ? await prefetched : null;
+ const bodies = new Set(bodyIds);
+ for (const id of ids) {
+ const known = early?.get(id);
+ if (known) cache.set(id, bodies.has(id) ? known : { ...known, body: null, words: null });
+ }
+ const unread = ids.filter(id => !cache.has(id));
+ if (unread.length === 0) return cache;
try {
- const rows = await engine.executeRaw<{ id: number; target: string | null; body: string | null; body_chars: number | null; lead: string | null }>(
- `SELECT p.id,
- COALESCE(NULLIF(btrim(p.frontmatter->>'redirect_to'), ''), NULLIF(btrim(p.frontmatter->>'redirect'), ''),
- NULLIF(btrim(p.frontmatter->>'merged_into'), ''),
- CASE WHEN ${STATUS_REDIRECT} THEN NULLIF(btrim(p.frontmatter->>'superseded_by'), '') END) AS target,
- length(${body}) AS body_chars,
- CASE WHEN p.id = ANY($2::int[]) AND length(${body}) >= ${IDENTICAL_BODY_MIN_CHARS} THEN md5(${body}) END AS body,
- CASE WHEN p.id = ANY($2::int[]) THEN left(${body}, ${OVERLAP_PREFIX_CHARS}) END AS lead
- FROM pages p WHERE p.id = ANY($1::int[])`,
- [ids, bodyIds],
- );
- for (const id of ids) cache.set(id, { target: null, body: null, bodyChars: null, words: null });
- for (const r of rows) cache.set(Number(r.id), { target: r.target, body: r.body, bodyChars: r.body_chars === null ? null : Number(r.body_chars), words: wordSet(r.lead) });
+ for (const [id, facts] of await readFactRows(engine, unread, bodyIds)) cache.set(id, facts);
} catch {
// fail-open: no frontmatter redirects or body identity this call
}
@@ -200,7 +226,7 @@ async function readTarget(engine: BrainEngine, sourceId: string, slug: string, s
export async function collapseResults(
engine: BrainEngine,
results: SearchResult[],
- opts: IdentityTierOpts & { onDecision?: (d: CollapseDecision) => void; facts?: Map<number, PageFacts> } = {},
+ opts: IdentityTierOpts & { onDecision?: (d: CollapseDecision) => void; facts?: Map<number, PageFacts>; prefetched?: Promise<Map<number, PageFacts> | null> } = {},
): Promise<SearchResult[]> {
if (results.length === 0) return results;
const pages = new Map<string, SearchResult[]>();
@@ -216,7 +242,7 @@ export async function collapseResults(
const slugCount = new Map<string, number>();
for (const rows of pages.values()) slugCount.set(rows[0].slug, (slugCount.get(rows[0].slug) ?? 0) + 1);
const compared = [...pages.keys()].filter((k, i) => i < FAMILY_HEAD || slugCount.get(pages.get(k)![0].slug)! > 1);
- const facts = await readPageFacts(engine, [...pages.keys()].map(idOf).filter(valid), compared.map(idOf).filter(valid), opts.facts ?? new Map());
+ const facts = await readPageFacts(engine, [...pages.keys()].map(idOf).filter(valid), compared.map(idOf).filter(valid), opts.facts ?? new Map(), opts.prefetched);
const decision: CollapseDecision = { twins: 0, redirects: 0, families: 0, redirect_reads: 0 };
// Redirect stubs and their targets (same source).
diff --git a/src/core/search/connection-budget.ts b/src/core/search/connection-budget.ts
index 000c2e7297..22d880fa7f 100644
--- a/src/core/search/connection-budget.ts
+++ b/src/core/search/connection-budget.ts
@@ -16,13 +16,23 @@ import { AsyncLocalStorage } from 'node:async_hooks';
/** The most pooled connections one search or query op holds at once. */
export const SEARCH_CONNECTION_LIMIT = 4;
-interface Budget { free: number; waiters: Array<() => void> }
+interface Budget { free: number; waiters: Array<() => void>; urgent: Array<() => void> }
const budgets = new AsyncLocalStorage<Budget | null>();
+const urgency = new AsyncLocalStorage<boolean>();
/** Run `fn` under one budget; a nested call shares the enclosing one. */
export function withSearchConnectionBudget<T>(fn: () => Promise<T>): Promise<T> {
if (budgets.getStore()) return fn();
- return budgets.run({ free: SEARCH_CONNECTION_LIMIT, waiters: [] }, fn);
+ return budgets.run({ free: SEARCH_CONNECTION_LIMIT, waiters: [], urgent: [] }, fn);
+}
+
+/**
+ * GBRA-156: reads `fn` starts take the next free slot ahead of every waiting read started outside one. The
+ * retrieval arms (keyword, title, vector) set the search's critical path; the reads a search starts early for its
+ * response (the keyword count, entity resolution) only need to finish before the response is built.
+ */
+export function withUrgentSearchConnections<T>(fn: () => Promise<T>): Promise<T> {
+ return urgency.run(true, fn);
}
/** Hold one slot of the current budget while `fn` runs; without a budget, run it directly. */
@@ -30,11 +40,11 @@ export async function holdSearchConnection<T>(fn: () => Promise<T>): Promise<T>
const budget = budgets.getStore();
if (!budget) return fn();
if (budget.free > 0) budget.free -= 1;
- else await new Promise<void>(resolve => budget.waiters.push(resolve));
+ else await new Promise<void>(resolve => (urgency.getStore() ? budget.urgent : budget.waiters).push(resolve));
try {
return await budgets.run(null, fn);
} finally {
- const next = budget.waiters.shift();
+ const next = budget.urgent.shift() ?? budget.waiters.shift();
if (next) next(); else budget.free += 1;
}
}
diff --git a/src/core/search/cosine-rescore.ts b/src/core/search/cosine-rescore.ts
index 86eb498247..aad3a0bdf2 100644
--- a/src/core/search/cosine-rescore.ts
+++ b/src/core/search/cosine-rescore.ts
@@ -43,63 +43,91 @@ export async function cosineReScore(
attribute = false,
onFallback?: () => void,
): Promise<SearchResult[]> {
+ return startCosineReScore(engine, results, queryEmbedding, column, imageSpace, onFallback)(results, attribute);
+}
+
+/**
+ * GBRA-156: start the cosine reads for `candidates` now and re-score later. Fusion only merges its input lists, so
+ * the fused rows' chunks are among the candidates' and hybrid search starts these reads beside the reads that run
+ * before fusion instead of a round trip after them. Only the re-scored rows' own cosines count, so the result is the
+ * one `cosineReScore` returns for those rows.
+ */
+export function startCosineReScore(
+ engine: BrainEngine,
+ candidates: SearchResult[],
+ queryEmbedding: Float32Array,
+ column: string = 'embedding',
+ imageSpace?: { queryEmbedding: Float32Array; column: string },
+ onFallback?: () => void,
+): (results: SearchResult[], attribute?: boolean) => Promise<SearchResult[]> {
// 'both' mode: image-arm rows live in the image space (image column,
// multimodal query vector); everything else in the text space.
const inImageSpace = (r: SearchResult): boolean => imageSpace !== undefined && r.modality === 'image';
- const idsFor = (image: boolean) => results
+ const idsFor = (rows: SearchResult[], image: boolean) => rows
.filter(r => inImageSpace(r) === image)
.map(r => r.chunk_id)
.filter((id): id is number => id != null);
- const chunkIds = idsFor(false);
- const imageChunkIds = idsFor(true);
-
- if (chunkIds.length === 0 && imageChunkIds.length === 0) return results;
-
- let cosines = new Map<number, number>();
- let imageCosines = new Map<number, number>();
- try {
- // v0.36 (D9): score in the active column so rescore happens in the
- // same embedding space the HNSW just ranked in.
- if (chunkIds.length > 0) {
- try {
- cosines = await sqlCosines(engine, chunkIds, column, queryEmbedding);
- } catch (err) {
- const sqlstate = (err as { code?: unknown } | null)?.code;
- warnOncePerProcess('cosine-rescore-sql-fallback',
- `[gbrain] cosine re-score in SQL failed (SQLSTATE ${typeof sqlstate === 'string' ? sqlstate : 'unknown'}); computing it in JavaScript for this process's failing searches.`);
- onFallback?.();
- cosines = await jsCosines(engine, chunkIds, column, queryEmbedding);
+ const reads = (async (): Promise<{ cosines: Map<number, number>; imageCosines: Map<number, number> } | null> => {
+ const chunkIds = idsFor(candidates, false);
+ const imageChunkIds = idsFor(candidates, true);
+ let cosines = new Map<number, number>();
+ let imageCosines = new Map<number, number>();
+ try {
+ // v0.36 (D9): score in the active column so rescore happens in the
+ // same embedding space the HNSW just ranked in.
+ if (chunkIds.length > 0) {
+ try {
+ cosines = await sqlCosines(engine, chunkIds, column, queryEmbedding);
+ } catch (err) {
+ const sqlstate = (err as { code?: unknown } | null)?.code;
+ warnOncePerProcess('cosine-rescore-sql-fallback',
+ `[gbrain] cosine re-score in SQL failed (SQLSTATE ${typeof sqlstate === 'string' ? sqlstate : 'unknown'}); computing it in JavaScript for this process's failing searches.`);
+ onFallback?.();
+ cosines = await jsCosines(engine, chunkIds, column, queryEmbedding);
+ }
}
+ if (imageSpace && imageChunkIds.length > 0) {
+ imageCosines = await jsCosines(engine, imageChunkIds, imageSpace.column, imageSpace.queryEmbedding);
+ }
+ } catch {
+ // DB error is non-fatal: the rows come back without re-scoring
+ return null;
}
- if (imageSpace && imageChunkIds.length > 0) {
- imageCosines = await jsCosines(engine, imageChunkIds, imageSpace.column, imageSpace.queryEmbedding);
- }
- } catch {
- // DB error is non-fatal, return results without re-scoring
- return results;
- }
+ return { cosines, imageCosines };
+ })();
- if (cosines.size === 0 && imageCosines.size === 0) return results;
+ return async (results, attribute = false) => {
+ const chunkIds = idsFor(results, false);
+ const imageChunkIds = idsFor(results, true);
+ if (chunkIds.length === 0 && imageChunkIds.length === 0) return results;
+ const read = await reads;
+ if (!read) return results;
+ const own = (all: Map<number, number>, ids: number[]) => new Map(ids.filter(id => all.has(id)).map(id => [id, all.get(id)!]));
+ const cosines = own(read.cosines, chunkIds);
+ const imageCosines = own(read.imageCosines, imageChunkIds);
- // Normalize RRF scores to 0-1 for blending
- const maxRrf = Math.max(...results.map(r => r.score));
+ if (cosines.size === 0 && imageCosines.size === 0) return results;
- return results.map(r => {
- // #3695: a row with no hydrated chunk embedding (the synthetic chunkless
- // row for an embed_skip'd oversized page, or a chunk whose embedding did
- // not hydrate) goes through the same blend with cosine 0, so it never
- // keeps its raw post-RRF score next to rows on the blended [0, 1] scale.
- const cosine = r.chunk_id != null ? ((inImageSpace(r) ? imageCosines : cosines).get(r.chunk_id) ?? 0) : 0;
- const normRrf = maxRrf > 0 ? r.score / maxRrf : 0;
- const blended = 0.7 * normRrf + 0.3 * cosine;
+ // Normalize RRF scores to 0-1 for blending
+ const maxRrf = Math.max(...results.map(r => r.score));
- if (DEBUG) {
- console.error(`[search-debug] ${r.slug}:${r.chunk_id} cosine=${cosine.toFixed(4)} norm_rrf=${normRrf.toFixed(4)} blended=${blended.toFixed(4)}`);
- }
+ return results.map(r => {
+ // #3695: a row with no hydrated chunk embedding (the synthetic chunkless
+ // row for an embed_skip'd oversized page, or a chunk whose embedding did
+ // not hydrate) goes through the same blend with cosine 0, so it never
+ // keeps its raw post-RRF score next to rows on the blended [0, 1] scale.
+ const cosine = r.chunk_id != null ? ((inImageSpace(r) ? imageCosines : cosines).get(r.chunk_id) ?? 0) : 0;
+ const normRrf = maxRrf > 0 ? r.score / maxRrf : 0;
+ const blended = 0.7 * normRrf + 0.3 * cosine;
+
+ if (DEBUG) {
+ console.error(`[search-debug] ${r.slug}:${r.chunk_id} cosine=${cosine.toFixed(4)} norm_rrf=${normRrf.toFixed(4)} blended=${blended.toFixed(4)}`);
+ }
- // v0.46.15: stamp the raw cosine — evidence + --explain read it.
- return { ...r, score: blended, cosine, ...(attribute ? { blend_norm_rrf: normRrf } : {}) };
- }).sort((a, b) => b.score - a.score);
+ // v0.46.15: stamp the raw cosine — evidence + --explain read it.
+ return { ...r, score: blended, cosine, ...(attribute ? { blend_norm_rrf: normRrf } : {}) };
+ }).sort((a, b) => b.score - a.score);
+ };
}
export function cosineSimilarity(a: Float32Array, b: Float32Array): number {
diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.ts
index 86ef36b253..9b1e967858 100644
--- a/src/core/search/hybrid/arms.ts
+++ b/src/core/search/hybrid/arms.ts
@@ -20,6 +20,7 @@ import { markKeywordHits } from '../evidence.ts';
import { resolveEffectiveRecency, resolveEffectiveSalience } from './effective-modes.ts';
import { searchSalvageEnabled } from '../token-budget.ts';
import { isDatetimeInputError, warnOncePerProcess } from '../../utils.ts';
+import { withUrgentSearchConnections } from '../connection-budget.ts';
export interface LexicalArms {
earlyModality: ModalityMode;
@@ -277,18 +278,18 @@ export function startVectorSide(req: HybridRequest, multimodalProviderProbe: str
const timer = req.timer.branch();
const degraded: HybridRequest['degraded'] = [];
const side: HybridRequest = { ...req, timer, degraded, searchOpts: { ...req.searchOpts, onVectorPoolMeta: vectorPoolMetaSink(req, degraded) } };
- const work = (async () => {
+ const work = withUrgentSearchConnections(async () => {
const modality = await resolveModalityAndQueries(side);
return { ...modality, ...await runVectorArms(side, { ...modality, multimodalProviderProbe }) };
- })();
+ });
return { work, timer, req: side };
}
/** Lexical then relational arms on the critical path; a failure waits for the vector side to settle before it is rethrown. */
export async function runLexicalAndRelational(req: HybridRequest, earlyModality: ModalityMode, vectorSide: VectorSide | null) {
try {
- const lexical = await req.timer.stage('lexical', () => runLexicalArms(req, earlyModality));
- const relationalList = await req.timer.stage('relational', () => buildRelationalList(req));
+ const lexical = await req.timer.stage('lexical', () => withUrgentSearchConnections(() => runLexicalArms(req, earlyModality)));
+ const relationalList = await req.timer.stage('relational', () => withUrgentSearchConnections(() => buildRelationalList(req)));
return { lexical, relationalList };
} catch (err) {
if (vectorSide) await Promise.allSettled([vectorSide.work]);
diff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.ts
index 62254de203..bbd34b841f 100644
--- a/src/core/search/hybrid/rank.ts
+++ b/src/core/search/hybrid/rank.ts
@@ -11,12 +11,13 @@ import { type FusionListEntry, type VectorArm, composeFusionLists } from '../fus
import { type HybridRequest, applyIdentityBoosts, emitHybridMeta } from './request.ts';
import type { KeywordArmConfidenceDecision } from '../arm-confidence.ts';
import { type MetadataBoostGateDecision, decideMetadataBoosts, lexicalArmsVoted } from '../metadata-boost-gate.ts';
-import { type PostFusionOpts, RRF_K, cosineReScore, resolveWalkDedupCap, rrfFusionWeighted, runPostFusionStages, stampContentFlags, stampUnverifiedExtractions, textVectorArmNonEmpty } from '../hybrid.ts';
+import { startCosineReScore } from '../cosine-rescore.ts';
+import { type PostFusionOpts, RRF_K, resolveWalkDedupCap, rrfFusionWeighted, runPostFusionStages, stampContentFlags, stampUnverifiedExtractions, textVectorArmNonEmpty } from '../hybrid.ts';
import { type RelationalEvidenceSlotDecision, ensureRelationalEvidenceSlot } from '../relational-recall.ts';
import { type RelationalRerankPinDecision, pinRelationalRows } from '../relational-rerank-pin.ts';
import { applyFeedbackStage } from '../feedback-boost.ts';
import { capPerSession } from '../diverse-pool.ts';
-import { collapseResults } from '../collapse.ts';
+import { collapseResults, prefetchPageFacts } from '../collapse.ts';
import { readGeneratedPages } from '../provenance-demotion.ts';
import { applyRankPriors } from '../rank-priors.ts';
import { type RerankFailedReason, type RerankPassThroughReason, type RerankSkipReason, applyReranker } from '../rerank.ts';
@@ -144,24 +145,24 @@ export async function fuseArms(
// issue #160: stamp unverified auto-extracted stubs across ALL candidate
// arms BEFORE fusion so the compiled-truth authority boost skips them.
- await stampUnverifiedExtractions(engine, allLists.flatMap((l) => l.list), opts);
-
- const attribute = opts?.explain === true || trace !== undefined;
- let fused = rrfFusionWeighted(allLists, ctBoost, attribute);
-
+ const candidates = allLists.flatMap((l) => l.list);
// Cosine re-scoring before dedup so semantically better chunks survive.
// v0.36 (D9): hydrate from the active embedding column so rescore happens
// in the same vector space the HNSW just ranked in. Pre-v0.36 this
// always pulled from `embedding` and silently corrupted alt-column ranks.
- if (queryEmbedding) {
- // Unified routing embedded the query with the multimodal model, so the
- // rescore must hydrate the multimodal column, not the text column.
- fused = await cosineReScore(
- engine, fused, queryEmbedding, unifiedDone ? 'embedding_multimodal' : resolvedCol.name,
- imageQueryEmbedding && !unifiedDone ? { queryEmbedding: imageQueryEmbedding, column: 'embedding_image' } : undefined,
- attribute, () => { req.cosineRescore = 'js_fallback'; },
- );
- }
+ // Unified routing embedded the query with the multimodal model, so the
+ // rescore must hydrate the multimodal column, not the text column.
+ // GBRA-156: its reads start here, beside the stub stamp below.
+ const rescore = queryEmbedding ? startCosineReScore(
+ engine, candidates, queryEmbedding, unifiedDone ? 'embedding_multimodal' : resolvedCol.name,
+ imageQueryEmbedding && !unifiedDone ? { queryEmbedding: imageQueryEmbedding, column: 'embedding_image' } : undefined,
+ () => { req.cosineRescore = 'js_fallback'; },
+ ) : null;
+ await stampUnverifiedExtractions(engine, candidates, opts);
+
+ const attribute = opts?.explain === true || trace !== undefined;
+ let fused = rrfFusionWeighted(allLists, ctBoost, attribute);
+ if (rescore) fused = await rescore(fused, attribute);
// Phase E3 (Cat 13): metadata boost gate — decided from the SAME lexical
// lists composeFusionLists just fused (post relaxed-row demotion); image
@@ -179,6 +180,7 @@ export async function fuseArms(
// both, or neither fires depending on resolved modes.
if (fused.length > 0) await req.timer.stage('post_fusion', async () => {
const generatedRead = readGeneratedPages(engine, fused);
+ if (resolvedMode.collapse) req.collapsePrefetch = prefetchPageFacts(engine, fused.map(r => r.page_id));
await runPostFusionStages(engine, fused, {
...postFusionOpts, skipMetadataBoosts: !metadataBoostGate.boosts_applied,
});
@@ -266,6 +268,7 @@ export async function collapsePool(req: HybridRequest, rows: SearchResult[]): Pr
return collapseResults(req.engine, rows, {
...req.aliasHopOpts,
facts: req.collapseFacts,
+ prefetched: req.collapsePrefetch,
onDecision: (d) => {
if (d.twins + d.redirects + d.families + d.redirect_reads === 0) return;
const prev = req.collapse ?? { twins: 0, redirects: 0, families: 0, redirect_reads: 0 };
diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.ts
index e57624a33c..f7981dead9 100644
--- a/src/core/search/hybrid/request.ts
+++ b/src/core/search/hybrid/request.ts
@@ -96,6 +96,8 @@ export interface HybridRequest {
collapse?: import('../collapse.ts').CollapseDecision;
/** Page facts the collapse stage read, reused by its second pass after the identity tiers. */
collapseFacts?: Map<number, import('../collapse.ts').PageFacts>;
+ /** GBRA-156: the fused pages' facts, read beside the post-fusion stages (collapse.ts prefetchPageFacts). */
+ collapsePrefetch?: Promise<Map<number, import('../collapse.ts').PageFacts> | null>;
/** The op's stage-timing collector (`opts._timings`), or the no-op timer. */
timer: StageTimer;
}
diff --git a/src/core/search/title-statement.ts b/src/core/search/title-statement.ts
index 2e96e2e532..5738d40ed0 100644
--- a/src/core/search/title-statement.ts
+++ b/src/core/search/title-statement.ts
@@ -41,14 +41,6 @@ export interface SearchTitlesStatement {
safeChunks: boolean;
}
-/**
- * Label every lexeme of a tsquery's text form with weight A
- * (`'acm' & !'secret'` → `'acm':A & !'secret':A`; prefix `'acm':*` →
- * `'acm':*A`). Lexemes are single-quoted with `''` escapes in that form.
- */
-const WEIGHT_A_QUERY = (ftsLang: string): string =>
- `regexp_replace(websearch_to_tsquery('${ftsLang}', gbrain_fts_input($1))::text, '(''(?:[^'']|'''')*'')(?::(\\*))?', '\\1:\\2A', 'g')::tsquery`;
-
export function buildSearchTitlesStatement(query: string, opts: SearchOpts | undefined, dialect: SearchTitlesDialect): SearchTitlesStatement {
const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());
const offset = opts?.offset || 0;
@@ -64,7 +56,7 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | und
const ftsLang = getFtsLanguage();
const tsq = `websearch_to_tsquery('${ftsLang}', gbrain_fts_input($1))`;
const titleOnly = safeChunks || dialect.relaxed === true;
- const matchSql = titleOnly ? `p.search_vector @@ ${WEIGHT_A_QUERY(ftsLang)}` : `p.search_vector @@ ${tsq}`;
+ const matchSql = titleOnly ? `ts_filter(p.search_vector, '{a}') @@ ${tsq}` : `p.search_vector @@ ${tsq}`;
const rankSql = titleOnly ? `ts_rank_cd(ts_filter(p.search_vector, '{a}'), ${tsq})` : `ts_rank_cd(p.search_vector, ${tsq})`;
const params: unknown[] = [boundWebsearchQuery(query), normalizeAlias(query), limit, offset];
diff --git a/src/schema.sql b/src/schema.sql
index a3a4921517..b11a386aa0 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -1169,6 +1169,8 @@ CREATE INDEX IF NOT EXISTS idx_file_migration_ledger_status
ALTER TABLE pages ADD COLUMN IF NOT EXISTS search_vector tsvector;
CREATE INDEX IF NOT EXISTS idx_pages_search ON pages USING GIN(search_vector);
+-- GBRA-156 (v267): the title arm's title-only predicate reads the weight-A slice (the title alone).
+CREATE INDEX IF NOT EXISTS idx_pages_title_search ON pages USING GIN (ts_filter(search_vector, '{a}'));
-- Function to rebuild search_vector for a page
-- #2704: compiled_truth (unbounded whole-page body) deliberately NOT
diff --git a/test/e2e/pgbouncer-transaction-pipeline-6930.test.ts b/test/e2e/pgbouncer-transaction-pipeline-6930.test.ts
index 2706f5146a..63e39e8263 100644
--- a/test/e2e/pgbouncer-transaction-pipeline-6930.test.ts
+++ b/test/e2e/pgbouncer-transaction-pipeline-6930.test.ts
@@ -23,6 +23,7 @@ import { join } from 'node:path';
import postgres from '#postgres';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { declarePersistenceProtocol, isPersistenceDeclaration } from '../../src/core/persistence/protocol.ts';
+import { isPipelinableSearchRead } from '../../src/core/postgres-engine/search-settings.ts';
import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
import { readSqlTrace, type StatementRecord } from '../helpers/statement-counter.ts';
import { withEnv } from '../helpers/with-env.ts';
@@ -350,3 +351,80 @@ describe.skipIf(!(pooled && pooledAdmin))('GBRA-156: a transaction\'s first stat
}, 60_000);
});
+describe.skipIf(!(pooled && pooledAdmin))('GBRA-156: a search read transaction sends its whole body behind BEGIN', () => {
+ const table = `txn_early_${crypto.randomUUID().replace(/-/g, '').slice(0, 8)}`;
+ const settings = "SELECT set_config('jit', $1, true), set_config('statement_timeout', $2, true)";
+ beforeAll(async () => {
+ if (!(pooled && pooledAdmin)) return;
+ const admin = postgres(pooledUrl('?prepare=false'), { max: 1, prepare: false, onnotice: () => {} });
+ try { await admin.unsafe(`CREATE TABLE ${table} (n int)`); } finally { await admin.end(); }
+ }, 60_000);
+
+ test('the settings and the read go out before BEGIN\'s answer, and the read runs inside the transaction under those settings', async () => {
+ let seen: Array<{ jit: string; timeout: string }> = [];
+ const records = await traced('early-read', 1, async engine => {
+ // Transaction-local settings are in effect only inside the transaction (outside one set_config(..., true) is a no-op).
+ // The first run also describes the settings statement's parameters; the second is the one measured.
+ for (let run = 0; run < 2; run++) {
+ seen = await engine.transaction(async tx => {
+ const applied = tx.executeRaw(settings, ['off', '4321ms']);
+ const read = tx.executeRaw<{ jit: string; timeout: string }>(
+ `SELECT current_setting('jit') AS jit, current_setting('statement_timeout') AS timeout /* early read ${run} */`);
+ await applied;
+ return read;
+ }, { pipelineEarly: isPipelinableSearchRead });
+ }
+ });
+ const measured = records.slice(records.findLastIndex(r => /^begin\s*$/i.test(r.sql)));
+ const begin = measured[0]!;
+ const applied = measured.find(r => r.sql === settings)!;
+ const read = measured.find(r => /early read 1 \*\/$/.test(r.sql))!;
+ expect(isPipelinableSearchRead(read.sql)).toBe(true);
+ expect([applied.conn, read.conn]).toEqual([begin.conn, begin.conn]);
+ expect(applied.t < end(begin)).toBe(true);
+ expect(read.t < end(begin)).toBe(true);
+ expect(seen.map(r => [r.jit, r.timeout])).toEqual([['off', '4321ms']]);
+ }, 60_000);
+
+ test('the first refused statement (a write), and every statement after it, waits for BEGIN\'s answer', async () => {
+ const records = await traced('early-refused', 1, async engine => {
+ await engine.transaction(async tx => {
+ await Promise.all([
+ tx.executeRaw('SELECT 1 AS early_before_write'),
+ tx.executeRaw(`INSERT INTO ${table} VALUES (0) /* refused write */`),
+ tx.executeRaw('SELECT 2 AS early_after_write'),
+ ]);
+ await tx.executeRaw(`DELETE FROM ${table} WHERE n = 0`);
+ }, { pipelineEarly: isPipelinableSearchRead });
+ });
+ const begin = records.find(r => /^begin\s*$/i.test(r.sql))!;
+ const before = records.find(r => /AS early_before_write$/.test(r.sql))!;
+ const write = records.find(r => /refused write \*\/$/.test(r.sql))!;
+ const after = records.find(r => /AS early_after_write$/.test(r.sql))!;
+ expect(before.t < end(begin)).toBe(true);
+ expect(write.t >= end(begin)).toBe(true);
+ expect(after.t >= end(begin)).toBe(true);
+ }, 60_000);
+
+ test('a BEGIN that fails runs only accepted reads, in autocommit: no write runs, and the transaction rejects with BEGIN\'s error', async () => {
+ let outcome: string | undefined;
+ let count = -1;
+ await traced('early-begin-fails', 1, async engine => {
+ outcome = await engine.sql.begin({ mode: 'isolation level bogus', early: isPipelinableSearchRead }, async tx => {
+ await Promise.all([tx.unsafe(settings, ['off', '1000ms']), tx.unsafe('SELECT 1 AS early_read_before_failed_begin'), tx.unsafe(`INSERT INTO ${table} VALUES (5)`)]);
+ }).then(() => 'none', (e: { code?: string }) => e.code);
+ count = Number((await engine.sql.unsafe(`SELECT count(*)::int AS c FROM ${table}`))[0]!.c);
+ });
+ expect(outcome).toBe('42601');
+ expect(count).toBe(0);
+ }, 60_000);
+
+ test('GBRAIN_PG_TXN_PIPELINE=0 keeps every statement behind BEGIN\'s answer', async () => {
+ const records = await traced('early-off', 1, async engine => {
+ await engine.transaction(tx => tx.executeRaw('SELECT 1 AS early_switched_off'), { pipelineEarly: isPipelinableSearchRead });
+ }, { GBRAIN_PG_TXN_PIPELINE: '0' });
+ const begin = records.find(r => /^begin\s*$/i.test(r.sql))!;
+ const read = records.find(r => /AS early_switched_off$/.test(r.sql))!;
+ expect(read.t >= end(begin)).toBe(true);
+ }, 60_000);
+});
diff --git a/test/e2e/search-read-pipeline-postgres.test.ts b/test/e2e/search-read-pipeline-postgres.test.ts
new file mode 100644
index 0000000000..63e73c933a
--- /dev/null
+++ b/test/e2e/search-read-pipeline-postgres.test.ts
@@ -0,0 +1,60 @@
+/**
+ * GBRA-156: a search read transaction sends its settings and its read behind BEGIN, before BEGIN's answer, on a
+ * direct (pipelining) pool too, so each scoped search read costs one round trip instead of two. The pooler case
+ * (transaction_pipeline behind transaction-mode PgBouncer) is test/e2e/pgbouncer-transaction-pipeline-6930.test.ts.
+ *
+ * Reads the socket trace (GBRAIN_SQL_TRACE): a statement sent before BEGIN's answer arrived was pipelined, a client
+ * decision rather than a timing. Regression that fails it: the driver awaited BEGIN's answer before running the body.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { seedPage } from '../helpers/keyword-paging-fixture.ts';
+import { readSqlTrace, type StatementRecord } from '../helpers/statement-counter.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const run = process.env.DATABASE_URL ? describe : describe.skip;
+const dir = mkdtempSync(join(tmpdir(), 'gbrain-search-read-pipeline-'));
+const trace = join(dir, 'trace.jsonl');
+let databaseUrl = '';
+let close: () => Promise<void> = async () => {};
+
+const end = (r: StatementRecord) => r.t + (r.ms ?? 0);
+
+run('search read transactions pipeline their body behind BEGIN (direct pool)', () => {
+ beforeAll(async () => {
+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ for (let i = 0; i < 6; i++) await seedPage(isolated.engine, `notes/orbital-ledger-${i}`, `Orbital ledger entry ${i}: the quasar survey.`, { title: `Orbital Ledger ${i}` });
+ await isolated.engine.disconnect();
+ databaseUrl = isolated.databaseUrl;
+ close = isolated.close;
+ }, 300_000);
+
+ afterAll(async () => { rmSync(dir, { recursive: true, force: true }); await close(); });
+
+ test('the title arm\'s settings and statement go out before BEGIN\'s answer, on BEGIN\'s connection', async () => {
+ let rows = 0;
+ await withEnv({ GBRAIN_SQL_TRACE: trace, GBRAIN_SQL_TRACE_LABEL: 'search-read-direct' }, async () => {
+ const engine = new PostgresEngine();
+ await engine.connect({ engine: 'postgres', database_url: databaseUrl, poolSize: 1 });
+ try {
+ // The first call also describes each statement's parameters; the second is the one measured.
+ await engine.searchTitles('orbital ledger', { requireSafeChunks: true, excludePrivate: true });
+ rows = (await engine.searchTitles('orbital ledger', { requireSafeChunks: true, excludePrivate: true })).length;
+ } finally { await engine.disconnect(); }
+ });
+ await Bun.sleep(1200);
+ const records = readSqlTrace(trace).filter(r => (r as { label?: string }).label === 'search-read-direct' && r.kind !== 'connect').sort((a, b) => a.t - b.t);
+ const measured = records.slice(records.findLastIndex(r => /^begin\s*$/i.test(r.sql)));
+ const begin = measured[0]!;
+ const settings = measured.find(r => /^SELECT set_config\('jit'/.test(r.sql))!;
+ const title = measured.find(r => /WITH top_pages AS/.test(r.sql))!;
+ expect(rows).toBeGreaterThan(0);
+ expect([settings.conn, title.conn]).toEqual([begin.conn, begin.conn]);
+ expect(settings.t < end(begin)).toBe(true);
+ expect(title.t < end(begin)).toBe(true);
+ }, 60_000);
+});
diff --git a/test/e2e/title-arm-postgres.test.ts b/test/e2e/title-arm-postgres.test.ts
index 9b34fd4a70..72464060ab 100644
--- a/test/e2e/title-arm-postgres.test.ts
+++ b/test/e2e/title-arm-postgres.test.ts
@@ -3,10 +3,12 @@
* test/search/title-arm-exact.test.ts, plus a plan proof for the remote
* (safe-chunks) predicate. The plan proof EXPLAINs the statement the engine
* runs (search/title-statement.ts buildSearchTitlesStatement, the one builder
- * both engines call) and requires `idx_pages_search` with no per-row
- * `to_tsvector(title)` filter (the pre-fix remote arm scanned every page in
- * scope). `enable_seqscan = off` inside the transaction keeps the plan
- * choice deterministic on a small fixture.
+ * both engines call) and requires the title-only index `idx_pages_title_search`
+ * (GBRA-156, v267: the weight-A slice of search_vector, so a term in timeline
+ * text never makes its page a candidate) with no per-row `to_tsvector(title)`
+ * filter (the pre-fix remote arm scanned every page in scope).
+ * `enable_seqscan = off` inside the transaction keeps the plan choice
+ * deterministic on a small fixture.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
@@ -33,6 +35,9 @@ describe('remote title arm plan (postgres)', () => {
await engine.putPage(slug, { type: 'note', title: i % 10 === 0 ? `Acme review ${i}` : `Globex weekly sync ${i}`, compiled_truth: body });
await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth' }]);
}
+ // Timeline text (search_vector weight C) names the title terms; the title-only predicate must not match it.
+ await engine.addTimelineEntry('notes/page-1', { date: '2026-02-02', source: 't', summary: 'Acme secret weekly sync with acme', detail: 'acme' });
+ await engine.addTimelineEntry('notes/page-10', { date: '2026-02-03', source: 't', summary: 'secret globex notes', detail: 'globex' });
await engine.executeRaw('ANALYZE pages');
}, 120_000);
@@ -48,13 +53,31 @@ describe('remote title arm plan (postgres)', () => {
}
for (const query of ['acme', 'acme -secret', '"weekly sync"', 'globex or acme']) {
- test(`\`${query}\` uses idx_pages_search with no per-row to_tsvector(title)`, async () => {
+ test(`\`${query}\` uses idx_pages_title_search with no per-row to_tsvector(title)`, async () => {
const text = await plan(query);
- expect(text).toContain('idx_pages_search');
+ expect(text).toContain('idx_pages_title_search');
expect(text).not.toMatch(/to_tsvector\([^)]*title/);
});
}
+ // GBRA-156: the title-only predicate `ts_filter(search_vector, '{a}') @@ q` matches exactly the pages the former
+ // `search_vector @@ q` with every lexeme labeled :A matched (negation and phrases read title lexemes only either way).
+ test('the title-only predicate returns the pages the weight-A labeled query returned', async () => {
+ const statement = buildSearchTitlesStatement('acme', REMOTE, POSTGRES_DIALECT);
+ expect(statement.sql).toContain("ts_filter(p.search_vector, '{a}') @@ websearch_to_tsquery(");
+ const labeled = statement.sql.replace(/ts_filter\(p\.search_vector, '\{a\}'\) @@ (websearch_to_tsquery\('\w+', gbrain_fts_input\(\$1\)\))/,
+ (_m, tsq: string) => `p.search_vector @@ regexp_replace(${tsq}::text, '(''(?:[^'']|'''')*'')(?::(\\*))?', '\\1:\\2A', 'g')::tsquery`);
+ expect(labeled).not.toBe(statement.sql);
+ for (const query of ['acme', 'acme -secret', '"weekly sync"', 'globex or acme', 'secret', 'globex -weekly', 'acme notes']) {
+ const params = buildSearchTitlesStatement(query, REMOTE, POSTGRES_DIALECT).params;
+ const now = (await engine.executeRaw<{ slug: string }>(statement.sql, params)).map(r => r.slug);
+ const before = (await engine.executeRaw<{ slug: string }>(labeled, params)).map(r => r.slug);
+ expect({ query, now }).toEqual({ query, now: before });
+ }
+ const secret = await engine.executeRaw<{ slug: string }>(statement.sql, buildSearchTitlesStatement('secret', REMOTE, POSTGRES_DIALECT).params);
+ expect(secret).toEqual([]);
+ });
+
test('the engine runs the same statement the plan proof explains', async () => {
const statement = buildSearchTitlesStatement('acme', REMOTE, POSTGRES_DIALECT);
const direct = await engine.executeRaw<{ slug: string }>(statement.sql, statement.params);
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index a6e54e1299..96e209d5a8 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -1230,6 +1230,7 @@
"idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)",
"idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)",
"idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))",
+ "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))",
"idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)",
"idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)",
"idx_pages_updated_at_desc": "CREATE INDEX idx_pages_updated_at_desc ON public.pages USING btree (updated_at DESC)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index fd28a3d598..d25271865d 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -1230,6 +1230,7 @@
"idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)",
"idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)",
"idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))",
+ "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))",
"idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)",
"idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)",
"idx_pages_updated_at_desc": "CREATE INDEX idx_pages_updated_at_desc ON public.pages USING btree (updated_at DESC)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index a44aaeb8df..cb3ecd5e65 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -1228,6 +1228,7 @@
"idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)",
"idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)",
"idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))",
+ "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))",
"idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)",
"idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)",
"idx_pages_updated_at_desc": "CREATE INDEX idx_pages_updated_at_desc ON public.pages USING btree (updated_at DESC)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index f68353953a..35b0e24d33 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -921,6 +921,7 @@
"idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)",
"idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)",
"idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))",
+ "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))",
"idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)",
"idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)",
"idx_rate_leases_key_expires": "CREATE INDEX idx_rate_leases_key_expires ON public.subagent_rate_leases USING btree (key, expires_at)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index a3eef1276e..583a826803 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -921,6 +921,7 @@
"idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)",
"idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)",
"idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))",
+ "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))",
"idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)",
"idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)",
"idx_rate_leases_key_expires": "CREATE INDEX idx_rate_leases_key_expires ON public.subagent_rate_leases USING btree (key, expires_at)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index c3ed303085..528833041b 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -920,6 +920,7 @@
"idx_pages_slug_trgm": "CREATE INDEX idx_pages_slug_trgm ON public.pages USING gin (slug gin_trgm_ops)",
"idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)",
"idx_pages_source_title_lower": "CREATE INDEX idx_pages_source_title_lower ON public.pages USING btree (source_id, lower(title))",
+ "idx_pages_title_search": "CREATE INDEX idx_pages_title_search ON public.pages USING gin (ts_filter(search_vector, '{a}'::\"char\"[]))",
"idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)",
"idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)",
"idx_rate_leases_key_expires": "CREATE INDEX idx_rate_leases_key_expires ON public.subagent_rate_leases USING btree (key, expires_at)",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 3637350a89..959baff9a4 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 261,
+ "count": 262,
"gaps": [
17,
18,
@@ -28,6 +28,7 @@
"PAGES_NAME_LOOKUP_INDEXES": "1ca830342164b5606e96cf0090645364f9145d36178d90f166230189fe8d2705",
"PAGES_RECONCILE_NAME_INDEXES": "8805e35341b22324b932b1cc05030cc8f2bfc95532bf810ec35330783f29c59a",
"PAGES_SEGMENTED_BODY_BYTES_INDEX": "c904a4f68cf190cce6bc68c03219c7b62d05b77eeb557db946a4f58a4f965e57",
+ "PAGES_TITLE_SEARCH_INDEX": "27e8e1a6c9a2069ee6c6af6fa99b9a7e9e9c118c7a933ffa80ba1864bf68baa3",
"PAGE_TIMELINE_FTS_MAX_CHARS": "f7d29264f4144976bbe2e1ded0251095b638175f8e1d711c36f1e80d2263e172",
"PERSISTENCE_COMMITTED_WATERMARK_INDEX": "f472fa0acb542c1caebaaa3bc69fb2da1647e5e201239429fc02ccef0d669533",
"PERSISTENCE_COMPACTABLE_INDEX": "25ee657878efb41ba9ea3a7624464ddcf66407d861659456c230366e57f230a0",
@@ -72,7 +73,7 @@
"tableRows": "906d2413b13d76a06d5910885e47ed5c544be4ff3a2266e83146715721b24270",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
- "latest": 266,
+ "latest": 267,
"records": [
{
"handler": {
@@ -4227,6 +4228,35 @@
"transaction": "absent",
"verify": "absent",
"version": 266
+ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [
+ "PAGES_TITLE_SEARCH_INDEX",
+ "PLANNER_REPAIR_TABLES",
+ "analyzeAfterIndexBuild",
+ "analyzeDeferred",
+ "analyzeYieldingToVacuum",
+ "buildIndexOnline",
+ "dropInvalidConcurrentIndex",
+ "lockTableForAnalyze",
+ "migrationNotice",
+ "quietMigrationNotices",
+ "tableRows"
+ ],
+ "sha256": "08f633af1c107eb453085b9027b8cad8d2ba1595147c44acf4296aa4e5410b3d"
+ },
+ "idempotent": true,
+ "name": "pages_title_search_index",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": "absent",
+ "transaction": false,
+ "verify": "absent",
+ "version": 267
}
],
"versions": [
@@ -4490,7 +4520,8 @@
263,
264,
265,
- 266
+ 266,
+ 267
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/postgres-driver-vendor-6930.test.ts b/test/postgres-driver-vendor-6930.test.ts
index 667f232eb8..8131b434c4 100644
--- a/test/postgres-driver-vendor-6930.test.ts
+++ b/test/postgres-driver-vendor-6930.test.ts
@@ -22,13 +22,17 @@ describe('vendored Postgres driver #6930 patch', () => {
expect(index).toContain("const first = typeof options === 'object' && options.first && sql.options.transaction_pipeline > sql.options.max_pipeline");
expect(index).toContain('const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]');
expect(index).toContain('&& q.args.every(x => !(x instanceof Query || x instanceof Builder || x instanceof Identifier || Array.isArray(x) && x.some(y => y instanceof Query)))');
- expect(index).toContain("&& first(strings.reduce((a, s, i) => a + '$' + i + s))");
- expect(index).toMatch(/if \(!early\)\n\s+return opening\.then\(\(\) => handler\(q\), q\.reject\)/);
+ expect(index).toContain("&& test(strings.reduce((a, s, i) => a + '$' + i + s))");
+ expect(index).toMatch(/if \(!sent\) \{\n\s+held = true\n\s+return opening\.then\(\(\) => handler\(q\), q\.reject\)/);
+ // GBRA-156: `early` sends each statement it accepts, in order until one is refused, on any pool that pipelines inside a transaction.
+ expect(index).toContain('&& (sql.options.transaction_pipeline > sql.options.max_pipeline || sql.options.max_pipeline > 0)');
+ expect(index).toContain('const test = early || !firstSeen && first');
+ expect(index).toContain('const sent = !held && test');
expect(index).toMatch(/const \[opened, result\] = await Promise\.allSettled\(\[begun, ran\]\)\n\s+if \(opened\.status === 'rejected'\)\n\s+throw opened\.reason/);
}
const types = readFileSync(new URL('../vendor/postgres/types/index.d.ts', import.meta.url), 'utf8');
expect(types).toContain('transaction_pipeline: number;');
- expect(types).toContain('begin<T>(options: { mode?: string; first?: (statement: string) => boolean }');
+ expect(types).toContain('begin<T>(options: { mode?: string; first?: (statement: string) => boolean; early?: (statement: string) => boolean }');
expect(types).toContain('array_types: { rows: Array<[number, number]> | null } | null;');
});
});
diff --git a/test/postgres-engine-rls-scope.test.ts b/test/postgres-engine-rls-scope.test.ts
index 7c0bfd67a0..fd6d6b7c52 100644
--- a/test/postgres-engine-rls-scope.test.ts
+++ b/test/postgres-engine-rls-scope.test.ts
@@ -41,14 +41,16 @@ function makeFakeSql() {
);
const sql = handle('pool') as unknown as Record<string, unknown> & {
(strings: TemplateStringsArray, ...params: unknown[]): Promise<unknown[]>;
- begin: (cb: (tx: unknown) => Promise<unknown>) => Promise<unknown>;
+ begin: (first: unknown, second?: (tx: unknown) => Promise<unknown>) => Promise<unknown>;
};
const tx = handle('transaction') as unknown as Record<string, unknown>;
tx.savepoint = async (cb: (tx: unknown) => Promise<unknown>) => {
savepointCalls++; const prior = scopes;
try { return await cb(tx); } catch (error) { scopes = prior; throw error; }
};
- sql.begin = async (cb: (t: unknown) => Promise<unknown>) => {
+ // The pool's begin also takes options first (GBRA-156: `{ early }` on search reads).
+ sql.begin = async (first: unknown, second?: (t: unknown) => Promise<unknown>) => {
+ const cb = (second ?? first) as (t: unknown) => Promise<unknown>;
beginCalls++;
const prior = scopes;
try { return await cb(tx); } finally { scopes = prior; }
diff --git a/test/search-connection-budget-urgent.test.ts b/test/search-connection-budget-urgent.test.ts
new file mode 100644
index 0000000000..04bcdbc9a6
--- /dev/null
+++ b/test/search-connection-budget-urgent.test.ts
@@ -0,0 +1,42 @@
+/**
+ * GBRA-156: inside one search's connection budget, a read started under withUrgentSearchConnections (the retrieval
+ * arms) takes the next free slot ahead of reads that were already waiting outside it (the keyword count and entity
+ * resolution a search starts early for its response). The limit itself is unchanged.
+ * Regression that fails it: a released slot went to the oldest waiter, so the title arm queued behind entity
+ * resolution's reads.
+ */
+import { describe, expect, test } from 'bun:test';
+import { holdSearchConnection, SEARCH_CONNECTION_LIMIT, withSearchConnectionBudget, withUrgentSearchConnections } from '../src/core/search/connection-budget.ts';
+
+describe('search connection budget: urgent reads', () => {
+ test('a released slot goes to a waiting urgent read before older ordinary waiters; at most the limit run at once', async () => {
+ const order: string[] = [];
+ let running = 0, peak = 0;
+ const gates: Array<() => void> = [];
+ const hold = (label: string, gated: boolean) => holdSearchConnection(async () => {
+ running++; peak = Math.max(peak, running);
+ order.push(label);
+ if (gated) await new Promise<void>(resolve => gates.push(resolve));
+ running--;
+ });
+ await withSearchConnectionBudget(async () => {
+ const holders = Array.from({ length: SEARCH_CONNECTION_LIMIT }, (_, i) => hold(`holder-${i}`, true));
+ await Bun.sleep(0);
+ const ordinary = [hold('count', false), hold('entity', false)];
+ const urgent = withUrgentSearchConnections(() => hold('title-arm', false));
+ await Bun.sleep(0);
+ expect(order).toEqual(['holder-0', 'holder-1', 'holder-2', 'holder-3']);
+ gates.shift()!();
+ await urgent;
+ gates.splice(0).forEach(open => open());
+ await Promise.all([...holders, ...ordinary]);
+ });
+ expect(order.slice(SEARCH_CONNECTION_LIMIT)).toEqual(['title-arm', 'count', 'entity']);
+ expect(peak).toBe(SEARCH_CONNECTION_LIMIT);
+ });
+
+ test('without waiters an urgent read takes a free slot like any other, and outside a budget nothing waits', async () => {
+ expect(await withSearchConnectionBudget(() => withUrgentSearchConnections(() => holdSearchConnection(async () => 'ran')))).toBe('ran');
+ expect(await withUrgentSearchConnections(() => holdSearchConnection(async () => 'unbudgeted'))).toBe('unbudgeted');
+ });
+});
diff --git a/test/search-settings-one-statement.test.ts b/test/search-settings-one-statement.test.ts
index af965bba8c..726e6662e6 100644
--- a/test/search-settings-one-statement.test.ts
+++ b/test/search-settings-one-statement.test.ts
@@ -21,7 +21,7 @@
*/
import { describe, expect, test } from 'bun:test';
import { PostgresEngine } from '../src/core/postgres-engine.ts';
-import { searchSettingsStatement, withSearchSettings } from '../src/core/postgres-engine/search-settings.ts';
+import { isPipelinableSearchRead, searchSettingsStatement, withSearchSettings } from '../src/core/postgres-engine/search-settings.ts';
import { vectorScanSettings } from '../src/core/search/vector-settings.ts';
const { default: Connection } = await import(new URL('../vendor/postgres/src/connection.js', import.meta.url).href) as {
@@ -117,13 +117,16 @@ describe('PostgresEngine.searchKeyword: statements per search transaction', () =
/** An engine over a fake pool whose transactions record their statements; every query returns no rows. */
function recordingEngine() {
const transactions: Statement[][] = [];
+ const options: unknown[] = [];
const handle = (into: () => Statement[]) => Object.assign(
async (strings: TemplateStringsArray, ...params: unknown[]) => { into().push({ sql: strings.join('$'), params }); return []; },
{ unsafe: async (sql: string, params: unknown[] = []) => { into().push({ sql, params }); return []; } },
);
const pool: Statement[] = [];
const sql = Object.assign(handle(() => pool), {
- begin: async (fn: (tx: unknown) => Promise<unknown>) => {
+ begin: async (first: unknown, second?: (tx: unknown) => Promise<unknown>) => {
+ const fn = (second ?? first) as (tx: unknown) => Promise<unknown>;
+ options.push(second ? first : undefined);
const statements: Statement[] = [];
transactions.push(statements);
return fn(Object.assign(handle(() => statements), { savepoint: (inner: (tx: unknown) => Promise<unknown>) => inner(handle(() => statements)) }));
@@ -135,7 +138,7 @@ describe('PostgresEngine.searchKeyword: statements per search transaction', () =
priv._connectionStyle = 'instance';
priv._savedConfig = { keyword_statement_timeout_ms: 8000 };
priv.registerBeforeDisconnect = () => () => {};
- return { engine, transactions };
+ return { engine, transactions, options };
}
test('strict attempt: settings then query; OR fallback: the same two, with enable_seqscan off in the one settings statement (work_mem in both, GBRA-156)', async () => {
@@ -150,4 +153,51 @@ describe('PostgresEngine.searchKeyword: statements per search transaction', () =
expect(transactions[1]![0]!.sql).toBe("SELECT set_config('jit', $1, true), set_config('statement_timeout', $2, true), set_config('enable_seqscan', $3, true), set_config('work_mem', $4, true)");
expect(transactions[1]![0]!.params).toEqual(['off', '8000ms', 'off', '32MB']);
});
+
+ test('GBRA-156: every search read transaction sends its settings and its read behind BEGIN, before BEGIN\'s answer', async () => {
+ const { engine, transactions, options } = recordingEngine();
+ await engine.searchKeyword('alpha beta', { orFallback: true });
+ await engine.searchTitles('alpha beta', { requireSafeChunks: true, excludePrivate: true });
+ expect(transactions.length).toBeGreaterThanOrEqual(4);
+ for (const [i, statements] of transactions.entries()) {
+ const early = (options[i] as { early?: (statement: string) => boolean } | undefined)?.early;
+ expect(early).toBe(isPipelinableSearchRead);
+ expect(statements.map(s => ({ head: s.sql.trim().slice(0, 40), sent: early!(s.sql) })))
+ .toEqual(statements.map(s => ({ head: s.sql.trim().slice(0, 40), sent: true })));
+ }
+ });
+});
+
+describe('isPipelinableSearchRead', () => {
+ test('accepts the settings statement and single reads', () => {
+ expect(isPipelinableSearchRead(searchSettingsStatement({ jit: 'off', statement_timeout: '8000ms', 'app.scopes': 'a,b', work_mem: '32MB' }).sql)).toBe(true);
+ expect(isPipelinableSearchRead('WITH top_pages AS (SELECT p.updated_at, p.deleted_at FROM pages p) SELECT * FROM top_pages')).toBe(true);
+ expect(isPipelinableSearchRead(' select 1')).toBe(true);
+ });
+
+ test('refuses writes, locks, sequences, session settings, notifications and more than one statement', () => {
+ for (const statement of [
+ 'INSERT INTO page_retrievals VALUES (1)',
+ 'UPDATE pages SET title = $1',
+ 'WITH gone AS (DELETE FROM pages RETURNING id) SELECT * FROM gone',
+ 'WITH m AS (MERGE INTO pages p USING x ON true WHEN MATCHED THEN DELETE) SELECT 1',
+ 'SELECT 1 FROM pages FOR UPDATE',
+ 'SELECT 1 FROM pages FOR NO KEY UPDATE',
+ 'SELECT 1 FROM pages FOR SHARE',
+ 'SELECT 1 FROM pages FOR KEY SHARE',
+ "SELECT nextval('page_generation_clock_seq')",
+ 'SELECT pg_advisory_xact_lock(1)',
+ 'SELECT pg_try_advisory_lock(1)',
+ "SELECT pg_notify('x', 'y')",
+ "SELECT set_config('jit', $1, false)",
+ "SELECT set_config('jit', 'off', true)",
+ 'SELECT txid_current()',
+ 'SELECT 1; SELECT 2',
+ 'COMMIT',
+ 'SAVEPOINT s0',
+ 'TRUNCATE pages',
+ 'LOCK TABLE pages',
+ 'CALL do_something()',
+ ]) expect({ statement, accepted: isPipelinableSearchRead(statement) }).toEqual({ statement, accepted: false });
+ });
});
diff --git a/test/search/collapse-hybrid.test.ts b/test/search/collapse-hybrid.test.ts
index 95dc309847..a5611a675b 100644
--- a/test/search/collapse-hybrid.test.ts
+++ b/test/search/collapse-hybrid.test.ts
@@ -10,7 +10,7 @@
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { hybridSearch } from '../../src/core/search/hybrid.ts';
-import { type CollapseDecision, collapseResults, redirectTargetSlug } from '../../src/core/search/collapse.ts';
+import { type CollapseDecision, collapseResults, prefetchPageFacts, redirectTargetSlug } from '../../src/core/search/collapse.ts';
import { fnv1a } from '../../src/eval/deterministic-embed.ts';
import type { HybridSearchMeta, SearchResult } from '../../src/core/types.ts';
import { installFixtureChunks } from '../helpers/page-projection.ts';
@@ -229,3 +229,41 @@ describe('look-alikes the review found (no false folds, no private slug)', () =>
expect(out.map(r => r.slug)).toEqual(['people/bram-example']);
});
});
+
+describe('GBRA-156: page facts read ahead of the collapse', () => {
+ const factReads = (sent: string[]) => sent.filter(sql => sql.includes("frontmatter->>'redirect_to'")).length;
+ const recording = (sent: string[]) => new Proxy(engine, {
+ get(target, key, receiver) {
+ if (key === 'executeRaw') return (sql: string, params?: unknown[]) => { sent.push(sql); return target.executeRaw(sql, params); };
+ const value = Reflect.get(target, key, receiver);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ }) as PGLiteEngine;
+
+ test('a prefetch over every page (more than the collapse reads) gives the same rows and the collapse reads no facts itself', async () => {
+ await engine.setConfig('search.collapse', 'false');
+ const allIds = (await engine.executeRaw<{ id: number }>('SELECT id FROM pages')).map(r => Number(r.id));
+ for (const q of ['zephyr ledger', 'orbit talk', 'heron memo', 'lumen sync', 'kestrel plan', 'standup badge reader', 'quill roster']) {
+ const { rows } = await search(q);
+ const plain: string[] = [];
+ const ahead: string[] = [];
+ const before = await collapseResults(recording(plain), rows.map(r => ({ ...r })), {});
+ const after = await collapseResults(recording(ahead), rows.map(r => ({ ...r })), { prefetched: prefetchPageFacts(engine, allIds) });
+ expect({ q, rows: after }).toEqual({ q, rows: before });
+ expect({ q, reads: factReads(plain) }).toEqual({ q, reads: 1 });
+ expect({ q, reads: factReads(ahead) }).toEqual({ q, reads: 0 });
+ }
+ });
+
+ test('pages the prefetch does not cover are read as before, and a failed prefetch falls back to the collapse\'s own read', async () => {
+ await engine.setConfig('search.collapse', 'false');
+ const { rows } = await search('zephyr ledger');
+ const expected = await collapseResults(engine, rows.map(r => ({ ...r })), {});
+ const sent: string[] = [];
+ const partial = await collapseResults(recording(sent), rows.map(r => ({ ...r })), { prefetched: prefetchPageFacts(engine, [rows[0]!.page_id]) });
+ expect(partial).toEqual(expected);
+ expect(factReads(sent)).toBe(1);
+ const failed = await collapseResults(engine, rows.map(r => ({ ...r })), { prefetched: Promise.resolve(null) });
+ expect(failed).toEqual(expected);
+ });
+});
diff --git a/test/search/cosine-rescore-sql.test.ts b/test/search/cosine-rescore-sql.test.ts
index a582eceb62..3e3b593c5c 100644
--- a/test/search/cosine-rescore-sql.test.ts
+++ b/test/search/cosine-rescore-sql.test.ts
@@ -14,7 +14,7 @@ import type { SearchResult } from '../../src/core/types.ts';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { importFromContent } from '../../src/core/import-file.ts';
import { serializeMarkdown } from '../../src/core/markdown.ts';
-import { cosineReScore, cosineSimilarity } from '../../src/core/search/cosine-rescore.ts';
+import { cosineReScore, cosineSimilarity, startCosineReScore } from '../../src/core/search/cosine-rescore.ts';
import { _resetWarnOnceForTests } from '../../src/core/utils.ts';
import { testBackends } from '../helpers/test-backends.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
@@ -117,6 +117,18 @@ for (const kind of testBackends()) {
expect(by['notes/deleted']!.cosine).toBe(0);
});
+ test('GBRA-156: reads started for a wider candidate set re-score the fused rows exactly as cosineReScore does', async () => {
+ const candidates = rows(['notes/random-a', 'notes/random-b', 'notes/near-floor', 'notes/zero', 'notes/missing', 'notes/deleted']);
+ for (const fused of [candidates.slice(0, 3), [candidates[3]!, candidates[1]!], candidates.slice(4)]) {
+ const direct = await cosineReScore(engine, fused, v.query);
+ const started = await startCosineReScore(engine, candidates, v.query)(fused);
+ expect(started).toEqual(direct);
+ }
+ // A fused set none of whose chunks hydrate comes back untouched, though other candidates hydrated.
+ const unhydrated = candidates.slice(4);
+ expect(await startCosineReScore(engine, candidates, v.query)(unhydrated)).toBe(unhydrated);
+ });
+
test('the all-missing set and a chunkless row come back untouched', async () => {
const input = [...rows(['notes/missing', 'notes/deleted']), { ...rows(['notes/random-a'])[0]!, chunk_id: null } as unknown as SearchResult];
expect(await cosineReScore(engine, input, v.query)).toBe(input);
diff --git a/vendor/README.md b/vendor/README.md
index 34cc575c1d..bc75f1c459 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -113,6 +113,18 @@ GBrain passes `isPersistenceDeclaration` (`src/core/persistence/protocol.ts`)
from the persistence transactions that open with the protocol declaration
(GBRA-156, same test file).
+`sql.begin({ early }, fn)` sends every statement `early(text)` accepts, in
+order, behind BEGIN before BEGIN's answer, on any pool that pipelines inside
+a transaction (a pipelining pool, or `transaction_pipeline` in force); the
+first statement it refuses, and every later one, waits for the answer. The
+same rule applies: if BEGIN fails the accepted statements have run in
+autocommit, so the test must accept only reads and transaction-local
+`set_config`. GBrain passes `isPipelinableSearchRead`
+(`src/core/postgres-engine/search-settings.ts`) from its search read
+transactions, so a scoped search read costs one round trip instead of two
+(GBRA-156, `test/e2e/pgbouncer-transaction-pipeline-6930.test.ts` and
+`test/e2e/search-read-pipeline-postgres.test.ts`).
+
On a reserved connection (`sql.reserve`), where the pool does not pipeline,
`reservedTransactions().begin({ first }, fn)`
(`src/core/postgres-engine/reserved-transactions.ts`) makes the same
diff --git a/vendor/postgres/cf/src/index.js b/vendor/postgres/cf/src/index.js
index 518178f046..99785da244 100644
--- a/vendor/postgres/cf/src/index.js
+++ b/vendor/postgres/cf/src/index.js
@@ -411,17 +411,26 @@ function Postgres(a, b) {
const first = typeof options === 'object' && options.first && sql.options.transaction_pipeline > sql.options.max_pipeline
? options.first
: null
+ // GBrain (GBRA-156): `{ early }` sends every statement it accepts, in order, behind BEGIN before BEGIN's answer,
+ // on any pool that pipelines inside a transaction (a pipelining pool, or transaction_pipeline behind a pooler that
+ // does not). The first statement it refuses, and every later one, waits for the answer. If BEGIN fails the accepted
+ // statements run in autocommit, so `early` must accept only reads and transaction-local set_config, never a write.
+ const early = typeof options === 'object' && options.early
+ && (sql.options.transaction_pipeline > sql.options.max_pipeline || sql.options.max_pipeline > 0)
+ ? options.early
+ : null
typeof options === 'object' && (options = options.mode || '')
let savepoints = 0
, connection
, prepare = null
, opening = null
, firstSeen = false
+ , held = false
, written
try {
const begun = sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
- if (!first) {
+ if (!first && !early) {
await begun
return await Promise.race([
scope(connection, fn),
@@ -496,17 +505,21 @@ function Postgres(a, b) {
q.catch(e => uncaughtError || (uncaughtError = e))
if (!reservation || c.reserved !== reservation)
return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
- // GBrain (#6930): while BEGIN is unanswered only an accepted first statement is sent; the rest wait, in order. It
- // is accepted on its text (`$n` for each argument, as statementText builds it) only when every argument is a
- // parameter value: a fragment (a query, a helper, an identifier) would carry SQL the test never saw.
+ // GBrain (#6930, GBRA-156): while BEGIN is unanswered only accepted statements are sent (the first one for
+ // `first`; each one until one is refused for `early`); the rest wait, in order. A statement is accepted on its
+ // text (`$n` for each argument, as statementText builds it) only when every argument is a parameter value: a
+ // fragment (a query, a helper, an identifier) would carry SQL the test never saw.
if (opening) {
const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
- const early = !firstSeen
+ const test = early || !firstSeen && first
+ const sent = !held && test
&& q.args.every(x => !(x instanceof Query || x instanceof Builder || x instanceof Identifier || Array.isArray(x) && x.some(y => y instanceof Query)))
- && first(strings.reduce((a, s, i) => a + '$' + i + s))
+ && test(strings.reduce((a, s, i) => a + '$' + i + s))
firstSeen = true
- if (!early)
+ if (!sent) {
+ held = true
return opening.then(() => handler(q), q.reject)
+ }
}
reservation.enqueue(q)
}
diff --git a/vendor/postgres/cjs/src/index.js b/vendor/postgres/cjs/src/index.js
index 4709ad4bd9..ef672e7c92 100644
--- a/vendor/postgres/cjs/src/index.js
+++ b/vendor/postgres/cjs/src/index.js
@@ -410,17 +410,26 @@ function Postgres(a, b) {
const first = typeof options === 'object' && options.first && sql.options.transaction_pipeline > sql.options.max_pipeline
? options.first
: null
+ // GBrain (GBRA-156): `{ early }` sends every statement it accepts, in order, behind BEGIN before BEGIN's answer,
+ // on any pool that pipelines inside a transaction (a pipelining pool, or transaction_pipeline behind a pooler that
+ // does not). The first statement it refuses, and every later one, waits for the answer. If BEGIN fails the accepted
+ // statements run in autocommit, so `early` must accept only reads and transaction-local set_config, never a write.
+ const early = typeof options === 'object' && options.early
+ && (sql.options.transaction_pipeline > sql.options.max_pipeline || sql.options.max_pipeline > 0)
+ ? options.early
+ : null
typeof options === 'object' && (options = options.mode || '')
let savepoints = 0
, connection
, prepare = null
, opening = null
, firstSeen = false
+ , held = false
, written
try {
const begun = sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
- if (!first) {
+ if (!first && !early) {
await begun
return await Promise.race([
scope(connection, fn),
@@ -495,17 +504,21 @@ function Postgres(a, b) {
q.catch(e => uncaughtError || (uncaughtError = e))
if (!reservation || c.reserved !== reservation)
return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
- // GBrain (#6930): while BEGIN is unanswered only an accepted first statement is sent; the rest wait, in order. It
- // is accepted on its text (`$n` for each argument, as statementText builds it) only when every argument is a
- // parameter value: a fragment (a query, a helper, an identifier) would carry SQL the test never saw.
+ // GBrain (#6930, GBRA-156): while BEGIN is unanswered only accepted statements are sent (the first one for
+ // `first`; each one until one is refused for `early`); the rest wait, in order. A statement is accepted on its
+ // text (`$n` for each argument, as statementText builds it) only when every argument is a parameter value: a
+ // fragment (a query, a helper, an identifier) would carry SQL the test never saw.
if (opening) {
const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
- const early = !firstSeen
+ const test = early || !firstSeen && first
+ const sent = !held && test
&& q.args.every(x => !(x instanceof Query || x instanceof Builder || x instanceof Identifier || Array.isArray(x) && x.some(y => y instanceof Query)))
- && first(strings.reduce((a, s, i) => a + '$' + i + s))
+ && test(strings.reduce((a, s, i) => a + '$' + i + s))
firstSeen = true
- if (!early)
+ if (!sent) {
+ held = true
return opening.then(() => handler(q), q.reject)
+ }
}
reservation.enqueue(q)
}
diff --git a/vendor/postgres/src/index.js b/vendor/postgres/src/index.js
index abf09edaa7..f93237cbd4 100644
--- a/vendor/postgres/src/index.js
+++ b/vendor/postgres/src/index.js
@@ -410,17 +410,26 @@ function Postgres(a, b) {
const first = typeof options === 'object' && options.first && sql.options.transaction_pipeline > sql.options.max_pipeline
? options.first
: null
+ // GBrain (GBRA-156): `{ early }` sends every statement it accepts, in order, behind BEGIN before BEGIN's answer,
+ // on any pool that pipelines inside a transaction (a pipelining pool, or transaction_pipeline behind a pooler that
+ // does not). The first statement it refuses, and every later one, waits for the answer. If BEGIN fails the accepted
+ // statements run in autocommit, so `early` must accept only reads and transaction-local set_config, never a write.
+ const early = typeof options === 'object' && options.early
+ && (sql.options.transaction_pipeline > sql.options.max_pipeline || sql.options.max_pipeline > 0)
+ ? options.early
+ : null
typeof options === 'object' && (options = options.mode || '')
let savepoints = 0
, connection
, prepare = null
, opening = null
, firstSeen = false
+ , held = false
, written
try {
const begun = sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
- if (!first) {
+ if (!first && !early) {
await begun
return await Promise.race([
scope(connection, fn),
@@ -495,17 +504,21 @@ function Postgres(a, b) {
q.catch(e => uncaughtError || (uncaughtError = e))
if (!reservation || c.reserved !== reservation)
return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
- // GBrain (#6930): while BEGIN is unanswered only an accepted first statement is sent; the rest wait, in order. It
- // is accepted on its text (`$n` for each argument, as statementText builds it) only when every argument is a
- // parameter value: a fragment (a query, a helper, an identifier) would carry SQL the test never saw.
+ // GBrain (#6930, GBRA-156): while BEGIN is unanswered only accepted statements are sent (the first one for
+ // `first`; each one until one is refused for `early`); the rest wait, in order. A statement is accepted on its
+ // text (`$n` for each argument, as statementText builds it) only when every argument is a parameter value: a
+ // fragment (a query, a helper, an identifier) would carry SQL the test never saw.
if (opening) {
const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
- const early = !firstSeen
+ const test = early || !firstSeen && first
+ const sent = !held && test
&& q.args.every(x => !(x instanceof Query || x instanceof Builder || x instanceof Identifier || Array.isArray(x) && x.some(y => y instanceof Query)))
- && first(strings.reduce((a, s, i) => a + '$' + i + s))
+ && test(strings.reduce((a, s, i) => a + '$' + i + s))
firstSeen = true
- if (!early)
+ if (!sent) {
+ held = true
return opening.then(() => handler(q), q.reject)
+ }
}
reservation.enqueue(q)
}
diff --git a/vendor/postgres/types/index.d.ts b/vendor/postgres/types/index.d.ts
index 03a10236da..1c4a50bbba 100644
--- a/vendor/postgres/types/index.d.ts
+++ b/vendor/postgres/types/index.d.ts
@@ -780,8 +780,10 @@ declare namespace postgres {
* GBrain (#6930): with transaction_pipeline in force, the first statement `first` accepts (its text, `$n` for
* parameters) is sent behind BEGIN before BEGIN's answer. If BEGIN fails it runs in autocommit, so `first` must
* accept only a read or a transaction-local set_config, never a write.
+ * GBrain (GBRA-156): on any pool that pipelines inside a transaction, every statement `early` accepts, in order, is
+ * sent behind BEGIN before BEGIN's answer; the first it refuses, and every later one, waits. The same rule applies.
*/
- begin<T>(options: { mode?: string; first?: (statement: string) => boolean }, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
+ begin<T>(options: { mode?: string; first?: (statement: string) => boolean; early?: (statement: string) => boolean }, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
reserve(options?: { signal?: AbortSignal }): Promise<ReservedSql<TTypes>>
}