Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search): typed-search type check in one JIT-off statement (LHF wave 2 item 1)

garrytancc7b91172d00
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 09c5b15ce4..4f928836a4 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -51,7 +51,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/ops/raw-data.ts` — `put_raw_data` / `get_raw_data`. `get_raw_data` follows the page soft-delete (a tombstoned page reads as `[]`, `restore_page` brings the rows back; there is no remote `include_deleted` param — `get_page include_deleted: true` verifies the tombstone) and, per #4352, a `visibility: private` page's raw data reads exactly like a missing page's for untrusted callers. Scope comes from `readPolicyOpts(ctx)`, never from MCP parameters.
-- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate. Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. `searchOutput` then projects the returned rows to the caller's row shape (`src/core/search/lean-rows.ts`: lean for remote callers unless `fields: "full"`, the transport chose full rows, or the caller is trusted-local; a lean row keeps `id` only when `ctx.isCallable('fetch')`, the MCP dispatch predicate `buildOperationContext` threads in, says the caller can call `fetch` (unset keeps it), and prints `score` at 4 significant digits) and reports it as `retrieval.rows` for remote callers and whenever `fields` is passed. The CLI formatter repeats this on JSON, explain and human output. System One: the `query` op asks S4 answerability (`decide.answerability`, diagnostic only) and surfaces `meta.answerability`; the crag escalation re-run keeps S2-S5 off (`rerankOnly`). Each handler times its request (`SearchTimings`, search/stage-timings.ts) and `searchOutput` emits `retrieval.timings` last. `buildRetrievalResponseMeta` also stamps `stale` on hits whose page's newer file is held, adds `held_files` per source in scope and emits the `held_files` degraded notice (`persistence/held-reads.ts`; Test: `test/held-read-signals.test.ts`).
+- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate. Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. `searchOutput` then projects the returned rows to the caller's row shape (`src/core/search/lean-rows.ts`: lean for remote callers unless `fields: "full"`, the transport chose full rows, or the caller is trusted-local; a lean row keeps `id` only when `ctx.isCallable('fetch')`, the MCP dispatch predicate `buildOperationContext` threads in, says the caller can call `fetch` (unset keeps it), and prints `score` at 4 significant digits) and reports it as `retrieval.rows` for remote callers and whenever `fields` is passed. The CLI formatter repeats this on JSON, explain and human output. System One: the `query` op asks S4 answerability (`decide.answerability`, diagnostic only) and surfaces `meta.answerability`; the crag escalation re-run keeps S2-S5 off (`rerankOnly`). Each handler times its request (`SearchTimings`, search/stage-timings.ts) and `searchOutput` emits `retrieval.timings` last. The typed-search type check lives in `ops/search-type-filter.ts` (`reconcileTypeFilter`): one statement of per-type `EXISTS` probes over each type's schema-expanded set, with the `DISTINCT` type list for the `type_filter_notice` evaluated only when a probe misses, run `jitOff` and unprepared (a generic plan scans every page per missing type); pinned by `test/search-type-filter-reconcile.test.ts` and `test/e2e/typed-search-jit-postgres.test.ts`. `buildRetrievalResponseMeta` also stamps `stale` on hits whose page's newer file is held, adds `held_files` per source in scope and emits the `held_files` degraded notice (`persistence/held-reads.ts`; Test: `test/held-read-signals.test.ts`).
- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 1cf3c7017a..bf35a04e1c 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -41,7 +41,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`. `PoisonedDiscardCounter` counts the driver's non-idle connection discards and writes one fixed-shape `pg_connection_poisoned` warn line each; the engine wires it into every pool it creates and reports it as `poisonedDiscards`. `onCheckout(listener)` (exposed as `PostgresEngine.onCheckout`) fires after a connection is actually obtained: signalled raw reserve resolution, transaction-callback entry and `withReservedConnection` reserve resolution; it never fires for a call still waiting (pinned by `test/e2e/postgres-checkout-observer.test.ts`). `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. Inside a caller's transaction the search runs in a savepoint and restores the caller's `jit` afterwards. Pinned by `test/e2e/search-query-contract-postgres.test.ts`. `getEmbeddingsByChunkIds` (in `src/core/engine-sql/chunks.ts`, both engines) uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. The chunk SQL below lives once in `src/core/engine-sql/chunks.ts`; the engine resolves the active column and source scope, owns the retry/transaction wrapper and the RLS scope transaction, and passes them in. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap(conn)` BEFORE replaying SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (Postgres dialect hooks: `current_schema()` probes plus the Postgres-blob-only `dream_verdicts.expires_at` probe); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). When the DDL pool has more than one slot, `initSchema` reserves one backend and runs the advisory lock 42 acquire, the bootstrap, the schema replay and the unlock on it, releasing it in `finally` (checkout gauge only, no long-hold permit, so pending `transaction: false` migrations can still reserve); a one-slot pool is already a single backend and runs unreserved. Pinned by `test/e2e/postgres-initschema-advisory-lock.test.ts`. `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-lifecycle.test.ts` (concurrent-connect ownership, `db.disconnect()` detaching the singleton before awaiting `end()`, and the instance-reconnect `_reconnecting` guard). `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`). #6278 PR 1.5: `runUnsafe` arms a settle timer after a signalled statement's `cancel()`; a statement still pending `cancelSettleMs()` later (`GBRAIN_CANCEL_SETTLE_MS`, default 2000) has its reserved connection discarded so the awaiting caller settles with `CONNECTION_DESTROYED` instead of parking on a round-trip a transaction-mode pooler never completed (backend in `ClientRead`). 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/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. Inside a caller's transaction the search runs in a savepoint and restores the caller's `jit` afterwards. Pinned by `test/e2e/search-query-contract-postgres.test.ts`. `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`.
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/src/core/engine.ts b/src/core/engine.ts
index 0f81c39c0a..09d88a58b0 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -2651,11 +2651,13 @@ export interface BrainEngine {
* transaction the option is ignored (a `SET LOCAL` there would change the
* enclosing transaction). PGLite ignores it: one in-process connection has
* no other session to wait on. `deadlineAt` (#6696, epoch ms) recomputes the bound after the pool wait.
+ * `jitOff` runs the statement with `jit = off` when the server has JIT on (postgres-engine/jit-off-statement.ts); PGLite ignores it.
+ * `prepare: false` plans the statement for its actual parameters on every call instead of a cached generic plan.
*/
executeRaw<T = Record<string, unknown>>(
sql: string,
params?: unknown[],
- opts?: { signal?: AbortSignal; timeoutMs?: number; deadlineAt?: number },
+ opts?: { signal?: AbortSignal; timeoutMs?: number; deadlineAt?: number; jitOff?: boolean; prepare?: boolean },
): Promise<T[]>;
/**
diff --git a/src/core/ops/search-type-filter.ts b/src/core/ops/search-type-filter.ts
new file mode 100644
index 0000000000..b655e70211
--- /dev/null
+++ b/src/core/ops/search-type-filter.ts
@@ -0,0 +1,57 @@
+/**
+ * Agents guess page types ("company", "account", "deal") that a brain may not
+ * have, and a filter on a type with no pages silently hides every page
+ * (gbrain-evals Cat 40: type-filtered agent runs failed 62% of tasks against
+ * 51% unfiltered). Requested types with no readable pages in scope are
+ * dropped, the rest stay; when none remain the filter is lifted. Either way
+ * the caller is told which types exist so it can refine.
+ *
+ * One statement answers it: an `EXISTS` per requested type's
+ * schema-expanded set, and the `DISTINCT` type list for the notice, which
+ * Postgres evaluates only when a probe came back false (a subplan in an
+ * untaken `CASE` branch never runs). It runs with JIT off (LHF wave 2 item
+ * 1): the correlated visibility subplans cost past `jit_above_cost`, and
+ * LLVM compilation took about half a second per typed search on Postgres.
+ * It is planned for its parameters on every call: a cached generic plan
+ * cannot tell a missing type from a common one and scans every page for
+ * each missing type, where the custom plan reads the type index. `OFFSET 0`
+ * keeps each probe evaluated once.
+ */
+import { expandEngineTypeFilters } from '../schema-pack/query-types.ts';
+import { pageReadFilter } from '../search/read-policy-sql.ts';
+import type { TrustTier } from '../trust/tier.ts';
+import type { OperationContext } from './contract.ts';
+
+type SourceScope = { sourceId?: string; sourceIds?: string[]; minTrust?: TrustTier };
+
+export async function reconcileTypeFilter(ctx: OperationContext, scope: SourceScope, excludePrivate: boolean,
+ types: string[] | undefined): Promise<{ types: string[] | undefined; notice?: string }> {
+ if (!types || scope.sourceIds?.length === 0) return { types };
+ // A schema-pack lookup failure propagates: typed reads fail closed rather than fall back to literal types.
+ const expanded = await Promise.all(types.map(async type => (await expandEngineTypeFilters(ctx.engine, { types: [type], ...scope })).types ?? [type]));
+ const params: unknown[] = [];
+ const filter = pageReadFilter('p', { ...scope, excludePrivate }, params, true);
+ const probes = expanded.flatMap((set, i) => {
+ if (set.length === 0) return [];
+ params.push(set);
+ return [{ name: `t${i}`, sql: `EXISTS (SELECT 1 FROM pages p WHERE ${filter} AND p.type = ANY($${params.length}::text[])) AS t${i}` }];
+ });
+ if (probes.length === 0) return { types };
+ let row: Record<string, unknown> | undefined;
+ try {
+ [row] = await ctx.engine.executeRaw(
+ `SELECT probe.*, CASE WHEN ${probes.map(p => `probe.${p.name}`).join(' AND ')} THEN NULL
+ ELSE ARRAY(SELECT DISTINCT p.type FROM pages p WHERE ${filter} LIMIT 500) END AS available
+ FROM (SELECT ${probes.map(p => p.sql).join(', ')} OFFSET 0) probe`, params, { jitOff: true, prepare: false });
+ } catch {
+ return { types };
+ }
+ const keep: string[] = [];
+ const missing: string[] = [];
+ types.forEach((type, i) => (expanded[i].length === 0 || row?.[`t${i}`] === true ? keep : missing).push(type));
+ if (missing.length === 0) return { types };
+ const available = [...new Set((row?.available ?? []) as string[])].sort().join(', ');
+ return keep.length === 0
+ ? { types: undefined, notice: `No pages have type ${missing.join(', ')}, so the type filter was dropped and every page type was searched. Page types in this brain: ${available}.` }
+ : { types: keep, notice: `No pages have type ${missing.join(', ')}; filtered to ${keep.join(', ')}. Page types in this brain: ${available}.` };
+}
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 77e12bc696..0fd0c290f8 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -41,6 +41,7 @@ import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';
import { expandEngineTypeFilters } from '../schema-pack/query-types.ts';
+import { reconcileTypeFilter } from './search-type-filter.ts';
import { probeProjectionReadiness } from '../search/projection-readiness.ts';
import { resolveBoostMap, resolveHardExcludes } from '../search/source-boost.ts';
import { pageReadFilter } from '../search/read-policy-sql.ts';
@@ -253,40 +254,6 @@ async function hasUnsealedPagesInScope(ctx: OperationContext, scope: SourceScope
}
}
-/**
- * Agents guess page types ("company", "account", "deal") that a brain may not
- * have, and a filter on a type with no pages silently hides every page
- * (gbrain-evals Cat 40: type-filtered agent runs failed 62% of tasks against
- * 51% unfiltered). Requested types with no readable pages in scope are
- * dropped, the rest stay; when none remain the filter is lifted. Either way
- * the caller is told which types exist so it can refine.
- */
-async function reconcileTypeFilter(ctx: OperationContext, scope: SourceScope, excludePrivate: boolean,
- types: string[] | undefined): Promise<{ types: string[] | undefined; notice?: string }> {
- if (!types || scope.sourceIds?.length === 0) return { types };
- const params: unknown[] = [];
- let present: Set<string>;
- try {
- const rows = await ctx.engine.executeRaw<{ type: string }>(
- `SELECT DISTINCT p.type FROM pages p WHERE ${pageReadFilter('p', { ...scope, excludePrivate }, params, true)} LIMIT 500`, params);
- present = new Set(rows.map(r => r.type));
- } catch {
- return { types };
- }
- const keep: string[] = [];
- const missing: string[] = [];
- for (const type of types) {
- // A schema-pack lookup failure propagates: typed reads fail closed rather than fall back to literal types.
- const expanded = (await expandEngineTypeFilters(ctx.engine, { types: [type], ...scope })).types ?? [type];
- (expanded.length === 0 || expanded.some(t => present.has(t)) ? keep : missing).push(type);
- }
- if (missing.length === 0) return { types };
- const available = [...present].sort().join(', ');
- return keep.length === 0
- ? { types: undefined, notice: `No pages have type ${missing.join(', ')}, so the type filter was dropped and every page type was searched. Page types in this brain: ${available}.` }
- : { types: keep, notice: `No pages have type ${missing.join(', ')}; filtered to ${keep.join(', ')}. Page types in this brain: ${available}.` };
-}
-
const FACT_MATCH_STOPWORDS = new Set(['the', 'and', 'for', 'who', 'what', 'when', 'where', 'which', 'with', 'from', 'that', 'this', 'are', 'was', 'were', 'our', 'your', 'their', 'now', 'current', 'currently', 'should', 'does', 'did', 'has', 'have', 'how', 'any', 'all', 'about', 'into', 'its', 'next']);
export interface AliasDeclaration { name: string; alias: string; slug: string }
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 26366f8fe6..f1a3a0b991 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -18,6 +18,7 @@ import { reservedTransactions, type ReservedTransactions } from './postgres-engi
import { traceSqlOptions } from './sql-trace.ts';
import { hasPostgresCancellationCapability, postgresCancellationUnavailable, reserveWithCancellation } from './postgres-engine/cancellation.ts';
import { runBoundedStatement } from './postgres-engine/bounded-statement.ts';
+import { needsJitOff, runJitOffStatement } from './postgres-engine/jit-off-statement.ts';
import { schemaDiagnosticConnection, withSchemaLockTimeout } from './postgres-engine/schema-lock-timeout.ts';
export { hasPostgresCancellationCapability } from './postgres-engine/cancellation.ts';
import type {
@@ -2879,13 +2880,14 @@ export class PostgresEngine implements BrainEngine {
async executeRaw<T = Record<string, unknown>>(
sql: string,
params?: unknown[],
- opts?: { signal?: AbortSignal; timeoutMs?: number; deadlineAt?: number },
+ opts?: { signal?: AbortSignal; timeoutMs?: number; deadlineAt?: number; jitOff?: boolean; prepare?: boolean },
): Promise<T[]> {
// try/finally (not .finally on the promise): runUnsafe throws
// SYNCHRONOUSLY on a pre-aborted signal, which would skip a chained
// .finally and leak the counter.
this.checkoutGauge.acquire('raw');
try {
+ if (opts?.jitOff && await needsJitOff(this.sql, this._pageTransaction)) return await runJitOffStatement<T>(this.sql, this._pageTransaction, sql, params, opts, (c, s, p, o) => this.runUnsafe(c, s, p, o), () => this.checkoutGauge.checkedOut());
// #6278: a transaction-local statement_timeout, which holds through a transaction-mode pooler (postgres-engine/bounded-statement.ts).
if (opts?.timeoutMs !== undefined && !this._pageTransaction) {
return await runBoundedStatement<T>(this.sql, sql, params, { ...opts, timeoutMs: opts.timeoutMs }, () => this.checkoutGauge.checkedOut());
diff --git a/src/core/postgres-engine/bounded-statement.ts b/src/core/postgres-engine/bounded-statement.ts
index 681da08d3f..1ec51e598a 100644
--- a/src/core/postgres-engine/bounded-statement.ts
+++ b/src/core/postgres-engine/bounded-statement.ts
@@ -12,21 +12,40 @@
* connection (a saturated pool must not hold the bound off); the statement
* itself ends at the bound, never by a cancel request. With `deadlineAt` the
* bound is the time left after the connection was reserved (#6696 B1).
+ *
+ * `jitOff` adds `SET LOCAL jit = off` to the same envelope (see
+ * jit-off-statement.ts). Without `timeoutMs` there is no bound, and a
+ * signalled statement runs through `run` (the engine's `runUnsafe`), so
+ * `signal` still cancels it in flight as it would a plain `executeRaw`; its
+ * `COMMIT` follows the statement instead of riding in the same round trip.
*/
import type postgres from '#postgres';
import { reserveWithCancellation } from './cancellation.ts';
-// engine-sql-ok: transaction control around a caller's statement (BEGIN / SET LOCAL statement_timeout / COMMIT), no storage-domain SQL
-export async function runBoundedStatement<T>(conn: ReturnType<typeof postgres>, sql: string, params: unknown[] | undefined,
- opts: { timeoutMs: number; deadlineAt?: number; signal?: AbortSignal }, onReserved: () => void): Promise<T[]> {
+type Sql = ReturnType<typeof postgres>;
+export type RunStatement = <T>(conn: Sql, sql: string, params: unknown[] | undefined, opts: { signal?: AbortSignal; prepare?: boolean }) => Promise<T[]>;
+
+// engine-sql-ok: transaction control around a caller's statement (BEGIN / SET LOCAL statement_timeout / SET LOCAL jit / COMMIT), no storage-domain SQL
+export async function runBoundedStatement<T>(conn: Sql, sql: string, params: unknown[] | undefined,
+ opts: { timeoutMs?: number; deadlineAt?: number; signal?: AbortSignal; jitOff?: boolean; prepare?: boolean }, onReserved: () => void, run?: RunStatement): Promise<T[]> {
const reserved = opts.signal ? await reserveWithCancellation(reserve => conn.reserve(reserve), opts.signal) : await conn.reserve();
onReserved();
- // #6696 B1: an absolute deadline is re-read after the pool wait, so time spent waiting for a connection is not granted again.
- const ms = Math.max(1, Math.ceil(opts.deadlineAt !== undefined ? Math.min(opts.timeoutMs, opts.deadlineAt - Date.now()) : opts.timeoutMs));
+ const settings = opts.jitOff ? ['SET LOCAL jit = off'] : [];
+ if (opts.timeoutMs !== undefined) {
+ // #6696 B1: an absolute deadline is re-read after the pool wait, so time spent waiting for a connection is not granted again.
+ const ms = Math.max(1, Math.ceil(opts.deadlineAt !== undefined ? Math.min(opts.timeoutMs, opts.deadlineAt - Date.now()) : opts.timeoutMs));
+ settings.push(`SET LOCAL statement_timeout = ${ms}`);
+ }
try {
- const open = reserved.unsafe(`BEGIN; SET LOCAL statement_timeout = ${ms}`).simple().execute();
- const read = reserved.unsafe(sql, params as Parameters<typeof reserved.unsafe>[1], { prepare: true }).execute();
- const close = reserved.unsafe('COMMIT').execute();
+ const open = reserved.unsafe(['BEGIN', ...settings].join('; ')).simple().execute();
+ // A cancellable statement is issued through `run`, which awaits the query and so enqueues it a microtask
+ // later than `execute()` would: COMMIT then waits for it to settle instead of being pipelined ahead of it.
+ const cancellable = opts.timeoutMs === undefined && opts.signal && run;
+ const read = cancellable
+ ? (async () => run<T>(reserved as unknown as Sql, sql, params, { signal: opts.signal, prepare: opts.prepare }))()
+ : reserved.unsafe(sql, params as Parameters<typeof reserved.unsafe>[1], { prepare: opts.prepare ?? true }).execute();
+ const commit = () => reserved.unsafe('COMMIT').execute();
+ const close = cancellable ? read.then(commit, commit) : commit();
const settled = await Promise.allSettled([open, read, close]);
for (const outcome of settled) if (outcome.status === 'rejected') throw outcome.reason;
return (settled[1] as PromiseFulfilledResult<unknown>).value as T[];
diff --git a/src/core/postgres-engine/jit-off-statement.ts b/src/core/postgres-engine/jit-off-statement.ts
new file mode 100644
index 0000000000..67dc05dbd4
--- /dev/null
+++ b/src/core/postgres-engine/jit-off-statement.ts
@@ -0,0 +1,60 @@
+/**
+ * `executeRaw(sql, params, { jitOff: true })` on Postgres (LHF wave 2 item 1).
+ *
+ * Some short reads outside the search transactions (the typed-search type
+ * check) cost more than `jit_above_cost`, and Postgres then compiles them
+ * with LLVM on every call: half a second of compilation for a sub-millisecond
+ * read. The wrapper costs round trips, so it runs only where it pays:
+ *
+ * - Outside a transaction, the server's `jit` setting is read once per pool.
+ * With JIT off the statement runs exactly as a plain `executeRaw`; with JIT
+ * on it runs in the pipelined envelope of bounded-statement.ts (`BEGIN; SET
+ * LOCAL jit = off`, the statement, `COMMIT` in one round trip), which keeps
+ * `timeoutMs`/`deadlineAt`, the reservation's abort signal and the checkout
+ * gauge.
+ * - Inside a caller's transaction the caller's own value is read, and when
+ * it is on, `SET LOCAL jit = off`, the statement and the restore of the
+ * caller's value are pipelined (a signalled statement's restore follows it). A failed statement aborts the caller's
+ * transaction as a plain `executeRaw` would, so nothing is left to restore.
+ *
+ * `SET LOCAL` never leaks past the transaction, so a transaction-mode pooler
+ * never hands a JIT-off session to another client. PGLite has no JIT
+ * provider and ignores the option.
+ */
+import type postgres from '#postgres';
+import { runBoundedStatement, type RunStatement } from './bounded-statement.ts';
+
+type Sql = ReturnType<typeof postgres>;
+
+const serverJit = new WeakMap<object, Promise<boolean>>();
+
+/** Whether a statement on this pool needs the JIT-off envelope; a failed read counts as on, since the envelope is always correct. */
+export function needsJitOff(pool: Sql, nested: boolean): Promise<boolean> {
+ if (nested) return Promise.resolve(true);
+ let known = serverJit.get(pool);
+ if (!known) {
+ // engine-sql-ok: jit is a Postgres server setting; PGLite has no JIT provider
+ known = pool.unsafe(`SELECT current_setting('jit') AS jit`).then(rows => (rows[0] as { jit?: string } | undefined)?.jit !== 'off');
+ serverJit.set(pool, known);
+ known.catch(() => { if (serverJit.get(pool) === known) serverJit.delete(pool); });
+ }
+ return known.catch(() => true);
+}
+
+// engine-sql-ok: jit is a Postgres server setting; PGLite has no JIT provider
+export async function runJitOffStatement<T>(conn: Sql, nested: boolean, sql: string, params: unknown[] | undefined,
+ opts: { signal?: AbortSignal; timeoutMs?: number; deadlineAt?: number; prepare?: boolean }, run: RunStatement, onReserved: () => void): Promise<T[]> {
+ if (!nested) return runBoundedStatement<T>(conn, sql, params, { ...opts, jitOff: true }, onReserved, run);
+ const [current] = await conn.unsafe(`SELECT current_setting('jit') AS jit`) as unknown as Array<{ jit: string }>;
+ if (current?.jit === 'off') return run<T>(conn, sql, params, { signal: opts.signal, prepare: opts.prepare });
+ const set = conn.unsafe('SET LOCAL jit = off').execute();
+ // As in bounded-statement.ts: a signalled statement goes through `run`, which enqueues it a microtask late, so the restore waits for it.
+ const read = opts.signal
+ ? (async () => run<T>(conn, sql, params, { signal: opts.signal, prepare: opts.prepare }))()
+ : conn.unsafe(sql, params as Parameters<typeof conn.unsafe>[1], { prepare: opts.prepare ?? true }).execute() as unknown as Promise<T[]>;
+ const reset = () => conn.unsafe(`SELECT set_config('jit', $1, true)`, [current!.jit]).execute();
+ const restore = opts.signal ? read.then(reset, reset) : reset();
+ const settled = await Promise.allSettled([set, read, restore]);
+ for (const outcome of settled) if (outcome.status === 'rejected') throw outcome.reason;
+ return (settled[1] as PromiseFulfilledResult<T[]>).value;
+}
diff --git a/test/e2e/typed-search-jit-postgres.test.ts b/test/e2e/typed-search-jit-postgres.test.ts
new file mode 100644
index 0000000000..61e5675ead
--- /dev/null
+++ b/test/e2e/typed-search-jit-postgres.test.ts
@@ -0,0 +1,138 @@
+/**
+ * LHF wave 2 item 1: the typed-search type check (`reconcileTypeFilter`)
+ * runs its batched EXISTS probes, and its DISTINCT type list only when a
+ * probe misses, in one statement with JIT off (`executeRaw({ jitOff: true })`). The plan assertions
+ * run on a one-connection engine whose session sets `jit_above_cost = 0`, so
+ * every statement that keeps JIT on compiles and shows a `JIT` block: the
+ * control proves the assertion can fail.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { serializeMarkdown } from '../../src/core/markdown.ts';
+import { reconcileTypeFilter } from '../../src/core/ops/search-type-filter.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+
+const url = process.env.DATABASE_URL!;
+type Raw = { sql: string; params: unknown[]; opts?: { jitOff?: boolean; prepare?: boolean } };
+
+async function oneConnection(settings: string[]): Promise<PostgresEngine> {
+ const engine = new PostgresEngine();
+ await engine.connect({ engine: 'postgres', database_url: url, poolSize: 1 });
+ for (const setting of settings) await engine.executeRaw(setting);
+ return engine;
+}
+
+async function explain(engine: PostgresEngine, raw: Raw, opts?: { jitOff?: boolean }): Promise<string> {
+ const [row] = await engine.executeRaw<{ 'QUERY PLAN': unknown }>(`EXPLAIN (ANALYZE, FORMAT JSON) ${raw.sql}`, raw.params, opts);
+ return JSON.stringify(row!['QUERY PLAN']);
+}
+
+/** Loops of the DISTINCT type list's LIMIT node: 0 when the subplan never ran. */
+function distinctLoops(plan: string): number {
+ const limits: number[] = [];
+ const walk = (node: Record<string, unknown>) => {
+ if (node['Node Type'] === 'Limit') limits.push(node['Actual Loops'] as number);
+ for (const child of (node.Plans as Array<Record<string, unknown>> | undefined) ?? []) walk(child);
+ };
+ walk((JSON.parse(plan) as Array<{ Plan: Record<string, unknown> }>)[0]!.Plan);
+ expect(limits.length).toBe(1);
+ return limits[0]!;
+}
+
+async function captureTypeCheck(engine: PostgresEngine, types: string[]): Promise<{ result: Awaited<ReturnType<typeof reconcileTypeFilter>>; statements: Raw[] }> {
+ const statements: Raw[] = [];
+ const execute = engine.executeRaw.bind(engine);
+ const spy = Object.assign(Object.create(engine), {
+ executeRaw: (sql: string, params?: unknown[], opts?: Raw['opts']) => {
+ if (/FROM pages p WHERE/.test(sql)) statements.push({ sql, params: params ?? [], opts });
+ return execute(sql, params, opts);
+ },
+ }) as PostgresEngine;
+ const ctx = { engine: spy, remote: true } as unknown as OperationContext;
+ return { result: await reconcileTypeFilter(ctx, { sourceId: 'default' }, false, types), statements };
+}
+
+(hasDatabase() ? describe : describe.skip)('typed-search type check without JIT (Postgres)', () => {
+ let engine: PostgresEngine;
+ beforeAll(async () => {
+ engine = await setupDB();
+ for (const [slug, type] of [['notes/jit-alpha', 'note'], ['companies/acme-example', 'company'], ['people/alice-example', 'person']] as const) {
+ await importFromContent(engine, slug, serializeMarkdown({}, `${slug} body`, '', { type, title: slug, tags: [] }), { noEmbed: true, forceRechunk: true });
+ }
+ }, 120_000);
+ afterAll(async () => { await teardownDB(); });
+
+ test('the one type-check statement shows no JIT block; with JIT on it does; the DISTINCT list runs only on a miss', async () => {
+ const reader = await oneConnection(['SET jit = on', 'SET jit_above_cost = 0']);
+ try {
+ const hit = await captureTypeCheck(reader, ['note']);
+ expect(hit.result).toEqual({ types: ['note'] });
+ const miss = await captureTypeCheck(reader, ['note', 'deal-example']);
+ expect(miss.result).toEqual({ types: ['note'], notice: 'No pages have type deal-example; filtered to note. Page types in this brain: company, note, person.' });
+ expect([hit.statements.length, miss.statements.length]).toEqual([1, 1]);
+
+ for (const statement of [...hit.statements, ...miss.statements]) {
+ expect(statement.opts).toEqual({ jitOff: true, prepare: false });
+ expect((await explain(reader, statement, statement.opts)).includes('"JIT"')).toBe(false);
+ expect((await explain(reader, statement)).includes('"JIT"')).toBe(true);
+ }
+ expect(distinctLoops(await explain(reader, hit.statements[0]!, { jitOff: true }))).toBe(0);
+ expect(distinctLoops(await explain(reader, miss.statements[0]!, { jitOff: true }))).toBe(1);
+ expect(await reader.executeRaw(`SELECT current_setting('jit') AS jit`)).toEqual([{ jit: 'on' }]);
+ } finally { await reader.disconnect(); }
+ }, 60_000);
+
+ test('a server with JIT off runs the statement as a plain read', async () => {
+ const reader = await oneConnection(['SET jit = off', 'SET jit_above_cost = 0']);
+ try {
+ const miss = await captureTypeCheck(reader, ['company', 'deal-example']);
+ expect(miss.result.types).toEqual(['company']);
+ for (const statement of miss.statements) expect((await explain(reader, statement, statement.opts)).includes('"JIT"')).toBe(false);
+ expect(await reader.executeRaw(`SELECT current_setting('jit') AS jit`, [], { jitOff: true })).toEqual([{ jit: 'off' }]);
+ } finally { await reader.disconnect(); }
+ }, 60_000);
+
+ test('inside a caller transaction the statement runs JIT off and the caller keeps its setting', async () => {
+ const reader = await oneConnection(['SET jit = on', 'SET jit_above_cost = 0']);
+ try {
+ const seen = await reader.transaction(async tx => {
+ const inner = await tx.executeRaw<{ jit: string }>(`SELECT current_setting('jit') AS jit`, [], { jitOff: true });
+ const after = await tx.executeRaw<{ jit: string }>(`SELECT current_setting('jit') AS jit`);
+ await tx.executeRaw(`SET LOCAL jit = off`);
+ const offInner = await tx.executeRaw<{ jit: string }>(`SELECT current_setting('jit') AS jit`, [], { jitOff: true });
+ const offAfter = await tx.executeRaw<{ jit: string }>(`SELECT current_setting('jit') AS jit`);
+ return [inner[0]!.jit, after[0]!.jit, offInner[0]!.jit, offAfter[0]!.jit];
+ });
+ expect(seen).toEqual(['off', 'on', 'off', 'off']);
+ await expect(reader.transaction(async tx => { await tx.executeRaw('SELECT 1 / 0', [], { jitOff: true }); })).rejects.toThrow(/division by zero/);
+ expect(await reader.executeRaw(`SELECT current_setting('jit') AS jit`)).toEqual([{ jit: 'on' }]);
+ } finally { await reader.disconnect(); }
+ }, 60_000);
+
+ test('the envelope keeps the deadline, the abort signal and the connection', async () => {
+ const reader = await oneConnection(['SET jit = on']);
+ try {
+ const bounded = await reader.executeRaw(`SELECT pg_sleep(2)`, [], { jitOff: true, timeoutMs: 150 }).catch((e: { code?: string }) => e.code);
+ expect(bounded).toBe('57014');
+ const deadline = await reader.executeRaw(`SELECT pg_sleep(2)`, [], { jitOff: true, timeoutMs: 60_000, deadlineAt: Date.now() + 150 }).catch((e: { code?: string }) => e.code);
+ expect(deadline).toBe('57014');
+ expect(await reader.executeRaw(`SELECT current_setting('jit') AS jit, current_setting('statement_timeout') AS t`, [], { jitOff: true, timeoutMs: 5_000 }))
+ .toEqual([{ jit: 'off', t: '5s' }]);
+
+ const aborted = new AbortController();
+ aborted.abort();
+ await expect(reader.executeRaw(`SELECT 1`, [], { jitOff: true, signal: aborted.signal })).rejects.toThrow(/abort/i);
+
+ const inFlight = new AbortController();
+ const started = Date.now();
+ setTimeout(() => inFlight.abort(), 150);
+ await expect(reader.executeRaw(`SELECT pg_sleep(5)`, [], { jitOff: true, signal: inFlight.signal })).rejects.toThrow();
+ expect(Date.now() - started).toBeLessThan(4_000);
+
+ expect(await reader.executeRaw(`SELECT current_setting('jit') AS jit`)).toEqual([{ jit: 'on' }]);
+ expect(await reader.executeRaw(`SELECT current_setting('jit') AS jit`, [], { jitOff: true, signal: new AbortController().signal })).toEqual([{ jit: 'off' }]);
+ } finally { await reader.disconnect(); }
+ }, 60_000);
+});
diff --git a/test/jit-off-statement.test.ts b/test/jit-off-statement.test.ts
new file mode 100644
index 0000000000..3e2d2e9d55
--- /dev/null
+++ b/test/jit-off-statement.test.ts
@@ -0,0 +1,52 @@
+/**
+ * LHF wave 2 item 1: `executeRaw({ jitOff })` reads the server's `jit` once
+ * per pool and skips the envelope when it is off; inside a transaction it
+ * reads the caller's value and restores it. Real Postgres behavior is pinned
+ * by test/e2e/typed-search-jit-postgres.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import { needsJitOff, runJitOffStatement } from '../src/core/postgres-engine/jit-off-statement.ts';
+
+function fakeConn(jit: string | Error) {
+ const sent: string[] = [];
+ const query = (text: string, rows: unknown[]) => {
+ sent.push(text);
+ const result = jit instanceof Error && text.includes('current_setting') ? Promise.reject(jit) : Promise.resolve(rows);
+ return Object.assign(result, { execute: () => result, simple: () => ({ execute: () => result }) });
+ };
+ const conn = { unsafe: (text: string) => query(text, text.includes("current_setting('jit')") ? [{ jit }] : [{ ok: 1 }]) };
+ return { conn: conn as never, sent };
+}
+
+describe('jitOff envelope selection', () => {
+ test('the server setting is read once per pool; off skips the envelope', async () => {
+ const off = fakeConn('off');
+ expect(await needsJitOff(off.conn, false)).toBe(false);
+ expect(await needsJitOff(off.conn, false)).toBe(false);
+ const on = fakeConn('on');
+ expect(await needsJitOff(on.conn, false)).toBe(true);
+ expect(await needsJitOff(on.conn, false)).toBe(true);
+ expect(off.sent).toEqual(["SELECT current_setting('jit') AS jit"]);
+ expect(on.sent).toEqual(["SELECT current_setting('jit') AS jit"]);
+ });
+
+ test('a failed read counts as on and is retried next time', async () => {
+ const failing = fakeConn(new Error('boom'));
+ expect(await needsJitOff(failing.conn, false)).toBe(true);
+ await Promise.resolve();
+ expect(await needsJitOff(failing.conn, false)).toBe(true);
+ expect(failing.sent.length).toBe(2);
+ });
+
+ test('inside a transaction the caller value decides and is restored after the statement', async () => {
+ const neverRun = () => { throw new Error('run is only for signalled statements'); };
+ const on = fakeConn('on');
+ expect(await runJitOffStatement(on.conn, true, 'SELECT 1', [], {}, neverRun as never, () => {})).toEqual([{ ok: 1 }]);
+ expect(on.sent).toEqual(["SELECT current_setting('jit') AS jit", 'SET LOCAL jit = off', 'SELECT 1', "SELECT set_config('jit', $1, true)"]);
+ const off = fakeConn('off');
+ let ran = 0;
+ await runJitOffStatement(off.conn, true, 'SELECT 1', [], {}, (async () => { ran++; return []; }) as never, () => {});
+ expect(off.sent).toEqual(["SELECT current_setting('jit') AS jit"]);
+ expect(ran).toBe(1);
+ });
+});