Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): vector joined fallback without page materialization; keyword arm carries ids until the final rows
garrytan295cee9d266c
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 77494b8c8e..c28c11709b 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -40,13 +40,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/stage-timings.ts` — per-request search stage timings. The `search`/`query` handlers create one `SearchTimings` and thread it into every hybrid call of the request (`HybridSearchOpts._timings`, `HybridRequest.timer`; absent = `UNTIMED`, a pass-through). `stage(name, work)` books critical-path blocked wall-clock time: one current stage at a time, a nested stage takes the clock and hands it back, so a fan-out or escalation hybrid call is booked once under its own stages, and retries accumulate. `overlap(label, promise)` times concurrent work (the keyword and title arms) into `overlapped_ms` without adding it to a stage. `branch()` returns a timer for stages run alongside the critical path (hybrid's vector side: modality, expansion, embed, vector arms); until `join(branch, promise)` its stage time goes to `overlapped_ms` under the stage name, and from the join the wait is booked to the branch's current stage (the stage key appears in `stages_ms` even at 0). `snapshot()` reads `total_ms` from its own monotonic start, apportions integer `stages_ms` + `other_ms` to sum to it exactly (`other_ms >= 0`); `searchOutput` takes it after the returned rows are assembled and emits it as `_meta.retrieval.timings` (never in content blocks); `formatTimingsSummary` is the `--explain` line. Stages: setup, lexical, relational, expansion, embed, vector, fuse, post_fusion, rerank, alias_fanout, anchoring, facts_arm, response. The gate (every bench query: `0 <= total - sum(stages) <= 10%`) is the `timings` phase of `scripts/bench-refactor-wave-1.ts`. Pinned by `test/search/stage-timings.test.ts` and `test/search/stage-timings-ops.test.ts`.- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.-- `src/core/search/keyword-chunk-match.ts` — `buildKeywordChunkMatch(ftsLang, excludePrivate)`: the chunk side of `PostgresEngine.searchKeyword`'s statement (FROM source for `cc`, the full-text match, the `modality = 'text'` filter). For excludePrivate callers it puts the match in an `OFFSET 0` subquery the planner plans on its own: the private-visibility subplans otherwise inflate every join 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` (~1.1 s → ~0.2 s for a common term at 250k chunks). Local callers keep the unfenced join, which can plan in parallel (an OFFSET subquery forbids that). PGLite does not use it. Pinned by `test/search/keyword-arm-ranking.test.ts` and `test/e2e/keyword-arm-ranking-postgres.test.ts`.+- `src/core/search/keyword-chunk-match.ts` — `buildKeywordChunkMatch(ftsLang, excludePrivate)`: the chunk side of `PostgresEngine.searchKeyword`'s statement (`cc` source, full-text match, text modality). For excludePrivate callers it plans the match alone in an `OFFSET 0` subquery; joined, the visibility subplans' cost let a seq scan detoasting every `search_vector` win (1.1 → 0.2 s, common term, 250k chunks). Local callers keep the unfenced, parallel-capable join. `KEYWORD_RANKED_ROWS_CTE`: ranking carries only ids, score and bounded_rows; display columns come from one `LIMIT 1` key probe per ranked chunk. Output equals the wide statement's; under the 50k bound (sample in plan order), its unspilled output. Not on PGLite. Pinned by `test/search/keyword-arm-ranking.test.ts`, `test/e2e/keyword-arm-ranking-postgres.test.ts`.- `src/core/search/title-match.ts` — pure, zero-I/O title-phrase matcher shared by the production title boost AND NamedThingBench (no drift). `isTitlePhraseMatch(query, title)` returns true when the normalized query is a contiguous token run inside the title with `>= MIN_CONTENT_TOKENS=2` non-stopword tokens, OR an exact full-title match (covers deliberate 1-word chosen names like "Helios"). Token-boundary matching (never raw substring, so "art" doesn't match "Bartholomew"); small conservative English stopword set excluded from the content-token floor (guards against promoting generic pages on stopword-y queries); NFKC normalize so CJK / width variants converge. `isTitleMentionedInQuery(query, title)` is the reverse direction the intent exact-match boost uses: the title appears as a contiguous token run INSIDE the query ("who is Alice Example" → "Alice Example"), guarded to titles with ≥2 content tokens or one content token of ≥4 characters. Exports `tokenizeTitle` + `__test__` internals.- `src/core/search/tune-recommendations.ts` — tuning recommendations never propose enabling or tuning unavailable semantic result caching. Mode-reduction suggestions describe payload size, not expansion savings: shipped commands pin expansion independently of the bundle.-- `src/core/search/vector-pool.ts` + `vector-settings.ts` — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness instead. Every pooled attempt scans with `hnsw.max_scan_tuples` = `POOL_MAX_SCAN_TUPLES` (20,000, pgvector's default), so a filtered attempt fills its candidate window before it is accepted; the index walk and scope scan keep their own window-sized budget (`searchIndexWalk`). Settings are restored even inside caller-owned transactions. A batch carries the raw `candidatePool` (exhaustion: a short window means the index ran dry) and an optional `eligiblePool` (candidates that passed the freshness filter outside the candidate CTE); `hasMore` receives the eligible count, defaulting to the raw one. `vectorScanSettings(...)` computes one attempt's settings (Postgres applies them in its search transaction's one settings statement, `postgres-engine/search-settings.ts`); `withVectorSettings(..., iterativeMode, indexWalk)` (PGLite and the fact-relevance read) reads, sets and restores them and sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`); `indexWalk` adds `INDEX_WALK_SETTINGS` and sizes `ef_search` for the over-fetched window. `searchIndexWalk(stmt, limit, run)` runs the statement's index walk before the pool and returns its rows only when its window is full and they fill the limit. Too few pages widen a full window x4 (`INDEX_WALK_ESCALATIONS`); else the pool runs.+- `src/core/search/vector-pool.ts` + `vector-settings.ts` — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness. Pooled attempts scan with `hnsw.max_scan_tuples` = `POOL_MAX_SCAN_TUPLES` (20,000), so a filtered attempt fills its window before acceptance; the walk and scope scan keep a window-sized budget. Settings are restored even inside caller-owned transactions. A batch carries the raw `candidatePool` (a short window means the index ran dry) and an optional `eligiblePool` (fresh candidates); `hasMore` receives the eligible count, else the raw one. `vectorScanSettings(...)` computes one attempt's settings (Postgres sets them in one settings statement, `postgres-engine/search-settings.ts`); `withVectorSettings(...)` (PGLite, fact-relevance) reads, sets and restores them, `hnsw.iterative_scan` in the caller's mode (default `relaxed_order`); `walkOverfetch` adds `INDEX_WALK_SETTINGS` and sizes `ef_search` for the over-fetched window; `joined` (a pool attempt of a statement with an index walk) adds `JOINED_STATEMENT_SETTINGS` (`enable_material = off`): pages are probed per HNSW candidate, never materialized and rescanned. Rows are judged under exact evaluation: a small scope may get an exact plan. `searchIndexWalk(stmt, limit, run)` runs the statement's index walk before the pool and returns its rows only when its window is full and they fill the limit. Too few pages widen a full window x4 (`INDEX_WALK_ESCALATIONS`); else the pool runs.- `src/core/search/vector-statement.ts` — `buildVectorSearchStatement({ dialect, embedding, limit, offset, opts })` builds the vector-search SQL once for both engines, doctor `vector_plan` and the plan-proof E2E: `{ sql, exactSql, hasMoreSql, params, innerLimitIdx, innerLimit, indexed, relaxed, indexWalkSql?, indexWalkOverfetch, scopeScanSql? }`. On an HNSW-indexed `embedding` column (relaxed variant) the candidate CTE carries only the model check; content freshness (`embedded_text_hash = md5(chunk_text)` or NULL) is projected as `hash_current` and filtered in `scored`, because Postgres cannot estimate that expression and drops the index when it sits in the CTE (#5824). Non-indexed columns, the legacy guard, `exactSql` and `hasMoreSql` keep the full guard inside. The pool row reports `candidate_pool` (raw) and `eligible_pool` (fresh). Since/until bounds are spelled per column (`effective_date`, then `updated_at`, then `created_at`) so each arm has column statistics. `indexWalkSql` (relaxed variant without a type or date filter, same parameters) is the statement both engines run first: `ann` orders `content_chunks` alone with the chunk-level filters over twice the window, then pages and sources are joined by key and every page filter, visibility and the private-page rule apply to those rows, keeping the nearest `innerLimit`. Run with `enable_sort = off` (`INDEX_WALK_SETTINGS`) the HNSW scan is its only ordered path; the joined statement's plan sat on a cost knife edge (TOASTed vectors cost a sequential scan too little, the HNSW estimate grows with `ef_search`, the private-page rule's subplans priced every page lookup high) and flipped to a full scan and sort at a 50-row limit or on any remote read. A full walk window selects the same rows as the joined statement (`test/search/vector-index-walk.test.ts`); a short one falls back to it. Source scopes: each engine's `vectorScopeLoader` reads `PAGE_SOURCE_STATS_SQL` (`pages.source_id` planner statistics plus `content_chunks` reltuples) at most once a minute, only for source-scoped searches, and passes `scope` (`share`, and `chunks`). For a scope under `SCOPE_SCAN_MAX_SHARE`, `chunks` comes from `SCOPE_CHUNKS_SQL` (at most once a minute per scope): the scope's live pages times the chunks per page of a `hashint4` stride sample of about 400 of them (every page in a smaller scope), because the page share undercounts sources of long pages; otherwise, and when the count fails, it is the share times chunk reltuples. The walk over-fetches `indexWalkOverfetch(share)` = ceil(2 / share) rows per window slot (2 unscoped or for a whole-brain scope, so that statement is byte-identical), and a share below `INDEX_WALK_MIN_SCOPE_SHARE` (0.04) skips it. `scopeScanSql` (relaxed variant, same parameters) serves a scope under `SCOPE_SCAN_MAX_SHARE` (0.3) of pages with at most `SCOPE_SCAN_MAX_CHUNKS` (120k) counted chunks: an exact distance scan over the scope's chunks, page filters and visibility applied once per page inside `cc.page_id = ANY(ARRAY(...))` so chunks are always reached through `idx_chunks_page` (an inline join flipped to a sequential scan with the private-page rule), ordering only chunk ids with `(distance) + 0` to keep the index out, then the window joins back for its columns. Up to `SCOPE_SCAN_FIRST_MAX_CHUNKS` (25k) it replaces the walk; above that the walk runs first and the scan answers when the walk comes back short (a scope clustered away from the query). It returns the joined statement's rows (`test/search/vector-index-walk.test.ts`); recall across share buckets on 1024-dim vectors is pinned by `test/e2e/vector-scope-recall-postgres.test.ts`. Missing statistics leave only the unscoped walk and the joined statement. PGLite adds the timeline `stale` column; everything else is byte-identical across dialects. Also exports the extension-version probe and the transaction-local `statement_timeout` SQL the Postgres engine runs. Pinned by `test/search/vector-statement.test.ts`, `test/search/vector-freshness.test.ts` and `test/e2e/vector-plan-real-column-postgres.test.ts`.diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 503d8374ab..64a08049ff 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1728,7 +1728,7 @@ export class PGLiteEngine implements BrainEngine {const bound = [...stmt.params];bound[stmt.innerLimitIdx] = requested;return readVectorPool((await tx.query<Record<string, unknown>>(scopeScan && stmt.scopeScanSql || indexWalk && stmt.indexWalkSql || stmt.sql, bound)).rows);- }, undefined, opts?.hnswIterativeScan, indexWalk && stmt.indexWalkSql ? stmt.indexWalkOverfetch : undefined));+ }, undefined, opts?.hnswIterativeScan, indexWalk && stmt.indexWalkSql ? stmt.indexWalkOverfetch : undefined, !!stmt.indexWalkSql && !indexWalk && !(scopeScan && stmt.scopeScanSql)));const rows = await searchIndexWalk(stmt, limit, attempt) ?? await searchVectorPool(limit, stmt.innerLimit, iterative, stmt.indexed, 'pglite',attempt,async pool => {diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 16203b708f..f05b4a2640 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -117,7 +117,7 @@ import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowTimport { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery, collapseWebsearchDashRuns } from './search/sql-ranking.ts';import { narrowedOrFallbackQuery } from './search/keyword-or-narrow.ts';-import { buildKeywordChunkMatch, KEYWORD_RANK_CANDIDATES, KEYWORD_STATEMENT_SETTINGS } from './search/keyword-chunk-match.ts';+import { buildKeywordChunkMatch, KEYWORD_RANK_CANDIDATES, KEYWORD_RANKED_ROWS_CTE, KEYWORD_STATEMENT_SETTINGS } from './search/keyword-chunk-match.ts';import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';@@ -1128,14 +1128,8 @@ export class PostgresEngine implements BrainEngine {const chunk = buildKeywordChunkMatch(ftsLang, opts?.excludePrivate);const rawQuery = `WITH ranked_chunks AS (- SELECT * FROM (SELECT *, count(*) OVER () AS bounded_rows, row_number() OVER (PARTITION BY page_id ORDER BY score DESC, chunk_id ASC) AS page_rank FROM (SELECT- p.slug, p.id as page_id, p.title, p.type, p.source_id,- p.effective_date, p.effective_date_source,- CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL- THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,- CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL- THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,- cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,+ SELECT page_id, chunk_id, score, bounded_rows FROM (SELECT *, count(*) OVER () AS bounded_rows, row_number() OVER (PARTITION BY page_id ORDER BY score DESC, chunk_id ASC) AS page_rank FROM (SELECT+ p.id as page_id, cc.id as chunk_id,ts_rank(cc.search_vector, websearch_to_tsquery('${ftsLang}', $${rankIdx + 1})) * ${sourceFactorCase} AS scoreFROM ${chunk.from}JOIN pages p ON p.id = cc.page_id@@ -1157,7 +1151,8 @@ export class PostgresEngine implements BrainEngine {ORDER BY score DESC, page_id ASC, chunk_id ASCLIMIT ${innerLimitParam}),- ${buildBestPerPagePoolCte('ranked_chunks')}+ ${KEYWORD_RANKED_ROWS_CTE},+ ${buildBestPerPagePoolCte('ranked_rows')}SELECT slug, page_id, title, type, source_id,effective_date, effective_date_source,message_id, thread_id, source_subject,@@ -1487,7 +1482,7 @@ export class PostgresEngine implements BrainEngine {const bound = [...stmt.params];bound[stmt.innerLimitIdx] = exact ? null : innerLimit;return run(tx, (scopeScan && stmt.scopeScanSql) || (walk && stmt.indexWalkSql) || (exact ? stmt.exactSql : stmt.sql), bound as Parameters<typeof tx.unsafe>[1]);- }, { alwaysTransaction: true, jitOff: true, settings: () => vectorScanSettings(iterative, innerLimit, maxScanTuples, deadline, opts?.hnswIterativeScan, walk ? shape.indexWalkOverfetch : undefined) });+ }, { alwaysTransaction: true, jitOff: true, settings: () => vectorScanSettings(iterative, innerLimit, maxScanTuples, deadline, opts?.hnswIterativeScan, walk ? shape.indexWalkOverfetch : undefined, !!shape.indexWalkSql && !walk && !(scopeScan && shape.scopeScanSql) && !exact) });}async getEmbeddingsByChunkIds(ids: number[], column: string = 'embedding'): Promise<Map<number, Float32Array>> {diff --git a/src/core/search/keyword-chunk-match.ts b/src/core/search/keyword-chunk-match.tsindex 8529f60dcc..24392523a4 100644--- a/src/core/search/keyword-chunk-match.ts+++ b/src/core/search/keyword-chunk-match.ts@@ -39,6 +39,39 @@ export const KEYWORD_RANK_CANDIDATES = 50_000;*/export const KEYWORD_STATEMENT_SETTINGS = { work_mem: '32MB' } as const;+/**+ * The display columns of the keyword statement's ranked chunks, joined by key+ * after ranking (`ranked_chunks` carries only page_id, chunk_id, score and+ * bounded_rows). Ranking reads only the score, so the rows and their order are+ * unchanged, except where the KEYWORD_RANK_CANDIDATES bound applies: its+ * sample is the first matches in plan order, and the wider rows used to split+ * the match's hash join into work_mem batches, which reordered it (the rows+ * equal the wide statement's at a work_mem without batches). What changes is+ * that the up to KEYWORD_RANK_CANDIDATES matches no longer carry chunk_text+ * and the frontmatter columns through the per-page window sort and the+ * bounded-row count. With them, a 46k-match OR+ * retry sorted 1.3 KB rows and spilled 57 MB to disk, and the windows+ * buffered the same rows again; now only the at most `innerLimit` ranked+ * chunks are read for display. Each is one primary-key probe whose LIMIT 1+ * keeps the subquery from being pulled up into a join: as a plain join, the+ * planner (estimating a few dozen ranked rows) sorted every page by source and slug for the per-page dedup and filtered+ * the ranked rows against all of them (15M join-filter rows, 2 s).+ */+// chunk-visibility-ok: joins by id only the chunks ranked_chunks selected under the statement's visibility clause+export const KEYWORD_RANKED_ROWS_CTE = `ranked_rows AS (+ SELECT p.slug, rc.page_id, p.title, p.type, p.source_id,+ p.effective_date, p.effective_date_source,+ CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL+ THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,+ CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL+ THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,+ rc.chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, rc.score, rc.bounded_rows+ FROM ranked_chunks rc+ CROSS JOIN LATERAL (SELECT c.chunk_index, c.chunk_text, c.chunk_source FROM content_chunks c WHERE c.id = rc.chunk_id LIMIT 1) cc+ CROSS JOIN LATERAL (SELECT pg.slug, pg.title, pg.type, pg.source_id, pg.effective_date, pg.effective_date_source, pg.frontmatter+ FROM pages pg WHERE pg.id = rc.page_id LIMIT 1) p+ )`;+export function buildKeywordChunkMatch(ftsLang: string, excludePrivate: boolean | undefined): { from: string; match: string; modality: string } {const tsq = `websearch_to_tsquery('${ftsLang}', $1)`;if (!excludePrivate) return { from: 'content_chunks cc', match: `cc.search_vector @@ ${tsq}`, modality: `AND cc.modality = 'text'` };diff --git a/src/core/search/vector-settings.ts b/src/core/search/vector-settings.tsindex 14892f93a3..acbb335757 100644--- a/src/core/search/vector-settings.ts+++ b/src/core/search/vector-settings.ts@@ -1,13 +1,15 @@import { hnswEfSearchFor, HNSW_EF_SEARCH_DEFAULT } from '../vector-index.ts';import { remainingVectorBudget } from './vector-pool.ts';import { HNSW_ITERATIVE_SCAN_DEFAULT, type HnswIterativeScanMode } from './hnsw-iterative-scan.ts';-import { INDEX_WALK_SETTINGS } from './vector-statement.ts';+import { INDEX_WALK_SETTINGS, JOINED_STATEMENT_SETTINGS } from './vector-statement.ts';/*** `walkOverfetch` (the statement's `indexWalkOverfetch`, set only for the* index walk) adds INDEX_WALK_SETTINGS and sizes `hnsw.ef_search` for the* walk's over-fetched window: a non-iterative scan cannot return past it, and* an iterative one past it orders less exactly (recall@50 0.96 against 0.995).+ * `joined` (an attempt that runs the joined statement, `sql`, of a statement+ * with an index walk) adds JOINED_STATEMENT_SETTINGS.*//** What each scan setting reads as when nothing set it (pgvector's defaults; NULL before the extension loads). */@@ -21,9 +23,10 @@ export function vectorScanSettings(deadline?: number,iterativeMode: HnswIterativeScanMode = HNSW_ITERATIVE_SCAN_DEFAULT,walkOverfetch?: number,+ joined = false,): Record<string, string> {const window = walkOverfetch ? candidateLimit * walkOverfetch : candidateLimit;- const settings: Record<string, string> = { 'hnsw.ef_search': String(hnswEfSearchFor(window)), ...(walkOverfetch ? INDEX_WALK_SETTINGS : {}) };+ const settings: Record<string, string> = { 'hnsw.ef_search': String(hnswEfSearchFor(window)), ...(walkOverfetch ? INDEX_WALK_SETTINGS : {}), ...(joined ? JOINED_STATEMENT_SETTINGS : {}) };if (iterative) {settings['hnsw.iterative_scan'] = iterativeMode;settings['hnsw.max_scan_tuples'] = String(maxScanTuples);@@ -47,8 +50,9 @@ export async function withVectorSettings<T>(deadline?: number,iterativeMode: HnswIterativeScanMode = HNSW_ITERATIVE_SCAN_DEFAULT,walkOverfetch?: number,+ joined = false,): Promise<T> {- const settings = vectorScanSettings(iterative, candidateLimit, maxScanTuples, deadline, iterativeMode, walkOverfetch);+ const settings = vectorScanSettings(iterative, candidateLimit, maxScanTuples, deadline, iterativeMode, walkOverfetch, joined);const names = Object.keys(settings);const previous = await query(`SELECT name, current_setting(name, true) AS value FROM unnest($1::text[]) AS settings(name)`, [names]);const setSql = `SELECT set_config(name, value, true) FROM unnest($1::text[], $2::text[]) AS settings(name, value)`;diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.tsindex 7f1efe472a..589b9de18d 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -33,7 +33,8 @@* the HNSW scan is the only ordered path, accept it when its window is full,* widen it when a full window's pages fall short of the limit* (searchIndexWalk), and otherwise run the joined statement as before, whose plans stay with the- * planner for selective filters. A type or date filter skips the walk: it is+ * planner for selective filters, with materialization off+ * (JOINED_STATEMENT_SETTINGS). A type or date filter skips the walk: it is* an explicit narrowing that usually leaves the window short, so the walk* would only add its cost. So does a source scope whose share of pages* (`pages.source_id` planner statistics, `scope.share`) is below@@ -123,6 +124,24 @@ export const INDEX_WALK_OVERFETCH = 2;*/export const INDEX_WALK_SETTINGS: Readonly<Record<string, string>> = { enable_sort: 'off' };+/**+ * Session settings for the ANN attempts of a joined statement (`sql`) that+ * backs an index walk, run when the walk times out or comes back short. The+ * private-page rule's correlated subplans price each page lookup high and its+ * row estimate low, so under the HNSW scan the planner preferred to filter+ * every page once, materialize the survivors and rescan them for each+ * candidate chunk, a join on `p.id = cc.page_id` run as a filter: about+ * 12.7M comparisons and 3 GB of temp reads (the materialized pages pass+ * work_mem) for a 250-row window over 51k pages, 2.2 s warm and 3-4 s under+ * load. With materialization off, the same HNSW scan drives the same filters+ * through a `pages_pkey` probe per candidate (10 ms). Materialize nodes+ * Postgres needs for correctness stay. Statements without a walk (a type or+ * date filter, a small source scope) keep their plans: there the planner may+ * prefer an exact scope-first scan once the materialized join is ruled out,+ * which orders a different, exact window.+ */+export const JOINED_STATEMENT_SETTINGS: Readonly<Record<string, string>> = { enable_material: 'off' };+/** Source scopes holding a smaller share of pages skip the index walk. */export const INDEX_WALK_MIN_SCOPE_SHARE = 0.04;diff --git a/test/e2e/keyword-arm-ranking-postgres.test.ts b/test/e2e/keyword-arm-ranking-postgres.test.tsindex 00d2662727..d33b3b8254 100644--- a/test/e2e/keyword-arm-ranking-postgres.test.ts+++ b/test/e2e/keyword-arm-ranking-postgres.test.ts@@ -10,6 +10,15 @@* run in parallel. (The planner drops the trivial Subquery Scan node from* EXPLAIN, so the proof reads the statement, then checks it plans and returns* rows.)+ *+ * The per-page window carries ids and scores only; display columns are read+ * for the ranked rows (KEYWORD_RANKED_ROWS_CTE). Standard for identical+ * output: rows and order equal the wide statement's whenever the+ * KEYWORD_RANK_CANDIDATES bound does not apply. When it applies, the ranked+ * sample is the first matches in plan order, which on the wide statement+ * already depended on work_mem and row width (its hash join split into+ * batches); there the rows equal the wide statement's at a work_mem that+ * does not spill.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import type { PostgresEngine } from '../../src/core/postgres-engine.ts';@@ -70,6 +79,22 @@ describe('keyword arm plan (postgres)', () => {expect(plan).toContain('content_chunks');});+ test(`\`${query}\`: the per-page window and the bounded-row count carry ids and scores only; display columns are read for the ranked rows`, async () => {+ for (const excludePrivate of [true, false]) {+ const { sql, params, rows } = await capturedKeywordStatement(query, excludePrivate);+ expect(rows).toBeGreaterThan(0);+ type Node = { 'Node Type': string; Output?: string[]; Plans?: Node[] };+ const nodes = (node: Node): Node[] => [node, ...(node.Plans ?? []).flatMap(nodes)];+ const [row] = await engine.executeRaw<{ 'QUERY PLAN': Array<{ Plan: Node }> }>(`EXPLAIN (VERBOSE, FORMAT JSON) ${sql}`, params);+ const windows = nodes(row!['QUERY PLAN'][0]!.Plan).filter(node => node['Node Type'] === 'WindowAgg');+ expect(windows.length).toBeGreaterThan(0);+ const display = /^\w+\.(slug|title|type|source_id|effective_date|effective_date_source|message_id|thread_id|source_subject|chunk_index|chunk_text|chunk_source|frontmatter)$/;+ for (const window of windows) {+ expect([window, ...(window.Plans ?? [])].flatMap(node => node.Output ?? []).filter(column => display.test(column))).toEqual([]);+ }+ }+ });+test(`\`${query}\` without excludePrivate keeps the unfenced join`, async () => {const { sql, rows } = await capturedKeywordStatement(query, false);expect(rows).toBeGreaterThan(0);diff --git a/test/e2e/vector-index-walk-plan-postgres.test.ts b/test/e2e/vector-index-walk-plan-postgres.test.tsindex 68786b28ab..bdba51759f 100644--- a/test/e2e/vector-index-walk-plan-postgres.test.ts+++ b/test/e2e/vector-index-walk-plan-postgres.test.ts@@ -1,12 +1,18 @@/*** #6728 on Postgres: the index walk reaches chunks and pages through one key* probe per ANN row, so no scope-wide chunk-page join is materialized and- * rescanned under the ANN loop. Same fixture and assertions as the PGLite- * plan test in test/search/vector-index-walk.test.ts, in a dedicated- * database so the shared schema keeps its dimensions.+ * rescanned under the ANN loop, and the joined statement behind the walk+ * never rescans a materialized page filter per HNSW candidate. Same fixture+ * and assertions as the PGLite plan tests in+ * test/search/vector-index-walk.test.ts, in a dedicated database so the+ * shared schema keeps its dimensions. The joined statement's rows are judged+ * under exact evaluation: on this small fixture the planner may answer with an+ * exact scope-first scan once the materialized join is ruled out.*/-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import * as vectorPool from '../../src/core/search/vector-pool.ts';+import * as vectorSettings from '../../src/core/search/vector-settings.ts';import { buildVectorSearchStatement, INDEX_WALK_SETTINGS } from '../../src/core/search/vector-statement.ts';import type { SearchOpts } from '../../src/core/types.ts';import { column, planNodes, seedVectorWalkFixture, vec, type PlanNode } from '../helpers/vector-index-walk-fixture.ts';@@ -42,4 +48,41 @@ import { hasDatabase } from './helpers.ts';expect(nodes.some(node => node['Index Name'] === 'idx_chunks_page')).toBe(false);}}, 60_000);++ test('the joined statement behind the walk never materializes the filtered pages and rescans them per HNSW candidate, and returns the same rows', async () => {+ const materializedPages = (nodes: PlanNode[]) => nodes.filter(node => node['Node Type'] === 'Materialize' && planNodes(node).some(inner => inner['Relation Name'] === 'pages')).map(node => node['Node Type']);+ const shape = (rows: Record<string, unknown>[]) => rows.filter(row => row.page_id != null).map(row => [row.slug, row.chunk_id, Number(row.score).toFixed(9)]);+ for (const opts of [{ excludePrivate: true }, { excludePrivate: true, sourceIds: ['default', 'side'] }] as SearchOpts[]) {+ const searchOpts: SearchOpts = { limit: 20, embeddingColumn: column, ...opts };+ const applied: Array<Record<string, string>> = [];+ const original = vectorSettings.vectorScanSettings;+ const walk = spyOn(vectorPool, 'searchIndexWalk').mockResolvedValue(null);+ const settings = spyOn(vectorSettings, 'vectorScanSettings').mockImplementation((...args) => {+ const value = original(...args);+ applied.push(value);+ return value;+ });+ try {+ await engine.searchVector(vec(11), searchOpts);+ } finally {+ walk.mockRestore();+ settings.mockRestore();+ }+ const { statement_timeout: _timeout, ...pool } = applied[0]!;+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding: vec(11), limit: 20, offset: 0, opts: searchOpts });+ expect(stmt.indexWalkSql).toBeDefined();+ const run = (values: Record<string, string>) => engine.transaction(async tx => {+ for (const [name, value] of Object.entries(values)) await tx.executeRaw('SELECT set_config($1, $2, true)', [name, value]);+ const [row] = await tx.executeRaw<{ 'QUERY PLAN': Array<{ Plan: PlanNode }> }>(`EXPLAIN (ANALYZE, FORMAT JSON) ${stmt.sql}`, [...stmt.params]);+ return { nodes: planNodes(row!['QUERY PLAN'][0]!.Plan), rows: await tx.executeRaw<Record<string, unknown>>(stmt.sql, [...stmt.params]) };+ });+ const joined = await run(pool);+ expect(materializedPages(joined.nodes)).toEqual([]);+ expect(joined.nodes.flatMap(node => node['Join Filter']?.includes('page_id') ? [node['Join Filter']] : [])).toEqual([]);+ const materialized = await run({ ...pool, enable_material: 'on' });+ expect(materializedPages(materialized.nodes)).not.toEqual([]);+ expect(shape(joined.rows)).toHaveLength(20);+ expect(shape(joined.rows)).toEqual(shape(materialized.rows));+ }+ }, 60_000);});diff --git a/test/search/vector-index-walk.test.ts b/test/search/vector-index-walk.test.tsindex ed5c0372da..0d7808cee6 100644--- a/test/search/vector-index-walk.test.ts+++ b/test/search/vector-index-walk.test.ts@@ -12,10 +12,19 @@* the comparison is row-for-row, order included. The scope scan* (`scopeScanSql`) is held to the same row-for-row bar. The Postgres* plan proof is test/e2e/vector-plan-real-column-postgres.test.ts.+ *+ * The joined statement behind the walk runs with JOINED_STATEMENT_SETTINGS+ * (materialization off). Its result set is judged under exact evaluation,+ * like every statement here: ruling out the materialized page join can move+ * the planner from the HNSW scan to an exact scope-first scan on a small+ * scope or brain (this fixture is one), which returns the exact window rather+ * than the HNSW approximation. That is accepted; on large brains the same+ * HNSW scan stays and only the page join changes.*/import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import * as vectorPool from '../../src/core/search/vector-pool.ts';+import * as vectorSettings from '../../src/core/search/vector-settings.ts';import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, INDEX_WALK_SETTINGS, PAGE_SOURCE_STATS_SQL, sourceScope, sourceScopeShare, type PageSourceStats } from '../../src/core/search/vector-statement.ts';import type { SearchOpts } from '../../src/core/types.ts';import { column, planNodes, seedVectorWalkFixture, vec, type PlanNode } from '../helpers/vector-index-walk-fixture.ts';@@ -102,6 +111,58 @@ describe('vector index walk (PGLite)', () => {}});+ /** The scan settings searchVector applies to its first pool attempt, the joined statement's. */+ async function poolAttemptSettings(opts: SearchOpts): Promise<Record<string, string>> {+ const applied: Array<Record<string, string>> = [];+ const walk = spyOn(vectorPool, 'searchIndexWalk').mockResolvedValue(null);+ const settings = spyOn(vectorSettings, 'withVectorSettings').mockImplementation(async (_query, iterative, limit, maxScanTuples, run, deadline, mode, walkOverfetch, joined) => {+ applied.push(vectorSettings.vectorScanSettings(iterative, limit, maxScanTuples, deadline, mode, walkOverfetch, joined));+ return run();+ });+ try {+ await engine.searchVector(vec(5), opts);+ } finally {+ walk.mockRestore();+ settings.mockRestore();+ }+ return applied[0]!;+ }++ /** Plan and rows of `sql` under `settings`. */+ async function planAndRows(sql: string, params: unknown[], settings: Record<string, string>) {+ for (const [name, value] of Object.entries(settings)) await engine.executeRaw('SELECT set_config($1, $2, false)', [name, value]);+ try {+ const [row] = await engine.executeRaw<{ 'QUERY PLAN': Array<{ Plan: PlanNode }> }>(`EXPLAIN (ANALYZE, FORMAT JSON) ${sql}`, params);+ return { nodes: planNodes(row['QUERY PLAN'][0].Plan), rows: await engine.executeRaw<Record<string, unknown>>(sql, params) };+ } finally {+ for (const name of Object.keys(settings)) await engine.executeRaw(`RESET ${name}`);+ }+ }++ const materializedPages = (nodes: PlanNode[]) => nodes.filter(node => node['Node Type'] === 'Materialize' && planNodes(node).some(inner => inner['Relation Name'] === 'pages')).map(node => node['Node Type']);++ test('the joined statement never materializes the filtered pages and rescans them per HNSW candidate, and returns the same rows', async () => {+ // The private-page rule's subplans drew the planner to filter every page+ // once and rescan the materialized survivors for each candidate chunk+ // (2.2 s per attempt on a 51k-page brain, where the pool attempt now+ // probes pages_pkey per HNSW candidate). The rows stay the same.+ for (const opts of [{ excludePrivate: true }, { excludePrivate: true, sourceIds: ['default', 'side'] }] as SearchOpts[]) {+ for (const seed of [11, 202]) {+ const searchOpts: SearchOpts = { limit: 20, embeddingColumn: column, ...opts };+ const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(seed), limit: 20, offset: 0, opts: searchOpts });+ const params = [...stmt.params];+ const settings = await poolAttemptSettings(searchOpts);+ const { nodes, rows } = await planAndRows(stmt.sql, params, settings);+ expect(materializedPages(nodes)).toEqual([]);+ expect(nodes.flatMap(node => node['Join Filter']?.includes('page_id') ? [node['Join Filter']] : [])).toEqual([]);+ const materialized = await planAndRows(stmt.sql, params, { ...settings, enable_material: 'on' });+ expect(materializedPages(materialized.nodes)).not.toEqual([]);+ expect(shape(rows)).toHaveLength(20);+ expect(shape(rows)).toEqual(shape(materialized.rows));+ }+ }+ });+test('the walk keeps every page filter: no hidden, deleted, archived or out-of-scope page reaches results', async () => {const hits = await engine.searchVector(vec(42), { limit: 50, embeddingColumn: column, excludePrivate: true, sourceIds: ['default', 'side'] });expect(hits).toHaveLength(50);