Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): exact scope scan for small source scopes, share-scaled index walk, binary embedding fetch
time-attacke14eb5b02b69
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 5bbded8c57..1e4406476c 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -21,7 +21,7 @@ import type { PageKey, PageSnapshot, PageSnapshotOptions } from '../page-state/timport { assertPageRevision } from '../page-state/types.ts';import type { BrainEngine } from '../engine.ts';import type { Chunk, ChunkInput, ChunklessPageRow, ResolvedColumn, StaleChunkRow } from '../types.ts';-import { rowToChunk, tryParseEmbedding, validateSlug } from '../utils.ts';+import { rowToChunk, validateSlug } from '../utils.ts';import { sanitizeText } from '../batch-rows.ts';import {normalizeEngineColumn,@@ -665,26 +665,21 @@ export async function deleteChunks(exec: SqlExecutor, slug: string, opts?: { sou}/**- * `tryParseEmbedding`'s result for every input, with a native fast path for- * well-formed pgvector text. Both drivers return the vector as its text- * literal; PGLite master decoded it with `JSON.parse`, Postgres master with- * `tryParseEmbedding` (split + `Number`, about twice as slow per 1024-d row on- * the hybrid rescoring path). JSON's number grammar is a subset of- * `Number()`'s with the same values, so an all-finite numeric array decodes- * identically; anything else (malformed, non-finite, not an array) takes- * `tryParseEmbedding` and keeps its skip-and-warn contract.- * `test/engine-sql-chunks.test.ts` pins the equivalence.+ * Decodes pgvector's binary send format (`vector_send`): int16 dimensions,+ * int16 unused, then big-endian float4 values. Both drivers return the bytea+ * as a Uint8Array (postgres.js a Buffer). The float4 values are the stored+ * ones, bit for bit the Float32Array the text literal parses to+ * (`test/engine-sql-chunks.test.ts` pins it on a real engine); a malformed+ * value decodes to null and the row is skipped.*/-export function decodeEmbedding(value: unknown): Float32Array | null {- if (typeof value === 'string') {- try {- const parsed: unknown = JSON.parse(value);- if (Array.isArray(parsed) && parsed.every((n) => typeof n === 'number' && Number.isFinite(n))) return Float32Array.from(parsed as number[]);- } catch {- // Not JSON: tryParseEmbedding decides (corrupt rows skip with one warning).- }- }- return tryParseEmbedding(value);+export function decodeVectorSend(value: unknown): Float32Array | null {+ if (!(value instanceof Uint8Array) || value.byteLength < 4) return null;+ const view = new DataView(value.buffer, value.byteOffset, value.byteLength);+ const dimensions = view.getInt16(0);+ if (value.byteLength !== 4 + 4 * dimensions) return null;+ const embedding = new Float32Array(dimensions);+ for (let i = 0; i < dimensions; i++) embedding[i] = view.getFloat32(4 + 4 * i);+ return embedding;}export async function getEmbeddingsByChunkIds(exec: LegacyUnscopedRead, ids: number[], column: string): Promise<Map<number, Float32Array>> {@@ -698,15 +693,18 @@ export async function getEmbeddingsByChunkIds(exec: LegacyUnscopedRead, ids: numif (!COLUMN_NAME_REGEX.test(column)) {throw new EmbeddingColumnNotRegisteredError(column, []);}+ // Binary transfer (`vector_send`, halfvec cast exactly to vector): the+ // text literal cost about 3x more in vector_out formatting, wire bytes and+ // parsing than the TOAST read itself, for the same float4 values.const quotedCol = trustedSql(quoteIdentifier(column));const { text, params } = renderFragment(sqlFragment`- SELECT cc.id, cc.${quotedCol} AS embedding FROM content_chunks cc JOIN pages p ON p.id=cc.page_id+ SELECT cc.id, vector_send(cc.${quotedCol}::vector) AS embedding FROM content_chunks cc JOIN pages p ON p.id=cc.page_idWHERE cc.id = ANY(${ids}::int[]) AND cc.${quotedCol} IS NOT NULL AND ${trustedSql(currentTextProjectionFilter('p'))}`);const { rows } = await exec.unsafe(text, params);const result = new Map<number, Float32Array>();for (const row of rows) {- const embedding = decodeEmbedding(row.embedding);+ const embedding = decodeVectorSend(row.embedding);if (embedding) result.set(row.id as number, embedding);}return result;diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex d136881923..58ba0aa30c 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -74,7 +74,7 @@ import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchimport { supportsHnswIterativeScan } from './vector-index.ts';import { searchIndexWalk, searchVectorPool, readVectorPool, type VectorPoolAttempt } from './search/vector-pool.ts';import { beforePlannerRead, plannerRead } from './planner-stats.ts';-import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeShareLoader, type PageSourceStats } from './search/vector-statement.ts';+import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeLoader, type PageSourceStats } from './search/vector-statement.ts';import { withVectorSettings } from './search/vector-settings.ts';import { PGLITE_SCHEMA_SQL, getPGLiteSchema } from './pglite-schema.ts';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';@@ -705,7 +705,7 @@ export async function probePgliteScratchStore(export class PGLiteEngine implements BrainEngine {private vectorIterativeScan?: Promise<boolean>;- private readonly vectorScopeShare = vectorScopeShareLoader(() => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL));+ private readonly vectorScope = vectorScopeLoader(() => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL));/** Transaction clones keep chunk invalidation and replacement atomic. */private _chunkWritesInTransaction = false;private _checkpointGuard: PgliteCheckpointGuard | undefined;@@ -1682,7 +1682,8 @@ 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 stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding, limit, offset: opts?.offset || 0, opts, scopeShare: await this.vectorScopeShare(opts) });+ const scope = await this.vectorScope(opts);+ const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding, limit, offset: opts?.offset || 0, opts, scopeShare: scope?.share, scopeChunks: scope?.chunks });this.vectorIterativeScan ??= this.executeRaw<{ extversion: string }>(VECTOR_EXTENSION_VERSION_SQL).then(rows => supportsHnswIterativeScan(rows[0]?.extversion));const probe = this.vectorIterativeScan;@@ -1692,12 +1693,12 @@ export class PGLiteEngine implements BrainEngine {if (this.vectorIterativeScan === probe) this.vectorIterativeScan = undefined;throw error;}- const attempt = ({ innerLimit: requested, maxScanTuples, indexWalk }: VectorPoolAttempt) => this.db.transaction(async tx => withVectorSettings(+ const attempt = ({ innerLimit: requested, maxScanTuples, indexWalk, scopeScan }: VectorPoolAttempt) => this.db.transaction(async tx => withVectorSettings(async (sql, values) => (await tx.query<Record<string, unknown>>(sql, values)).rows, iterative, requested, maxScanTuples, async () => {const bound = [...stmt.params];bound[stmt.innerLimitIdx] = requested;- return readVectorPool((await tx.query<Record<string, unknown>>(indexWalk && stmt.indexWalkSql || stmt.sql, bound)).rows);- }, undefined, opts?.hnswIterativeScan, indexWalk && !!stmt.indexWalkSql));+ 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));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 6f89eab003..eb9adb8788 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -65,7 +65,7 @@ import { SCHEMA_SQL } from './schema-embedded.generated.ts';import { verifySchema } from './schema-verify.ts';import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, supportsHnswIterativeScan } from './vector-index.ts';import { searchIndexWalk, searchVectorPool, readVectorPool, remainingVectorBudget, type VectorPoolAttempt } from './search/vector-pool.ts';-import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, SET_STATEMENT_TIMEOUT_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeShareLoader, type PageSourceStats, type VectorSearchStatement } from './search/vector-statement.ts';+import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, SET_STATEMENT_TIMEOUT_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeLoader, type PageSourceStats, type VectorSearchStatement } from './search/vector-statement.ts';import { withVectorSettings } from './search/vector-settings.ts';import {vectorCastSuffix,@@ -179,7 +179,7 @@ export function getPostgresSchema(export class PostgresEngine implements BrainEngine {private vectorIterativeScan?: Promise<boolean>;- private readonly vectorScopeShare = vectorScopeShareLoader(() => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL));+ private readonly vectorScope = vectorScopeLoader(() => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL));/** Transaction clones keep chunk invalidation and replacement atomic. */private _chunkWritesInTransaction = false;readonly kind = 'postgres' as const;@@ -1322,7 +1322,8 @@ 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 stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scopeShare: await this.vectorScopeShare(opts) });+ 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 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);@@ -1354,9 +1355,10 @@ export class PostgresEngine implements BrainEngine {*/async explainVectorSearch(embedding: Float32Array, opts?: SearchOpts): Promise<Record<string, unknown>> {const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());- const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scopeShare: await this.vectorScopeShare(opts) });+ 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 iterative = await this.vectorIterativeScanSupported();- const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: 2_000, remainingMs: 8_000, exact: false, indexWalk: !!stmt.indexWalkSql };+ 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));const plan = row?.['QUERY PLAN'];return (Array.isArray(plan) ? plan[0] : plan) as Record<string, unknown>;@@ -1375,7 +1377,7 @@ export class PostgresEngine implements BrainEngine {private runVectorAttempt(stmt: VectorSearchStatement,- { innerLimit, maxScanTuples, remainingMs, exact, indexWalk }: VectorPoolAttempt,+ { innerLimit, maxScanTuples, remainingMs, exact, indexWalk, scopeScan }: VectorPoolAttempt,iterative: boolean,opts: SearchOpts | undefined,run: (tx: ReturnType<typeof postgres>, sql: string, bound: Parameters<ReturnType<typeof postgres>['unsafe']>[1]) => Promise<Record<string, unknown>[]>,@@ -1383,12 +1385,13 @@ 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, walk || (exact ? stmt.exactSql : stmt.sql), bound as Parameters<typeof tx.unsafe>[1]);- }, deadline, opts?.hnswIterativeScan, !!walk);+ return run(tx, first || (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-pool.ts b/src/core/search/vector-pool.tsindex 86a929e7c9..f7e2582b89 100644--- a/src/core/search/vector-pool.ts+++ b/src/core/search/vector-pool.ts@@ -17,26 +17,40 @@ export interface VectorPoolAttempt {exact: boolean;/** Run the statement's `indexWalkSql` with INDEX_WALK_SETTINGS instead of `sql`. */indexWalk?: boolean;+ /** Run the statement's `scopeScanSql` instead of `sql`. */+ scopeScan?: boolean;}/**- * Runs the statement's index walk (when it has one) before the pool. Its rows- * answer the search when its window is full and they fill the limit; otherwise,- * or past its 2 s budget, this returns null and the caller runs the pool.+ * Runs the statement's index walk, then its scope scan (each when present),+ * before the pool. Walk rows answer the search 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 (a short window). Otherwise, or past an+ * attempt's 2 s budget, this returns null and the caller runs the pool. The+ * walk may visit its whole over-fetched window, so its tuple budget covers it.*/export async function searchIndexWalk(- stmt: Pick<VectorSearchStatement, 'indexWalkSql' | 'innerLimit'>,+ stmt: Pick<VectorSearchStatement, 'indexWalkSql' | 'scopeScanSql' | 'innerLimit' | 'indexWalkOverfetch'>,limit: number,run: (attempt: VectorPoolAttempt) => Promise<VectorPoolBatch>,): Promise<Record<string, unknown>[] | null> {- if (!stmt.indexWalkSql) return null;- try {- const batch = await run({ innerLimit: stmt.innerLimit, maxScanTuples: 2_000, remainingMs: 2_000, exact: false, indexWalk: true });- return batch.candidatePool >= stmt.innerLimit && batch.rows.length >= limit ? batch.rows : null;- } catch (error) {- if ((error as { code?: string }).code === '57014') return null;- throw error;+ const attempt = async (kind: { indexWalk: true } | { scopeScan: true }) => {+ try {+ return await run({ innerLimit: stmt.innerLimit, maxScanTuples: Math.max(2_000, stmt.innerLimit * stmt.indexWalkOverfetch), remainingMs: 2_000, exact: false, ...kind });+ } catch (error) {+ if ((error as { code?: string }).code === '57014') return null;+ throw error;+ }+ };+ if (stmt.indexWalkSql) {+ const batch = await attempt({ indexWalk: true });+ if (batch && batch.candidatePool >= stmt.innerLimit && batch.rows.length >= limit) return batch.rows;+ }+ if (stmt.scopeScanSql) {+ const batch = await attempt({ scopeScan: true });+ if (batch && (batch.rows.length >= limit || batch.candidatePool < stmt.innerLimit)) return batch.rows;}+ return null;}export function remainingVectorBudget(deadline: number): number {diff --git a/src/core/search/vector-settings.ts b/src/core/search/vector-settings.tsindex de0dce7876..967d1254f3 100644--- a/src/core/search/vector-settings.ts+++ b/src/core/search/vector-settings.ts@@ -1,10 +1,11 @@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_OVERFETCH, INDEX_WALK_SETTINGS } from './vector-statement.ts';+import { INDEX_WALK_SETTINGS } from './vector-statement.ts';/**- * `indexWalk` adds INDEX_WALK_SETTINGS and sizes `hnsw.ef_search` for the+ * `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).*/@@ -17,10 +18,10 @@ export async function withVectorSettings<T>(run: () => Promise<T>,deadline?: number,iterativeMode: HnswIterativeScanMode = HNSW_ITERATIVE_SCAN_DEFAULT,- indexWalk = false,+ walkOverfetch?: number,): Promise<T> {- const window = indexWalk ? candidateLimit * INDEX_WALK_OVERFETCH : candidateLimit;- const settings: Record<string, string> = { 'hnsw.ef_search': String(hnswEfSearchFor(window)), ...(indexWalk ? INDEX_WALK_SETTINGS : {}) };+ const window = walkOverfetch ? candidateLimit * walkOverfetch : candidateLimit;+ const settings: Record<string, string> = { 'hnsw.ef_search': String(hnswEfSearchFor(window)), ...(walkOverfetch ? INDEX_WALK_SETTINGS : {}) };const defaults: Record<string, string> = { 'hnsw.ef_search': String(HNSW_EF_SEARCH_DEFAULT), 'hnsw.iterative_scan': 'off', 'hnsw.max_scan_tuples': '20000' };if (iterative) {settings['hnsw.iterative_scan'] = iterativeMode;diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.tsindex 529044fd41..52fa550154 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -26,17 +26,36 @@* pages up front. A 25k-chunk brain flips to a full scan, sort and* nested-loop join at a 50-row limit or on any remote read. The index walk* orders `content_chunks` alone (`ann`, chunk-level filters only, twice the- * window), then joins pages and sources by key and applies every page filter- * to those rows, keeping the nearest `innerLimit` eligible ones: the same set- * the joined statement selects whenever that many survive. Callers run it- * with sorting disabled so the HNSW scan is the only ordered path, accept it- * when its window is full, 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 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 INDEX_WALK_MIN_SCOPE_SHARE: the nearest chunks overall rarely- * fill its window.+ * window, scaled by 1/share for a source scope), then joins pages and+ * sources by key and applies every page filter to those rows, keeping the+ * nearest `innerLimit` eligible ones: the same set the joined statement+ * selects whenever that many survive. Callers run it with sorting disabled so+ * the HNSW scan is the only ordered path, accept it when its window is full,+ * 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+ * 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+ * 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+ * `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+ * its columns. The eligible page ids come first as `= ANY(ARRAY(...))`, so+ * chunks are always reached through `idx_chunks_page`: joined inline, the+ * private-page rule's estimate flipped the scan to a sequential scan of every+ * chunk with a nested-loop join filter and ran the rule once per chunk+ * (1.1 s for a 40k-chunk scope at 50k pages, 9-22 s for a 74k-chunk one). It is complete by construction, where a filtered HNSW scan of+ * a mid-share scope returned a fraction of the true neighbours, and it costs+ * a few microseconds per scope chunk. Up to SCOPE_SCAN_FIRST_MAX_CHUNKS it+ * replaces the walk; above that the walk runs first (fast when the scope's+ * chunks spread through the space) and the scan answers when the walk comes+ * back short, as it does for a scope clustered away from the query. Callers+ * accept the scan when it fills the limit or its window is short (the scope+ * ran out of eligible chunks).*/import type { SearchOpts } from '../types.ts';import { hnswIndexExpected } from '../vector-index.ts';@@ -54,8 +73,10 @@ export interface VectorSearchStatementInput {limit: number;offset: number;opts?: SearchOpts;- /** Estimated share of pages the source scope holds (`vectorScopeShareLoader`); below INDEX_WALK_MIN_SCOPE_SHARE the walk is omitted. */+ /** 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;}export interface VectorSearchStatement {@@ -73,6 +94,10 @@ export interface VectorSearchStatement {relaxed: boolean;/** Index-walk statement (relaxed variant without a type or date filter), same parameters as `sql`; trusted when `candidate_pool` reaches the window. */indexWalkSql?: string;+ /** Raw rows the walk orders per window slot: INDEX_WALK_OVERFETCH, scaled by 1/share for a source scope. */+ indexWalkOverfetch: number;+ /** Exact scan over a small source scope's chunks (relaxed variant), same parameters as `sql`; runs after the walk when both exist. */+ scopeScanSql?: string;}/** Raw rows the index walk orders per window slot, so page filters can drop some and still fill the window. */@@ -85,11 +110,26 @@ export const INDEX_WALK_OVERFETCH = 2;export const INDEX_WALK_SETTINGS: Readonly<Record<string, string>> = { enable_sort: 'off' };/** Source scopes holding a smaller share of pages skip the index walk. */-export const INDEX_WALK_MIN_SCOPE_SHARE = 0.1;+export const INDEX_WALK_MIN_SCOPE_SHARE = 0.04;++/**+ * Source scopes under SCOPE_SCAN_MAX_SHARE of pages get the exact scope scan+ * up to SCOPE_SCAN_MAX_CHUNKS (estimated): first when at most+ * SCOPE_SCAN_FIRST_MAX_CHUNKS, otherwise after the walk comes back short.+ */+export const SCOPE_SCAN_MAX_SHARE = 0.5;+export const SCOPE_SCAN_FIRST_MAX_CHUNKS = 25_000;+export const SCOPE_SCAN_MAX_CHUNKS = 60_000;++/** Walk overfetch for a scope holding `share` of pages: the window keeps about INDEX_WALK_OVERFETCH in-scope rows per slot. */+export function indexWalkOverfetch(share: number | undefined): number {+ return share === undefined || share >= 1 ? INDEX_WALK_OVERFETCH : Math.ceil(INDEX_WALK_OVERFETCH / Math.max(share, INDEX_WALK_MIN_SCOPE_SHARE));+}/** Planner statistics for `pages.source_id`; PGLite analyzes `pages` itself (planner-stats.ts), Postgres through autovacuum. */export const PAGE_SOURCE_STATS_SQL = `SELECT most_common_vals::text::text[] AS sources, most_common_freqs AS freqs, n_distinct, null_frac,- (SELECT reltuples FROM pg_class WHERE oid = 'pages'::regclass) AS reltuples+ (SELECT reltuples FROM pg_class WHERE oid = 'pages'::regclass) AS reltuples,+ (SELECT reltuples FROM pg_class WHERE oid = 'content_chunks'::regclass) AS chunk_reltuplesFROM pg_stats WHERE schemaname = current_schema() AND tablename = 'pages' AND attname = 'source_id'`;export interface PageSourceStats {@@ -98,6 +138,14 @@ export interface PageSourceStats {n_distinct: number;null_frac: number;reltuples: number;+ /** `content_chunks` reltuples; -1 or absent when never analyzed. */+ chunk_reltuples?: number;+}++export interface VectorScope {+ share: number;+ /** Estimated chunks in the scope (share times `content_chunks` reltuples), absent without chunk statistics. */+ chunks?: number;}/** Share of pages the source scope holds, or undefined without a scope or statistics. */@@ -111,18 +159,27 @@ export function sourceScopeShare(stats: PageSourceStats | undefined, opts?: Searreturn [...new Set(scope)].reduce((sum, id) => sum + (sources.includes(id) ? freqs[sources.indexOf(id)]! : unlisted), 0);}+/** Share of pages and estimated chunks the source scope holds, or undefined without a scope or statistics. */+export function sourceScope(stats: PageSourceStats | undefined, opts?: SearchOpts): VectorScope | undefined {+ const share = sourceScopeShare(stats, opts);+ if (share === undefined) return undefined;+ const chunks = Number(stats?.chunk_reltuples ?? -1);+ return chunks > 0 ? { share, chunks: share * chunks } : { share };+}+/**- * The engines' scope-share lookup: PAGE_SOURCE_STATS_SQL through `load`, at- * most once a minute and only for source-scoped searches. A share only- * decides whether the walk runs, never which rows return, so stale or- * missing statistics cost speed at most.+ * The engines' scope lookup: PAGE_SOURCE_STATS_SQL through `load`, at most+ * once a minute and only for source-scoped searches. The estimate only picks+ * the walk, the scope scan or the joined statement, each of which falls back+ * to the joined statement when it comes back short, so stale or missing+ * statistics cost speed at most.*/-export function vectorScopeShareLoader(load: () => Promise<PageSourceStats[]>): (opts?: SearchOpts) => Promise<number | undefined> {+export function vectorScopeLoader(load: () => Promise<PageSourceStats[]>): (opts?: SearchOpts) => Promise<VectorScope | undefined> {let cached: { at: number; stats: Promise<PageSourceStats | undefined> } | undefined;return async opts => {if (!opts?.sourceIds?.length && !opts?.sourceId) return undefined;if (!cached || performance.now() - cached.at > 60_000) cached = { at: performance.now(), stats: load().then(rows => rows[0], () => undefined) };- return sourceScopeShare(await cached.stats, opts);+ return sourceScope(await cached.stats, opts);};}@@ -174,6 +231,10 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): V// so those keep the joined statement alone.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);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})@@ -233,7 +294,7 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): V${chunkFilters.join('\n ')}${relaxedGeneration}ORDER BY cc.${col} <=> ${castSql}- LIMIT ${innerLimitParam}::int * ${INDEX_WALK_OVERFETCH}+ LIMIT ${innerLimitParam}::int * ${overfetch}),hnsw_candidates AS (SELECT@@ -252,6 +313,35 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): VLIMIT ${innerLimitParam}::int),`;+ const scopeScanCandidates = `+ WITH scope_scan AS MATERIALIZED (+ SELECT cc.id+ FROM content_chunks cc+ WHERE cc.page_id = ANY(ARRAY(+ SELECT p.id+ FROM pages p+ JOIN sources s ON s.id = p.source_id+ WHERE true+ ${pageFilters.join('\n ')}+ ${hardExcludeClause}+ ${visibilityClause}+ ))+ AND cc.${col} IS NOT NULL ${modalityFilter}+ ${chunkFilters.join('\n ')}+ ${relaxedGeneration}+ ORDER BY (cc.${col} <=> ${castSql}) + 0, cc.id+ LIMIT ${innerLimitParam}+ ),+ hnsw_candidates AS (+ SELECT+ ${candidateColumns}+ ${hashCurrent} AS hash_current,+ 1 - (cc.${col} <=> ${castSql}) AS raw_score+ FROM scope_scan+ JOIN content_chunks cc ON cc.id = scope_scan.id+ JOIN pages p ON p.id = cc.page_id+ ),`;+const statement = (candidates: string, relax: boolean) => `${candidates}-- score computed as a select-list expr (NOT in the inner ORDER BY, which-- must stay pure-distance so the HNSW index is usable).@@ -297,6 +387,8 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): VinnerLimit,indexed,relaxed,- ...(relaxed && !narrowed ? { indexWalkSql: statement(indexWalkCandidates, true) } : {}),+ indexWalkOverfetch: overfetch,+ ...(walk ? { indexWalkSql: statement(indexWalkCandidates, true) } : {}),+ ...(scopeScan ? { scopeScanSql: statement(scopeScanCandidates, true) } : {}),};}diff --git a/test/e2e/vector-plan-real-column-postgres.test.ts b/test/e2e/vector-plan-real-column-postgres.test.tsindex bf1075d94a..47ecd43ffa 100644--- a/test/e2e/vector-plan-real-column-postgres.test.ts+++ b/test/e2e/vector-plan-real-column-postgres.test.ts@@ -14,8 +14,8 @@* across a filter matrix incl. remote readers, wide windows and RLS;* 3. stale-heavy pools escalate or fall back exactly instead of underfilling;* 4. doctor `vector_plan` reports each outcome;- * 5. a source scope holding a small share of pages skips the walk and runs- * the joined statement first.+ * 5. a source scope holding few chunks skips the walk and runs the exact+ * scope scan first, reaching chunks through idx_chunks_page.** Runs in a dedicated 64-dim database created on the E2E server and dropped in* afterAll, so the shared 1536-dim schema is untouched.@@ -26,7 +26,7 @@ import postgres from '#postgres';import { PostgresEngine } from '../../src/core/postgres-engine.ts';import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';import { refreshProjectionStatistics } from '../../src/core/search/projection-statistics.ts';-import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, PAGE_SOURCE_STATS_SQL, sourceScopeShare, type PageSourceStats } from '../../src/core/search/vector-statement.ts';+import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, PAGE_SOURCE_STATS_SQL, SCOPE_SCAN_FIRST_MAX_CHUNKS, sourceScope, type PageSourceStats } from '../../src/core/search/vector-statement.ts';import * as vectorPool from '../../src/core/search/vector-pool.ts';import type { VectorPoolAttempt, VectorPoolBatch } from '../../src/core/search/vector-pool.ts';import { vectorPlanCheck } from '../../src/commands/doctor/checks/vector-plan.ts';@@ -142,7 +142,7 @@ function axis(d: number): Float32Array {get(target, key) {if (key !== 'unsafe') return Reflect.get(target, key);return (sql: string, params: unknown[]) => {- if (sql.includes('WITH hnsw_candidates') || sql.includes('WITH ann AS MATERIALIZED')) statements.push({ sql, params: [...params] });+ if (sql.includes('WITH hnsw_candidates') || sql.includes('WITH ann AS MATERIALIZED') || sql.includes('WITH scope_scan AS MATERIALIZED')) statements.push({ sql, params: [...params] });return target.unsafe(sql, params);};},@@ -375,7 +375,7 @@ function axis(d: number): Float32Array {}}, 60_000);- test('a source scope holding a small share of pages skips the walk: EXPLAIN and the first attempt run the joined statement', async () => {+ test('a source scope holding few chunks skips the walk: EXPLAIN and the first attempt run the scope scan through idx_chunks_page', async () => {await seedEngine.executeRaw(`INSERT INTO sources (id, name) VALUES ('tiny', 'tiny') ON CONFLICT (id) DO NOTHING`);await seedEngine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)SELECT 'tiny/n-' || i, 'tiny', 'note', 'Tiny ' || i, 'body', '00000000-0000-4000-8000-000000000001'::uuid, '00000000-0000-4000-8000-000000000001'::uuid, 4@@ -387,17 +387,22 @@ function axis(d: number): Float32Array {await seedEngine.executeRaw('ANALYZE pages');const opts: SearchOpts = { limit: 10, embeddingColumn: column, sourceId: 'tiny', excludePrivate: true };const [stats] = await engine.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL);- expect(sourceScopeShare(stats, opts)!).toBeLessThan(INDEX_WALK_MIN_SCOPE_SHARE);- const unscoped = buildVectorSearchStatement({ dialect: 'postgres', embedding: query, limit: 10, offset: 0, opts });- expect(unscoped.indexWalkSql).toBeDefined();+ 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 });+ expect(stmt.indexWalkSql).toBeUndefined();+ expect(stmt.scopeScanSql).toBeDefined();const start = statements.length;- await engine.explainVectorSearch(query, opts);+ const plan = await engine.explainVectorSearch(query, opts);const hits = await engine.searchVector(query, opts);const [explained, searched] = statements.slice(start);- expect(explained.sql).toBe(`EXPLAIN (FORMAT JSON) ${unscoped.sql}`);- expect(searched.sql).toBe(unscoped.sql);+ expect(explained.sql).toBe(`EXPLAIN (FORMAT JSON) ${stmt.scopeScanSql}`);+ expect(searched.sql).toBe(stmt.scopeScanSql!);expect(statements.slice(start).some(entry => entry.sql.includes('WITH ann AS MATERIALIZED'))).toBe(false);+ expect(JSON.stringify(plan)).toContain('"Index Name":"idx_chunks_page"');+ expect(scans(plan)).not.toMatch(/Seq Scan[^>]*content_chunks/);expect(hits).toHaveLength(10);expect(hits.every(hit => hit.source_id === 'tiny')).toBe(true);}, 60_000);diff --git a/test/e2e/vector-scope-recall-postgres.test.ts b/test/e2e/vector-scope-recall-postgres.test.tsnew file mode 100644index 0000000000..6657b861ec--- /dev/null+++ b/test/e2e/vector-scope-recall-postgres.test.ts@@ -0,0 +1,180 @@+/**+ * Vector search recall across source-scope shares, on real-width (1024-dim,+ * TOASTed) vectors. Each scope's results are compared with the exact+ * statement (`exactSql`, no index, unbounded window) for the same query:+ *+ * - scopes under SCOPE_SCAN_MAX_SHARE of pages run the exact scope scan+ * first on this fixture, so their rows equal the exact statement's;+ * - a scope clustered away from the query, sized as a mid-size scope, runs+ * the walk first, comes back short and is answered by the scope scan;+ * - wide scopes and unscoped searches keep the HNSW walk, held to a recall+ * floor against the exact statement.+ *+ * Runs in a dedicated database created on the E2E server and dropped in+ * afterAll. The 50k-page benchmark that motivated the scope scan is in the+ * PR description; this fixture keeps the same statement paths at test size.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import postgres from '#postgres';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, SCOPE_SCAN_FIRST_MAX_CHUNKS, sourceScope, type PageSourceStats, type VectorScope } from '../../src/core/search/vector-statement.ts';+import * as vectorPool from '../../src/core/search/vector-pool.ts';+import type { SearchOpts } from '../../src/core/types.ts';+import { hasDatabase } from './helpers.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';++const DIM = 1024;+const MODEL = 'voyage:voyage-4';+const PAGES = 2_000;+const TOPICS = 8;+const LIMIT = 20;+const QUERIES = 8;+const column = { name: 'embedding', type: 'vector' as const, dimensions: DIM, embeddingModel: MODEL };+/** Share buckets: source id and its share of pages (the rest stay in `default`). */+const BUCKETS: Array<[string, number]> = [['b0_1', 0.001], ['b1', 0.01], ['b4', 0.04], ['b8', 0.08], ['b16', 0.16], ['b50', 0.5]];+/** Pages of topic 0 that are moved to the clustered `topic` source. */+const TOPIC_SOURCE = 'topic';++const adminUrl = process.env.GBRAIN_PGBOUNCER_DIRECT_URL ?? process.env.DATABASE_URL ?? '';+const dbName = `gbrain_test_vector_recall_${randomUUID().replaceAll('-', '')}`;+let admin: ReturnType<typeof postgres> | undefined;+let engine: PostgresEngine;+let queries: Float32Array[] = [];++/** Page ids of the exact statement's results: no index, every candidate ranked. */+async function exactPages(embedding: Float32Array, opts: SearchOpts): Promise<number[]> {+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit: LIMIT, offset: 0, opts });+ const bound = [...stmt.params];+ bound[stmt.innerLimitIdx] = null;+ const rows = await engine.executeRaw<{ page_id: number | null }>(stmt.exactSql, bound);+ return rows.filter(row => row.page_id != null).map(row => Number(row.page_id));+}++async function recall(opts: SearchOpts): Promise<{ recall: number; identical: boolean }> {+ let hit = 0, total = 0, identical = true;+ for (const embedding of queries) {+ const truth = await exactPages(embedding, opts);+ const got = (await engine.searchVector(embedding, { ...opts, limit: LIMIT })).map(row => row.page_id);+ const truthSet = new Set(truth);+ total += truth.length;+ hit += got.filter(id => truthSet.has(id)).length;+ identical &&= JSON.stringify(got) === JSON.stringify(truth);+ }+ return { recall: hit / total, identical };+}++/** Which first attempts searchVector ran: 'walk', 'scan', or neither. */+async function firstAttempts(opts: SearchOpts): Promise<string[]> {+ const kinds: string[] = [];+ const original = vectorPool.searchIndexWalk;+ const spy = spyOn(vectorPool, 'searchIndexWalk').mockImplementation((stmt, limit, run) => original(stmt, limit, async attempt => {+ kinds.push(attempt.scopeScan ? 'scan' : attempt.indexWalk ? 'walk' : 'pool');+ return run(attempt);+ }));+ try {+ await engine.searchVector(queries[0]!, { ...opts, limit: LIMIT });+ } finally {+ spy.mockRestore();+ }+ return kinds;+}++(hasDatabase() ? describe : describe.skip)('vector search recall across source-scope shares (Postgres, 1024-dim)', () => {+ beforeAll(async () => {+ assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);+ admin = postgres(adminUrl, { max: 1, prepare: false });+ await admin.unsafe(`CREATE DATABASE ${dbName}`);+ await admin.unsafe(`ALTER DATABASE ${dbName} SET jit = off`);+ const url = new URL(adminUrl);+ url.pathname = `/${dbName}`;+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIM, env: {} });+ const seed = new PostgresEngine();+ await seed.connect({ database_url: url.toString(), poolSize: 1 });+ await seed.initSchema();+ const sources = [...BUCKETS.map(([id]) => id), TOPIC_SOURCE];+ await seed.executeRaw(`SET session_replication_role = replica`);+ await seed.executeRaw(`INSERT INTO sources (id, name) SELECT s, s FROM unnest($1::text[]) s ON CONFLICT (id) DO NOTHING`, [sources]);+ // Page i: topic i % TOPICS; bucket sources take consecutive slices of a+ // page-id hash so they spread over every topic; topic-0 pages left in+ // `default` move to the clustered `topic` source.+ const cuts = BUCKETS.reduce<Array<[string, number]>>((acc, [id, share]) => [...acc, [id, (acc.at(-1)?.[1] ?? 0) + share]], []);+ const bucketCase = cuts.map(([id, upTo]) => `WHEN r.rank <= ${Math.round(upTo * PAGES)} THEN '${id}'`).join(' ');+ await seed.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)+ SELECT 'notes/n-' || r.i,+ CASE ${bucketCase} WHEN r.i % ${TOPICS} = 0 THEN '${TOPIC_SOURCE}' ELSE 'default' END,+ 'note', 'Note ' || r.i, 'body', '00000000-0000-4000-8000-000000000001'::uuid, '00000000-0000-4000-8000-000000000001'::uuid, 4+ FROM (SELECT i, row_number() OVER (ORDER BY md5(i::text)) AS rank FROM generate_series(0, ${PAGES - 1}) i) r`);+ await seed.executeRaw(`SELECT setseed(0.71)`);+ await seed.executeRaw(`CREATE TEMP TABLE topic_center AS SELECT t, array_agg(random() - 0.5 ORDER BY d)::real[] AS c FROM generate_series(0, ${TOPICS - 1}) t, generate_series(1, ${DIM}) d GROUP BY t`);+ await seed.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding)+ SELECT p.id, ci, 'chunk ' || p.id || ' ' || ci, 'compiled_truth', '${MODEL}', md5('chunk ' || p.id || ' ' || ci),+ (SELECT array_agg(tc.c[d] * 0.8 + (random() - 0.5) * 0.6 ORDER BY d)::real[]::vector FROM generate_series(1, ${DIM}) d WHERE p.id > 0 AND ci >= 0)+ FROM pages p JOIN topic_center tc ON tc.t = split_part(p.slug, '-', 2)::int % ${TOPICS}+ CROSS JOIN generate_series(0, 1) ci`);+ await seed.executeRaw(`SET session_replication_role = origin`);+ await seed.executeRaw('CREATE INDEX IF NOT EXISTS idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops)');+ for (const table of ['content_chunks', 'pages', 'sources']) await seed.executeRaw(`ANALYZE ${table}`);+ // Queries: chunk vectors of topics 1..7 (never the clustered topic 0) plus noise.+ const rows = await seed.executeRaw<{ v: string }>(`SELECT cc.embedding::text AS v FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE split_part(p.slug, '-', 2)::int % ${TOPICS} <> 0 ORDER BY md5(cc.id::text) LIMIT ${QUERIES}`);+ queries = rows.map((row, k) => Float32Array.from(JSON.parse(row.v) as number[], (x, d) => x + Math.sin((k + 1) * (d + 1)) * 0.2));+ await seed.disconnect();+ engine = new PostgresEngine();+ await engine.connect({ database_url: url.toString(), poolSize: 1 });+ }, 300_000);++ afterAll(async () => {+ await engine?.disconnect();+ resetGateway();+ if (admin) {+ await admin.unsafe(`DROP DATABASE IF EXISTS ${dbName} WITH (FORCE)`);+ await admin.end();+ }+ }, 60_000);++ test('the fixture spans the share buckets with TOASTed vectors', async () => {+ const [stats] = await engine.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL);+ for (const [id, share] of BUCKETS) expect(sourceScope(stats, { sourceId: id })!.share).toBeCloseTo(share, 2);+ const [toast] = await engine.executeRaw<{ external: boolean }>(`SELECT pg_column_size(embedding) < ${DIM * 4} OR pg_relation_size(reltoastrelid) > 0 AS external+ FROM content_chunks, pg_class WHERE pg_class.oid = 'content_chunks'::regclass LIMIT 1`);+ expect(toast.external).toBe(true);+ });++ for (const [id] of BUCKETS.filter(([, share]) => share < 0.5)) {+ test(`${id}: the scope scan runs first and returns the exact statement's pages, in order, for local and remote readers`, async () => {+ for (const extra of [{}, { excludePrivate: true }]) {+ const opts: SearchOpts = { embeddingColumn: column, sourceId: id, ...extra };+ expect(await firstAttempts(opts)).toEqual(['scan']);+ const result = await recall(opts);+ expect(result).toEqual({ recall: 1, identical: true });+ }+ }, 120_000);+ }++ test('a mid-size scope clustered away from the query: the walk comes back short and the scope scan answers exactly', async () => {+ const opts: SearchOpts = { embeddingColumn: column, sourceId: TOPIC_SOURCE };+ const scope = engine as unknown as { vectorScope: (opts?: SearchOpts) => Promise<VectorScope | undefined> };+ const original = scope.vectorScope;+ scope.vectorScope = async o => {+ const estimate = await original(o);+ return estimate && { share: 0.2, chunks: SCOPE_SCAN_FIRST_MAX_CHUNKS + 1 };+ };+ try {+ expect(await firstAttempts(opts)).toEqual(['walk', 'scan']);+ expect(await recall(opts)).toEqual({ recall: 1, identical: true });+ } finally {+ scope.vectorScope = original;+ }+ }, 120_000);++ for (const [label, opts] of [['b50 (walk)', { sourceId: 'b50' }], ['unscoped (walk)', {}]] as Array<[string, SearchOpts]>) {+ test(`${label}: the HNSW walk keeps recall against the exact statement`, async () => {+ const result = await recall({ embeddingColumn: column, ...opts });+ console.info(JSON.stringify({ metric: 'vector-scope-recall', scope: label, recall: result.recall }));+ expect(await firstAttempts({ embeddingColumn: column, ...opts })).toEqual(['walk']);+ expect(result.recall).toBeGreaterThanOrEqual(0.9);+ }, 120_000);+ }+});diff --git a/test/engine-sql-chunks.test.ts b/test/engine-sql-chunks.test.tsindex 60b6b50179..c334a30cd3 100644--- a/test/engine-sql-chunks.test.ts+++ b/test/engine-sql-chunks.test.ts@@ -6,13 +6,15 @@* texts together so an edit to one cannot silently leave the other behind:* the fragment rendered at its placeholder positions must equal the shared* builder's text, and bind exactly (model, dims). It also pins- * `decodeEmbedding` (getEmbeddingsByChunkIds' vector decoder) to- * `tryParseEmbedding` for well-formed, malformed and non-string inputs.+ * `decodeVectorSend` (getEmbeddingsByChunkIds' binary vector decoder) to+ * `tryParseEmbedding` of the same rows' text literal on a real engine, for+ * vector and halfvec columns at real width, and to null on malformed input.*/-import { describe, expect, test } from 'bun:test';+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { currentSpaceChunkPredicate } from '../src/core/embedding-invalidation.ts';import { quoteIdentifier } from '../src/core/search/embedding-column.ts';-import { currentSpaceChunkFragment, decodeEmbedding } from '../src/core/engine-sql/chunks.ts';+import { currentSpaceChunkFragment, decodeVectorSend } from '../src/core/engine-sql/chunks.ts';import { tryParseEmbedding } from '../src/core/utils.ts';import { renderFragment } from '../src/core/engine-sql/fragment.ts';@@ -26,22 +28,38 @@ describe('engine-sql chunks: currentSpaceChunkFragment', () => {}});-describe('engine-sql chunks: decodeEmbedding', () => {- const inputs: unknown[] = [- '[0.1,-0.25,3e-8,1024]', ' [ 1 , 2.5 ] ', '[]', '[1,,2]', '[1.,+2,0x10]', '[1e999]', '[NaN]',- '[1,[2]]', '"[1,2]"', '5', 'not-a-vector', '[1,2', '', null, undefined,- [0.5, 1.5], new Float32Array([0.25, 0.75]),- ];- for (const input of inputs) {- test(`matches tryParseEmbedding for ${JSON.stringify(input) ?? String(input)}`, () => {- const expected = tryParseEmbedding(input);- const actual = decodeEmbedding(input);- expect(actual === null ? null : Array.from(actual)).toEqual(expected === null ? null : Array.from(expected));+describe('engine-sql chunks: decodeVectorSend', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.executeRaw(`CREATE EXTENSION IF NOT EXISTS vector`);+ await engine.executeRaw(`CREATE TABLE send_probe (id int PRIMARY KEY, v vector(1024), h halfvec(1024))`);+ await engine.executeRaw(`INSERT INTO send_probe SELECT i, x.v::vector, x.v::halfvec+ FROM generate_series(1, 40) i+ CROSS JOIN LATERAL (SELECT array_agg(((i * 7919 + g * 104729) % 200003) / 100001.5 - 1 + CASE WHEN g = 3 THEN 1e-7 ELSE 0 END)::real[] AS v FROM generate_series(1, 1024) g) x`);+ });+ afterAll(async () => { await engine.disconnect(); });++ for (const column of ['v', 'h']) {+ test(`binary rows equal the text literal's parse bit for bit (${column === 'v' ? 'vector' : 'halfvec'}(1024))`, async () => {+ const rows = await engine.executeRaw<{ id: number; text: string; bin: Uint8Array }>(+ `SELECT id, ${column}::text AS text, vector_send(${column}::vector) AS bin FROM send_probe ORDER BY id`);+ expect(rows).toHaveLength(40);+ for (const row of rows) {+ const binary = decodeVectorSend(row.bin)!;+ const text = tryParseEmbedding(row.text)!;+ expect(binary).toHaveLength(1024);+ expect(Buffer.from(binary.buffer).equals(Buffer.from(text.buffer))).toBe(true);+ }});}- test('decodes a 1024-d pgvector literal exactly like tryParseEmbedding', () => {- const literal = '[' + Array.from({ length: 1024 }, (_, i) => ((i * 7919) % 2001 / 1000 - 1).toFixed(8)).join(',') + ']';- expect(Array.from(decodeEmbedding(literal)!)).toEqual(Array.from(tryParseEmbedding(literal)!));+ test('malformed or non-binary values decode to null', () => {+ const header = (dims: number, floats: number) => { const b = new Uint8Array(4 + 4 * floats); new DataView(b.buffer).setInt16(0, dims); return b; };+ for (const input of [null, undefined, '[1,2]', [1, 2], new Uint8Array(3), header(3, 2), header(1, 2)]) {+ expect(decodeVectorSend(input)).toBeNull();+ }+ expect(Array.from(decodeVectorSend(header(2, 2))!)).toEqual([0, 0]);});});diff --git a/test/search/vector-index-walk.test.ts b/test/search/vector-index-walk.test.tsindex 71c4872bca..08f18a1b43 100644--- a/test/search/vector-index-walk.test.ts+++ b/test/search/vector-index-walk.test.ts@@ -7,15 +7,16 @@* pages that the private-page rule hides (explicit `visibility: private`,* atoms, synthesized concepts, `derived_from` a private page), quarantined* and soft-deleted pages, stale chunk hashes, and three chunks per page, plus- * a `tiny` source with 2% of pages, which skips the walk. Both- * statements run with index scans disabled, so each computes its window- * exactly and the comparison is row-for-row, order included. The Postgres+ * a `tiny` source with 2% of pages, which skips the walk. Every statement+ * runs with index scans disabled, so each computes its window exactly and+ * 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.*/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 { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, PAGE_SOURCE_STATS_SQL, sourceScopeShare, type PageSourceStats } from '../../src/core/search/vector-statement.ts';+import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, PAGE_SOURCE_STATS_SQL, sourceScope, sourceScopeShare, type PageSourceStats } from '../../src/core/search/vector-statement.ts';import type { SearchOpts } from '../../src/core/types.ts';const MODEL = 'test:vector-index-walk';@@ -165,11 +166,54 @@ describe('vector index walk (PGLite)', () => {const opts: SearchOpts = { limit: 20, embeddingColumn: column, sourceIds: ['default', 'side'], excludePrivate: true };const [stats] = await engine.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL);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 }).indexWalkSql!]);+ expect(seen).toEqual([buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(7), limit: 20, offset: 0, opts, scopeShare: scope.share, scopeChunks: scope.chunks }).indexWalkSql!]);expect(hits).toHaveLength(20);});+ const scanMatrix: Array<[string, SearchOpts]> = [+ ['small source', { sourceId: 'side' }],+ ['small source, remote reader', { sourceId: 'side', excludePrivate: true }],+ ['small source, limit 50 and offset', { sourceId: 'side', excludePrivate: true, limit: 50, offset: 5 }],+ ['small source, type filter', { sourceId: 'side', type: 'note' }],+ ['small source, compiled truth only', { sourceIds: ['side', 'tiny'], detail: 'low', excludePrivate: true }],+ ['archived source', { sourceId: 'gone' }],+ ['scope smaller than the limit', { sourceId: 'tiny', excludePrivate: true }],+ ];+ 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 });+ expect(stmt.scopeScanSql).toBeDefined();+ const params = [...stmt.params];+ expect(shape(await exactRows(stmt.scopeScanSql!, params))).toEqual(shape(await exactRows(stmt.sql, params)));+ }+ });+ }++ test('searchVector runs the scope scan for a source with few chunks and returns the joined statement result', async () => {+ 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 });+ expect(stmt.scopeScanSql).toBeDefined();+ expect(stmt.indexWalkSql).toBeUndefined();+ const kinds: string[] = [];+ const original = vectorPool.searchIndexWalk;+ const spy = spyOn(vectorPool, 'searchIndexWalk').mockImplementation((s, limit, run) => original(s, limit, attempt => {+ kinds.push(attempt.scopeScan ? 'scan' : 'walk');+ return run(attempt);+ }));+ try {+ const hits = await engine.searchVector(vec(7), opts);+ expect(kinds).toEqual(['scan']);+ expect(hits.map(hit => hit.slug)).toEqual(shape(await exactRows(stmt.sql, [...stmt.params])).map(row => String(row[0])));+ } finally {+ spy.mockRestore();+ }+ });+test('a selective filter leaves the walk short and searchVector returns the joined statement result', async () => {const opts: SearchOpts = { limit: 10, embeddingColumn: column, sourceId: 'side', excludePrivate: true };const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(7), limit: 10, offset: 0, opts });diff --git a/test/search/vector-pool.test.ts b/test/search/vector-pool.test.tsindex 79d418893c..c33fb5ec6f 100644--- a/test/search/vector-pool.test.ts+++ b/test/search/vector-pool.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from 'bun:test';-import { readVectorPool, searchVectorPool, type VectorPoolAttempt } from '../../src/core/search/vector-pool.ts';+import { readVectorPool, searchIndexWalk, searchVectorPool, type VectorPoolAttempt, type VectorPoolBatch } from '../../src/core/search/vector-pool.ts';import { supportsHnswIterativeScan } from '../../src/core/vector-index.ts';import type { SearchOpts } from '../../src/core/types.ts';@@ -122,3 +122,49 @@ describe('bounded vector candidate safety', () => {rows: [{ page_id: 3, candidate_pool: 100, eligible_pool: 12 }], candidatePool: 100, eligiblePool: 12 });});});++describe('first attempts: index walk, then scope scan', () => {+ const rows = (n: number) => Array.from({ length: n }, (_, page_id) => ({ page_id }));+ async function run(stmt: { indexWalkSql?: string; scopeScanSql?: string }, batches: Partial<Record<'walk' | 'scan', VectorPoolBatch | Error>>, limit = 10) {+ const kinds: Array<'walk' | 'scan'> = [];+ const attempts: VectorPoolAttempt[] = [];+ const result = await searchIndexWalk({ innerLimit: 100, indexWalkOverfetch: 50, ...stmt }, limit, async attempt => {+ const kind = attempt.scopeScan ? 'scan' : 'walk';+ kinds.push(kind);+ attempts.push(attempt);+ const batch = batches[kind]!;+ if (batch instanceof Error) throw batch;+ return batch;+ });+ return { result, kinds, attempts };+ }+ const timeout = () => Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });++ test('no walk and no scan leaves the pool to the caller', async () => {+ expect(await run({}, {})).toEqual({ result: null, kinds: [], attempts: [] });+ });++ test('a full walk window answers; its tuple budget covers the over-fetched window', async () => {+ const { result, kinds, attempts } = await run({ indexWalkSql: 'w', scopeScanSql: 's' }, { walk: { rows: rows(10), candidatePool: 100 } });+ expect(result).toHaveLength(10);+ expect(kinds).toEqual(['walk']);+ expect(attempts[0]).toMatchObject({ indexWalk: true, maxScanTuples: 5000, remainingMs: 2000, exact: false });+ });++ test('a short walk falls through to the scope scan, which answers when it fills the limit or the scope ran out', async () => {+ const short = { rows: rows(4), candidatePool: 40 };+ expect((await run({ indexWalkSql: 'w', scopeScanSql: 's' }, { walk: short, scan: { rows: rows(10), candidatePool: 100 } })).kinds).toEqual(['walk', 'scan']);+ const exhausted = await run({ scopeScanSql: 's' }, { scan: { rows: rows(3), candidatePool: 6 } });+ expect(exhausted.result).toHaveLength(3);+ expect(exhausted.kinds).toEqual(['scan']);+ expect(exhausted.attempts[0]).toMatchObject({ scopeScan: true, exact: false });+ });++ test('a full scan window that stale rows left short, or a timed-out attempt, falls back to the pool', async () => {+ expect((await run({ scopeScanSql: 's' }, { scan: { rows: rows(8), candidatePool: 100, eligiblePool: 90 } })).result).toBeNull();+ expect((await run({ indexWalkSql: 'w' }, { walk: { rows: rows(4), candidatePool: 40 } })).result).toBeNull();+ const timedOut = await run({ indexWalkSql: 'w', scopeScanSql: 's' }, { walk: timeout(), scan: timeout() });+ expect(timedOut).toMatchObject({ result: null, kinds: ['walk', 'scan'] });+ await expect(run({ scopeScanSql: 's' }, { scan: new Error('boom') })).rejects.toThrow('boom');+ });+});diff --git a/test/search/vector-statement.test.ts b/test/search/vector-statement.test.tsindex 364ababdbf..97208890e5 100644--- a/test/search/vector-statement.test.ts+++ b/test/search/vector-statement.test.ts@@ -7,7 +7,7 @@* timeline `stale` column.*/import { afterEach, describe, expect, spyOn, test } from 'bun:test';-import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, sourceScopeShare, vectorScopeShareLoader, type PageSourceStats, type VectorSearchStatementInput } from '../../src/core/search/vector-statement.ts';+import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, indexWalkOverfetch, SCOPE_SCAN_FIRST_MAX_CHUNKS, SCOPE_SCAN_MAX_CHUNKS, SCOPE_SCAN_MAX_SHARE, sourceScope, sourceScopeShare, vectorScopeLoader, type PageSourceStats, type VectorSearchStatementInput } from '../../src/core/search/vector-statement.ts';import { _resetVectorLegacyGuardForTests, readVectorLegacyGuard, resolveVectorLegacyGuard } from '../../src/core/search/vector-legacy-guard.ts';import { withEnv } from '../helpers/with-env.ts';@@ -15,8 +15,8 @@ const MD5 = 'md5(cc.chunk_text)';const indexedColumn = { name: 'embedding', type: 'vector' as const, dimensions: 1536, embeddingModel: 'openai:text-embedding-3-large' };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) {- return buildVectorSearchStatement({ dialect, embedding: new Float32Array([1, 0, 0]), limit: 10, offset: 0, opts: { embeddingColumn: indexedColumn, ...overrides }, scopeShare });+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 });}/** The WHERE of the `hnsw_candidates` CTE, between its FROM and its ORDER BY. */@@ -139,21 +139,90 @@ describe('vector index walk statement', () => {});});-describe('index walk skip for small source scopes', () => {- const stats: PageSourceStats = { sources: ['notes', 'sessions', 'small'], freqs: [0.7, 0.25, 0.01], n_distinct: 5, null_frac: 0, reltuples: 1000 };+describe('source scope strategy: walk overfetch, walk skip and scope scan', () => {+ const stats: PageSourceStats = { sources: ['notes', 'sessions', 'small'], freqs: [0.7, 0.25, 0.01], n_distinct: 5, null_frac: 0, reltuples: 1000, chunk_reltuples: 200_000 };+ const unchanged = (stmt: ReturnType<typeof build>, base: ReturnType<typeof build>) =>+ expect([stmt.sql, stmt.exactSql, stmt.hasMoreSql, stmt.params, stmt.innerLimit, stmt.innerLimitIdx])+ .toEqual([base.sql, base.exactSql, base.hasMoreSql, base.params, base.innerLimit, base.innerLimitIdx]);- test('a scope share below the threshold omits the walk and leaves every other statement byte-identical', () => {+ test('the walk over-fetches about INDEX_WALK_OVERFETCH in-scope rows per window slot', () => {+ expect(indexWalkOverfetch(undefined)).toBe(2);+ expect(indexWalkOverfetch(1)).toBe(2);+ expect(indexWalkOverfetch(0.5)).toBe(4);+ expect(indexWalkOverfetch(0.16)).toBe(13);+ expect(indexWalkOverfetch(INDEX_WALK_MIN_SCOPE_SHARE)).toBe(50);+ expect(indexWalkOverfetch(INDEX_WALK_MIN_SCOPE_SHARE / 10)).toBe(50);+ });++ test('an unscoped or whole-brain scope keeps the walk byte-identical; a partial share only changes its LIMIT factor', () => {+ for (const dialect of ['postgres', 'pglite'] as const) {+ const unscoped = build({ sourceId: 'notes', excludePrivate: true }, dialect);+ const whole = build({ sourceId: 'notes', excludePrivate: true }, dialect, 1, 1_000_000);+ const half = build({ sourceId: 'notes', excludePrivate: true }, dialect, 0.5, 1_000_000);+ expect(unscoped.indexWalkOverfetch).toBe(2);+ expect(whole.indexWalkSql).toBe(unscoped.indexWalkSql!);+ expect(half.indexWalkOverfetch).toBe(4);+ expect(half.indexWalkSql).toBe(unscoped.indexWalkSql!.replace(`::int * 2\n`, `::int * 4\n`));+ for (const stmt of [whole, half]) {+ unchanged(stmt, unscoped);+ expect(stmt.scopeScanSql).toBeUndefined();+ }+ }+ });++ test('a scope share below the walk threshold omits the walk; without chunk statistics it keeps only the joined statement', () => {for (const dialect of ['postgres', 'pglite'] as const) {const unscoped = build({ sourceId: 'small', excludePrivate: true }, dialect);const sparse = build({ sourceId: 'small', excludePrivate: true }, dialect, INDEX_WALK_MIN_SCOPE_SHARE / 2);- const wide = build({ sourceId: 'small', excludePrivate: true }, dialect, INDEX_WALK_MIN_SCOPE_SHARE);expect(sparse.indexWalkSql).toBeUndefined();- expect(wide.indexWalkSql).toBe(unscoped.indexWalkSql!);- for (const stmt of [sparse, wide]) {- expect([stmt.sql, stmt.exactSql, stmt.hasMoreSql, stmt.params, stmt.innerLimit, stmt.innerLimitIdx])- .toEqual([unscoped.sql, unscoped.exactSql, unscoped.hasMoreSql, unscoped.params, unscoped.innerLimit, unscoped.innerLimitIdx]);- }+ expect(sparse.scopeScanSql).toBeUndefined();+ unchanged(sparse, unscoped);+ }+ });++ test('a scope of at most SCOPE_SCAN_FIRST_MAX_CHUNKS runs the scope scan instead of the walk', () => {+ const small = build({ sourceId: 'small' }, 'postgres', 0.2, SCOPE_SCAN_FIRST_MAX_CHUNKS);+ expect(small.scopeScanSql).toBeDefined();+ expect(small.indexWalkSql).toBeUndefined();+ const narrowed = build({ sourceId: 'small', type: 'note' }, 'postgres', 0.01, 500);+ expect(narrowed.scopeScanSql).toBeDefined();+ unchanged(small, build({ sourceId: 'small' }));+ });++ test('a mid-size scope runs the walk first and keeps the scope scan as its fallback; larger, wider or unindexed scopes get no scan', () => {+ const mid = build({ sourceId: 'sessions' }, 'postgres', 0.25, SCOPE_SCAN_MAX_CHUNKS);+ expect(mid.indexWalkSql).toBeDefined();+ expect(mid.scopeScanSql).toBeDefined();+ expect(build({ sourceId: 'sessions' }, 'postgres', 0.25, SCOPE_SCAN_MAX_CHUNKS + 1).scopeScanSql).toBeUndefined();+ expect(build({ sourceId: 'notes' }, 'postgres', SCOPE_SCAN_MAX_SHARE, 1_000).scopeScanSql).toBeUndefined();+ expect(build({ sourceId: 'small' }, 'postgres', 0.01).scopeScanSql).toBeUndefined();+ expect(build({ sourceId: 'small', vectorLegacyGuard: true }, 'postgres', 0.01, 500).scopeScanSql).toBeUndefined();+ expect(build({ sourceId: 'small', embeddingColumn: wideColumn }, 'postgres', 0.01, 500).scopeScanSql).toBeUndefined();+ });++ test('the scope scan orders only chunk ids over the eligible pages, with the index kept out, then joins the window back', () => {+ const stmt = build({ sourceIds: ['a'], exclude_slugs: ['x'], language: 'typescript', detail: 'low', excludePrivate: true, type: 'note' }, 'postgres', 0.01, 500);+ const scan = stmt.scopeScanSql!;+ const cte = scan.slice(scan.indexOf('WITH scope_scan AS MATERIALIZED ('), scan.indexOf('hnsw_candidates AS ('));+ const pagesSubquery = cte.slice(cte.indexOf('ANY(ARRAY('), cte.indexOf('))'));+ expect(cte).toContain('SELECT cc.id\n FROM content_chunks cc\n WHERE cc.page_id = ANY(ARRAY(');+ for (const filter of ['AND p.type = $2', 'AND p.slug != ALL($3::text[])', 'AND p.source_id = ANY($5::text[])', `COALESCE(p.frontmatter->>'visibility'`, "AND NOT (p.slug LIKE 'test/%'"]) {+ expect(pagesSubquery).toContain(filter);}+ expect(pagesSubquery).not.toContain('cc.');+ expect(cte).toContain(`AND cc.chunk_source = 'compiled_truth'`);+ expect(cte).toContain('AND cc.language = $4');+ expect(cte).toContain('AND (cc.model=$6 OR');+ expect(cte).not.toContain(MD5);+ expect(cte).toContain('ORDER BY (cc."embedding" <=> $1::vector) + 0, cc.id');+ expect(cte).toContain(`LIMIT $${stmt.innerLimitIdx + 1}\n`);+ expect(scan).toContain('JOIN content_chunks cc ON cc.id = scope_scan.id');+ expect(scoredCte(scan)).toContain('WHERE $6::text IS NULL OR hash_current');+ const placeholders = (sql: string) => [...new Set(sql.match(/\$\d+/g))].sort();+ expect(placeholders(scan)).toEqual(placeholders(stmt.sql));+ const lite = build({ sourceIds: ['a'], excludePrivate: true }, 'pglite', 0.01, 500).scopeScanSql!;+ expect(lite.replace(' p.updated_at,', '').replace(/CASE WHEN bpp\.updated_at < \([\s\S]*?\) THEN true ELSE false END AS stale/, 'false AS stale'))+ .toBe(build({ sourceIds: ['a'], excludePrivate: true }, 'postgres', 0.01, 500).scopeScanSql!);});test('scope share sums the planner frequencies of the scoped sources', () => {@@ -167,6 +236,13 @@ describe('index walk skip for small source scopes', () => {expect(sourceScopeShare({ sources: null, freqs: null, n_distinct: 4, null_frac: 0, reltuples: 100 }, { sourceId: 'x' })).toBe(0.25);});+ test('scope chunks are the share of content_chunks reltuples, absent when chunks were never analyzed', () => {+ expect(sourceScope(stats, { sourceId: 'sessions' })).toEqual({ share: 0.25, chunks: 50_000 });+ expect(sourceScope({ ...stats, chunk_reltuples: -1 }, { sourceId: 'sessions' })).toEqual({ share: 0.25 });+ expect(sourceScope({ ...stats, chunk_reltuples: undefined }, { sourceId: 'sessions' })).toEqual({ share: 0.25 });+ expect(sourceScope(stats, {})).toBeUndefined();+ });+test('no scope or no statistics leaves the walk on', () => {expect(sourceScopeShare(stats, {})).toBeUndefined();expect(sourceScopeShare(stats, { sourceIds: [] })).toBeUndefined();@@ -176,24 +252,24 @@ describe('index walk skip for small source scopes', () => {test('the loader reads statistics only for scoped searches, once a minute, and treats a failed read as unknown', async () => {let reads = 0;- const share = vectorScopeShareLoader(async () => { reads++; return [stats]; });- expect(await share({})).toBeUndefined();- expect(await share(undefined)).toBeUndefined();+ const scope = vectorScopeLoader(async () => { reads++; return [stats]; });+ expect(await scope({})).toBeUndefined();+ expect(await scope(undefined)).toBeUndefined();expect(reads).toBe(0);- expect(await share({ sourceId: 'small' })).toBe(0.01);- expect(await share({ sourceIds: ['notes'] })).toBe(0.7);+ expect(await scope({ sourceId: 'small' })).toEqual({ share: 0.01, chunks: 2_000 });+ expect((await scope({ sourceIds: ['notes'] }))?.share).toBe(0.7);expect(reads).toBe(1);const now = performance.now();const clock = spyOn(performance, 'now').mockReturnValue(now + 61_000);try {- expect(await share({ sourceId: 'small' })).toBe(0.01);+ expect((await scope({ sourceId: 'small' }))?.share).toBe(0.01);expect(reads).toBe(2);} finally {clock.mockRestore();}- const failing = vectorScopeShareLoader(async () => { throw new Error('permission denied for pg_stats'); });+ const failing = vectorScopeLoader(async () => { throw new Error('permission denied for pg_stats'); });expect(await failing({ sourceId: 'small' })).toBeUndefined();- const empty = vectorScopeShareLoader(async () => []);+ const empty = vectorScopeLoader(async () => []);expect(await empty({ sourceId: 'small' })).toBeUndefined();});});