Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): pass the scope estimate as one input; vector-scope-share bench; docs and behavior notice
time-attackf0a1d9c9993f
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 434fd651cc..3c69b3c99c 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -22,9 +22,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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. 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. `withVectorSettings(..., iterativeMode, indexWalk)` 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; otherwise (or past its 2 s budget) both engines run the pool unchanged.+- `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. 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. `withVectorSettings(..., iterativeMode, walkOverfetch)` sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`); `walkOverfetch` (the statement's `indexWalkOverfetch`, index walk only) adds `INDEX_WALK_SETTINGS` and sizes `ef_search` for the over-fetched window. `searchIndexWalk(stmt, limit, run)` runs the statement's index walk, then its scope scan (each when present), before the pool: walk rows answer when its window is full and they fill the limit, scope-scan rows when they fill the limit or the scope ran out of eligible chunks; otherwise (or past an attempt's 2 s budget) both engines run the pool unchanged. The walk's `hnsw.max_scan_tuples` covers its whole over-fetched window.-- `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? }`. 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. A source scope whose share of pages (`pages.source_id` planner statistics, `PAGE_SOURCE_STATS_SQL`, read by each engine's `vectorScopeShareLoader` at most once a minute) is below `INDEX_WALK_MIN_SCOPE_SHARE` (0.1) skips the walk like a type or date filter, because the nearest chunks overall never fill its window; the input `scopeShare` only removes `indexWalkSql`, every other statement stays byte-identical, and missing statistics leave the walk on. 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`.+- `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 `scopeShare` and `scopeChunks` (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.5) of pages with at most `SCOPE_SCAN_MAX_CHUNKS` (60k) estimated 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`.- `src/core/search/vector-legacy-guard.ts` — one-release rollback for the #5824 statement change. `readVectorLegacyGuard(cfg, env)` reports the setting (`GBRAIN_VECTOR_LEGACY_GUARD` wins over `search.vector_legacy_guard`); `resolveVectorLegacyGuard(cfg)` latches it once per process for `hybrid/request.ts`, which passes `SearchOpts.vectorLegacyGuard` to the engines (they never read config), and prints `[gbrain] vector legacy guard active` to stderr once when on. A changed setting takes effect when the owning service restarts.diff --git a/docs/designs/refactor-wave-1/w1-inventory.md b/docs/designs/refactor-wave-1/w1-inventory.mdindex 3ef0a450bb..96e5f41251 100644--- a/docs/designs/refactor-wave-1/w1-inventory.md+++ b/docs/designs/refactor-wave-1/w1-inventory.md@@ -264,6 +264,6 @@ occurrence-renumbered text hash is identical.| `listStaleChunks` | identical-after-normalization | PGLite reused `$1` for the three `afterUpdatedAt` comparisons; Postgres binds each occurrence. Scoped: `ScopedRead`. || `countChunklessPagesWithContent`, `listChunklessPagesWithContent` | identical | Shared `buildChunklessPagesWhere` becomes a fragment builder. Scoped: `ScopedRead`; Postgres ran `tx.unsafe`: stays `unsafe`. || `deleteChunks` | identical-after-normalization | Placeholder numbering only. |-| `getEmbeddingsByChunkIds` | identical SQL, different driver post-processing | Same statement (raw on both); both drivers return the vector as its text literal. PGLite decoded it with `JSON.parse` (throwing on a malformed row), Postgres with `tryParseEmbedding` (skip and warn once). Unified on Postgres's contract through `decodeEmbedding`: `JSON.parse` when the text is an all-finite numeric array (JSON's number grammar is a subset of `Number()`'s with equal values, so the vector is identical), otherwise `tryParseEmbedding`. The column is a pgvector `vector`/`halfvec`, which rejects NaN/Infinity on input and always emits a well-formed literal, so the two engines' malformed-row branches are unreachable here and results are identical on both. Keeps PGLite's decode speed on the hybrid rescoring path (a first cut on plain `tryParseEmbedding` cost PGLite `hybridSearchCached` about +7%). Pinned by `test/engine-sql-chunks.test.ts`. Unscoped: `LegacyUnscopedRead`. |+| `getEmbeddingsByChunkIds` | identical SQL, different driver post-processing | Same statement (raw on both); both drivers return the vector as its text literal. PGLite decoded it with `JSON.parse` (throwing on a malformed row), Postgres with `tryParseEmbedding` (skip and warn once). Unified on Postgres's contract through `decodeEmbedding`: `JSON.parse` when the text is an all-finite numeric array (JSON's number grammar is a subset of `Number()`'s with equal values, so the vector is identical), otherwise `tryParseEmbedding`. The column is a pgvector `vector`/`halfvec`, which rejects NaN/Infinity on input and always emits a well-formed literal, so the two engines' malformed-row branches are unreachable here and results are identical on both. Keeps PGLite's decode speed on the hybrid rescoring path (a first cut on plain `tryParseEmbedding` cost PGLite `hybridSearchCached` about +7%). Since v0.60.131.0 both read `vector_send(col::vector)` and decode it with `decodeVectorSend` (same float4 values, about 2x faster at 100 ids: no vector_out text, smaller wire, no parse). Pinned by `test/engine-sql-chunks.test.ts`. Unscoped: `LegacyUnscopedRead`. || `getChunksWithEmbeddings` | identical-after-normalization | Placeholder numbering only; shared `rowToChunk(r, true)`. Unscoped: `LegacyUnscopedRead`. || Stays in the engines: `activeEmbeddingColId` (also serves `getStats` / `getHealth`, out of scope), `upsertChunks`'s retry/transaction wrapper, `lockPageKeys` / `readPageSnapshot` (pages domain). No chunks, files or sources method is dialect-specific. | | |diff --git a/scripts/bench/vector-scope-share.ts b/scripts/bench/vector-scope-share.tsnew file mode 100644index 0000000000..7a93648abc--- /dev/null+++ b/scripts/bench/vector-scope-share.ts@@ -0,0 +1,85 @@+#!/usr/bin/env bun+/**+ * Vector search latency and recall per source scope, against an existing+ * brain. Opt-in, never run in CI, not shipped in the CLI; reads only.+ *+ * bun scripts/bench/vector-scope-share.ts <postgres-url | pglite-dir> <scope>... \+ * [--queries 25] [--limit 20] [--remote] [--window] [--json]+ *+ * A scope is a source id, several joined with `+`, or `all` (unscoped). Query+ * vectors are stored chunk embeddings plus fixed noise (the same chunks every+ * run, by md5 of the chunk id), so two builds compare on identical queries.+ * Each scope runs one warm-up search, then every query through the engine's+ * `searchVector`, and reports p50/p95 latency (nearest rank), the mean result+ * count, recall of result pages against the exact statement (`exactSql`, no+ * index; `--window` bounds it to the candidate window instead of every+ * candidate), the share of pages the scope holds per planner statistics, and+ * underfilled exits. `--remote` adds the private-page rule (`excludePrivate`).+ */+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, sourceScope, type PageSourceStats } from '../../src/core/search/vector-statement.ts';+import type { SearchOpts } from '../../src/core/types.ts';++const args = process.argv.slice(2);+const flag = (name: string) => args.includes(`--${name}`);+const option = (name: string, fallback: number) => {+ const at = args.indexOf(`--${name}`);+ return at >= 0 ? Number(args[at + 1]) : fallback;+};+const positional = args.filter((arg, i) => !arg.startsWith('--') && !['--queries', '--limit'].includes(args[i - 1] ?? ''));+const [target, ...scopes] = positional;+if (!target || scopes.length === 0) {+ console.error('usage: bun scripts/bench/vector-scope-share.ts <postgres-url | pglite-dir> <scope>... [--queries N] [--limit N] [--remote] [--window] [--json]');+ process.exit(2);+}+const queries = option('queries', 25);+const limit = option('limit', 20);+const pglite = !/^postgres(ql)?:\/\//.test(target);+const engine = pglite ? new PGLiteEngine() : new PostgresEngine();+await engine.connect(pglite ? { engine: 'pglite', database_path: target } : { engine: 'postgres', database_url: target });++const vectors: Float32Array[] = [];+let seed = 1;+const noise = () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648 - 0.5;+for (const { v } of await engine.executeRaw<{ v: string }>(`SELECT embedding::text AS v FROM content_chunks WHERE embedding IS NOT NULL ORDER BY md5(id::text) LIMIT ${queries}`)) {+ vectors.push(Float32Array.from(JSON.parse(v) as number[], x => x + noise() * 0.8));+}+const [stats] = await engine.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL);+const percentile = (values: number[], p: number) => {+ const sorted = [...values].sort((a, b) => a - b);+ return +sorted[Math.min(sorted.length - 1, Math.ceil(p * sorted.length) - 1)]!.toFixed(1);+};++const rows = [];+for (const scope of scopes) {+ const opts: SearchOpts = { limit, ...(flag('remote') ? { excludePrivate: true } : {}), ...(scope === 'all' ? {} : { sourceIds: scope.split('+') }) };+ let underfilled = 0;+ await engine.searchVector(vectors[0]!, opts);+ const ms: number[] = [];+ const results: number[][] = [];+ for (const vector of vectors) {+ const start = performance.now();+ const hits = await engine.searchVector(vector, { ...opts, onVectorPoolMeta: () => { underfilled++; } });+ ms.push(performance.now() - start);+ results.push(hits.map(hit => hit.page_id));+ }+ let hit = 0, total = 0;+ for (const [k, vector] of vectors.entries()) {+ const stmt = buildVectorSearchStatement({ dialect: pglite ? 'pglite' : 'postgres', embedding: vector, limit, offset: 0, opts });+ const bound = [...stmt.params];+ bound[stmt.innerLimitIdx] = flag('window') ? stmt.innerLimit : null;+ const truth = new Set((await engine.executeRaw<{ page_id: number | null }>(stmt.exactSql, bound)).filter(row => row.page_id != null).map(row => Number(row.page_id)));+ total += truth.size;+ hit += results[k]!.filter(id => truth.has(id)).length;+ }+ rows.push({+ scope, share: scope === 'all' ? 1 : +(sourceScope(stats, opts)?.share ?? NaN).toFixed(4), n: ms.length,+ p50_ms: percentile(ms, 0.5), p95_ms: percentile(ms, 0.95),+ results: +(results.reduce((sum, r) => sum + r.length, 0) / results.length).toFixed(1),+ recall: +(hit / Math.max(1, total)).toFixed(3), underfilled,+ });+}+await engine.disconnect();+if (flag('json')) console.log(JSON.stringify(rows));+else console.table(rows);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 12d33f36c2..acd25034b5 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -350,6 +350,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Budgeted delivery PR 1. `since` equals the branch's VERSION; the integrator sets it to the merge-slot stamp by hand (release:restamp does not rewrite this table).{ since: '0.60.124.0', text: 'A token budget passed under `auto` evidence delivery (`token_budget` on query, search and assemble_evidence, `budget_tokens` on recall with `return_unit: "auto"`) is now a hard cap on the delivered titles and evidence: the best hit comes first, and conversations or notes that do not fit are listed in `delivery.dropped_reasons` instead of being appended as extra chunks. A budget below 32 tokens is refused with `invalid_params`. Calls without a budget, and a bare query `token_budget` (legacy chunk budgeting), are unchanged. `gbrain config set search.auto_packing off` restores the uncapped behavior.' },{ since: '0.60.126.0', text: '`context_pack` cards now list the newest pages that mention each entity and are dated after the entity\'s own page (up to 8 per card, 2,000 characters per card and 6,000 per pack, each with its date, slug, title and preview), so a later mail or note that corrects the page reaches the agent on its first call. A remote caller never sees a private page or another source there, and the section packs last under `budget_tokens`. `gbrain config set mentions.newer_on_cards false` turns it off.' },+ { since: '0.60.131.0', text: 'Vector search scoped to a source that holds a small part of the brain now returns its true nearest chunks: a source with up to about 25,000 chunks is scanned exactly instead of through the HNSW index, and a larger one falls back to that scan when the index comes back short. Unscoped search is unchanged; scoped results can differ from earlier releases where the index had missed closer matches.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 3ed854734c..3c6f918dc2 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1682,8 +1682,7 @@ export class PGLiteEngine implements BrainEngine {}// Same statement as postgres-engine (search/vector-statement.ts); the// PGLite dialect adds the timeline `stale` flag and has no exact fallback.- const scope = await this.vectorScope(opts);- const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding, limit, offset: opts?.offset || 0, opts, scopeShare: scope?.share, scopeChunks: scope?.chunks });+ const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding, limit, offset: opts?.offset || 0, opts, scope: await this.vectorScope(opts) });this.vectorIterativeScan ??= this.executeRaw<{ extversion: string }>(VECTOR_EXTENSION_VERSION_SQL).then(rows => supportsHnswIterativeScan(rows[0]?.extversion));const probe = this.vectorIterativeScan;diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 00de9a9d30..fa1df50ee4 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -1322,8 +1322,7 @@ export class PostgresEngine implements BrainEngine {// so the HNSW index stays usable; the outer stages re-rank by source// factor. Statement shape, freshness placement (#5824) and pool counts// live in search/vector-statement.ts, shared with PGLite and doctor.- const scope = await this.vectorScope(opts);- const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scopeShare: scope?.share, scopeChunks: scope?.chunks });+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scope: await this.vectorScope(opts) });const iterative = await this.vectorIterativeScanSupported();const walked = await searchIndexWalk(stmt, limit, async walk => readVectorPool(await this.runVectorAttempt(stmt, walk, iterative, opts, (tx, sql, bound) => tx.unsafe(sql, bound))));if (walked) return walked.map(rowToSearchResult);@@ -1355,8 +1354,7 @@ export class PostgresEngine implements BrainEngine {*/async explainVectorSearch(embedding: Float32Array, opts?: SearchOpts): Promise<Record<string, unknown>> {const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());- const scope = await this.vectorScope(opts);- const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scopeShare: scope?.share, scopeChunks: scope?.chunks });+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scope: await this.vectorScope(opts) });const iterative = await this.vectorIterativeScanSupported();const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: Math.max(2_000, stmt.innerLimit * stmt.indexWalkOverfetch), remainingMs: 8_000, exact: false, indexWalk: !!stmt.indexWalkSql, scopeScan: !stmt.indexWalkSql && !!stmt.scopeScanSql };const [row] = await this.runVectorAttempt(stmt, attempt, iterative, opts, (tx, sql, bound) => tx.unsafe(`EXPLAIN (FORMAT JSON) ${sql}`, bound));@@ -1385,12 +1383,11 @@ export class PostgresEngine implements BrainEngine {const deadline = performance.now() + remainingMs;return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async tx => {const walk = indexWalk && stmt.indexWalkSql;- const first = (scopeScan && stmt.scopeScanSql) || walk;return withVectorSettings((sql, values) => tx.unsafe(sql, values as Parameters<typeof tx.unsafe>[1]), iterative, innerLimit, maxScanTuples, async () => {const bound = [...stmt.params];bound[stmt.innerLimitIdx] = exact ? null : innerLimit;await tx.unsafe(SET_STATEMENT_TIMEOUT_SQL, [String(remainingVectorBudget(deadline))]);- return run(tx, first || (exact ? stmt.exactSql : stmt.sql), bound as Parameters<typeof tx.unsafe>[1]);+ return run(tx, (scopeScan && stmt.scopeScanSql) || walk || (exact ? stmt.exactSql : stmt.sql), bound as Parameters<typeof tx.unsafe>[1]);}, deadline, opts?.hnswIterativeScan, walk ? stmt.indexWalkOverfetch : undefined);}, { alwaysTransaction: true, jitOff: true });}diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.tsindex 52fa550154..6df38012fb 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -35,12 +35,12 @@* planner for selective filters. 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, `scopeShare`) is below+ * (`pages.source_id` planner statistics, `scope.share`) is below* INDEX_WALK_MIN_SCOPE_SHARE: the nearest chunks overall rarely fill its* window.** `scopeScanSql` serves a source scope under SCOPE_SCAN_MAX_SHARE of pages- * whose estimated chunk count (`scopeChunks`, the share times+ * whose estimated chunk count (`scope.chunks`, the share times* `content_chunks` reltuples) is at most SCOPE_SCAN_MAX_CHUNKS: an exact* distance scan over the scope's chunks with every filter applied, ordering* only chunk ids (`+ 0` keeps the index out), then the window joins back for@@ -73,10 +73,12 @@ export interface VectorSearchStatementInput {limit: number;offset: number;opts?: SearchOpts;- /** Estimated share of pages the source scope holds (`vectorScopeLoader`); below INDEX_WALK_MIN_SCOPE_SHARE the walk is omitted. */- scopeShare?: number;- /** Estimated chunks in the source scope (`vectorScopeLoader`); at most SCOPE_SCAN_MAX_CHUNKS adds the scope scan. */- scopeChunks?: number;+ /**+ * Estimated share of pages and chunks the source scope holds+ * (`vectorScopeLoader`): below INDEX_WALK_MIN_SCOPE_SHARE the walk is+ * omitted; at most SCOPE_SCAN_MAX_CHUNKS adds the scope scan.+ */+ scope?: VectorScope;}export interface VectorSearchStatement {@@ -229,12 +231,12 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): V// A type or date filter, or a source scope with a small share of pages, is// the caller narrowing the search; the walk would usually come back short,// so those keep the joined statement alone.+ const share = input.scope?.share, chunks = input.scope?.chunks;const narrowed = !!(opts?.type || opts?.types?.length || opts?.afterDate || opts?.beforeDate)- || (input.scopeShare !== undefined && input.scopeShare < INDEX_WALK_MIN_SCOPE_SHARE);- const scopeScan = relaxed && input.scopeShare !== undefined && input.scopeShare < SCOPE_SCAN_MAX_SHARE- && input.scopeChunks !== undefined && input.scopeChunks <= SCOPE_SCAN_MAX_CHUNKS;- const walk = relaxed && !narrowed && !(scopeScan && input.scopeChunks! <= SCOPE_SCAN_FIRST_MAX_CHUNKS);- const overfetch = indexWalkOverfetch(input.scopeShare);+ || (share !== undefined && share < INDEX_WALK_MIN_SCOPE_SHARE);+ const scopeScan = relaxed && share !== undefined && share < SCOPE_SCAN_MAX_SHARE && chunks !== undefined && chunks <= SCOPE_SCAN_MAX_CHUNKS;+ const walk = relaxed && !narrowed && !(scopeScan && chunks! <= SCOPE_SCAN_FIRST_MAX_CHUNKS);+ const overfetch = indexWalkOverfetch(share);const preMigration = modelParam ? `(${modelParam}::text IS NULL AND NOT EXISTS(SELECT 1 FROM config WHERE key='embedding_migration.state'))` : '';const hashCurrent = `(cc.embedded_text_hash=md5(cc.chunk_text) OR cc.embedded_text_hash IS NULL)`;const guardedGeneration = modelParam ? `AND ((cc.model=${modelParam} AND ${hashCurrent})diff --git a/test/e2e/vector-plan-real-column-postgres.test.ts b/test/e2e/vector-plan-real-column-postgres.test.tsindex 47ecd43ffa..72ea9258a6 100644--- a/test/e2e/vector-plan-real-column-postgres.test.ts+++ b/test/e2e/vector-plan-real-column-postgres.test.ts@@ -390,7 +390,7 @@ function axis(d: number): Float32Array {const scope = sourceScope(stats, opts)!;expect(scope.share).toBeLessThan(INDEX_WALK_MIN_SCOPE_SHARE);expect(scope.chunks!).toBeLessThanOrEqual(SCOPE_SCAN_FIRST_MAX_CHUNKS);- const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding: query, limit: 10, offset: 0, opts, scopeShare: scope.share, scopeChunks: scope.chunks });+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding: query, limit: 10, offset: 0, opts, scope });expect(stmt.indexWalkSql).toBeUndefined();expect(stmt.scopeScanSql).toBeDefined();diff --git a/test/search/vector-index-walk.test.ts b/test/search/vector-index-walk.test.tsindex 08f18a1b43..c76a4e198e 100644--- a/test/search/vector-index-walk.test.ts+++ b/test/search/vector-index-walk.test.ts@@ -151,7 +151,7 @@ describe('vector index walk (PGLite)', () => {const share = sourceScopeShare(stats, opts)!;expect(share).toBeGreaterThan(0);expect(share).toBeLessThan(INDEX_WALK_MIN_SCOPE_SHARE);- const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(7), limit: 10, offset: 0, opts, scopeShare: share });+ const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(7), limit: 10, offset: 0, opts, scope: { share } });expect(stmt.indexWalkSql).toBeUndefined();const unscoped = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(7), limit: 10, offset: 0, opts });expect(stmt.sql).toBe(unscoped.sql);@@ -168,7 +168,7 @@ describe('vector index walk (PGLite)', () => {expect(sourceScopeShare(stats, opts)!).toBeGreaterThanOrEqual(INDEX_WALK_MIN_SCOPE_SHARE);const scope = sourceScope(stats, opts)!;const { hits, seen } = await statementsSearched(opts);- expect(seen).toEqual([buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(7), limit: 20, offset: 0, opts, scopeShare: scope.share, scopeChunks: scope.chunks }).indexWalkSql!]);+ expect(seen).toEqual([buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(7), limit: 20, offset: 0, opts, scope }).indexWalkSql!]);expect(hits).toHaveLength(20);});@@ -184,7 +184,7 @@ describe('vector index walk (PGLite)', () => {for (const [label, opts] of scanMatrix) {test(`${label}: the scope scan returns the joined statement's rows in the same order`, async () => {for (const seed of [11, 202, 3003]) {- const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(seed), limit: opts.limit ?? 20, offset: opts.offset ?? 0, opts: { embeddingColumn: column, ...opts }, scopeShare: 0.2, scopeChunks: 500 });+ const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(seed), limit: opts.limit ?? 20, offset: opts.offset ?? 0, opts: { embeddingColumn: column, ...opts }, scope: { share: 0.2, chunks: 500 } });expect(stmt.scopeScanSql).toBeDefined();const params = [...stmt.params];expect(shape(await exactRows(stmt.scopeScanSql!, params))).toEqual(shape(await exactRows(stmt.sql, params)));@@ -196,7 +196,7 @@ describe('vector index walk (PGLite)', () => {const opts: SearchOpts = { limit: 10, embeddingColumn: column, sourceId: 'side', excludePrivate: true };const [stats] = await engine.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL);const scope = sourceScope(stats, opts)!;- const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(7), limit: 10, offset: 0, opts, scopeShare: scope.share, scopeChunks: scope.chunks });+ const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(7), limit: 10, offset: 0, opts, scope });expect(stmt.scopeScanSql).toBeDefined();expect(stmt.indexWalkSql).toBeUndefined();const kinds: string[] = [];diff --git a/test/search/vector-statement.test.ts b/test/search/vector-statement.test.tsindex 97208890e5..19f159bf55 100644--- a/test/search/vector-statement.test.ts+++ b/test/search/vector-statement.test.ts@@ -16,7 +16,7 @@ const indexedColumn = { name: 'embedding', type: 'vector' as const, dimensions:const wideColumn = { name: 'embedding', type: 'vector' as const, dimensions: 3072, embeddingModel: 'openai:text-embedding-3-large' };function build(overrides: Partial<VectorSearchStatementInput['opts']> = {}, dialect: 'postgres' | 'pglite' = 'postgres', scopeShare?: number, scopeChunks?: number) {- return buildVectorSearchStatement({ dialect, embedding: new Float32Array([1, 0, 0]), limit: 10, offset: 0, opts: { embeddingColumn: indexedColumn, ...overrides }, scopeShare, scopeChunks });+ return buildVectorSearchStatement({ dialect, embedding: new Float32Array([1, 0, 0]), limit: 10, offset: 0, opts: { embeddingColumn: indexedColumn, ...overrides }, scope: scopeShare === undefined ? undefined : { share: scopeShare, chunks: scopeChunks } });}/** The WHERE of the `hnsw_candidates` CTE, between its FROM and its ORDER BY. */