Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search): skip the vector index walk for source scopes below 10% of pages

time-attack70fab69de17a
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index f9893eb7ad..03e01a3cda 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -24,7 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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-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. 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? }`. 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-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/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 3c75c6b41e..d136881923 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -74,7 +74,7 @@ import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatch
import { 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, VECTOR_EXTENSION_VERSION_SQL } from './search/vector-statement.ts';
+import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeShareLoader, 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,6 +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));
/** Transaction clones keep chunk invalidation and replacement atomic. */
private _chunkWritesInTransaction = false;
private _checkpointGuard: PgliteCheckpointGuard | undefined;
@@ -1681,7 +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 stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding, limit, offset: opts?.offset || 0, opts });
+ const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding, limit, offset: opts?.offset || 0, opts, scopeShare: await this.vectorScopeShare(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.ts
index 263ecc71fc..31a012de77 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, SET_STATEMENT_TIMEOUT_SQL, VECTOR_EXTENSION_VERSION_SQL, type VectorSearchStatement } from './search/vector-statement.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 { withVectorSettings } from './search/vector-settings.ts';
import {
vectorCastSuffix,
@@ -1321,7 +1321,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 stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts });
+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scopeShare: await this.vectorScopeShare(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);
@@ -1353,7 +1353,7 @@ 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 });
+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scopeShare: await this.vectorScopeShare(opts) });
const iterative = await this.vectorIterativeScanSupported();
const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: 2_000, remainingMs: 8_000, exact: false, indexWalk: !!stmt.indexWalkSql };
const [row] = await this.runVectorAttempt(stmt, attempt, iterative, opts, (tx, sql, bound) => tx.unsafe(`EXPLAIN (FORMAT JSON) ${sql}`, bound));
@@ -1361,6 +1361,8 @@ export class PostgresEngine implements BrainEngine {
return (Array.isArray(plan) ? plan[0] : plan) as Record<string, unknown>;
}
+ private readonly vectorScopeShare = vectorScopeShareLoader(() => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL));
+
private async vectorIterativeScanSupported(): Promise<boolean> {
this.vectorIterativeScan ??= this.executeRaw<{ extversion: string }>(VECTOR_EXTENSION_VERSION_SQL)
.then(rows => supportsHnswIterativeScan(rows[0]?.extversion));
diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.ts
index cf0cf5bcd3..529044fd41 100644
--- a/src/core/search/vector-statement.ts
+++ b/src/core/search/vector-statement.ts
@@ -33,7 +33,10 @@
* 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.
+ * 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.
*/
import type { SearchOpts } from '../types.ts';
import { hnswIndexExpected } from '../vector-index.ts';
@@ -51,6 +54,8 @@ 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. */
+ scopeShare?: number;
}
export interface VectorSearchStatement {
@@ -79,6 +84,48 @@ 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;
+
+/** 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
+ FROM pg_stats WHERE schemaname = current_schema() AND tablename = 'pages' AND attname = 'source_id'`;
+
+export interface PageSourceStats {
+ sources: string[] | null;
+ freqs: number[] | null;
+ n_distinct: number;
+ null_frac: number;
+ reltuples: number;
+}
+
+/** Share of pages the source scope holds, or undefined without a scope or statistics. */
+export function sourceScopeShare(stats: PageSourceStats | undefined, opts?: SearchOpts): number | undefined {
+ const scope = opts?.sourceIds?.length ? opts.sourceIds : opts?.sourceId ? [opts.sourceId] : undefined;
+ if (!scope || !stats) return undefined;
+ const sources = stats.sources ?? [];
+ const freqs = (stats.freqs ?? []).map(Number);
+ const distinct = Number(stats.n_distinct) < 0 ? -Number(stats.n_distinct) * Number(stats.reltuples) : Number(stats.n_distinct);
+ const unlisted = Math.max(0, 1 - Number(stats.null_frac) - freqs.reduce((sum, freq) => sum + freq, 0)) / Math.max(1, distinct - sources.length);
+ return [...new Set(scope)].reduce((sum, id) => sum + (sources.includes(id) ? freqs[sources.indexOf(id)]! : unlisted), 0);
+}
+
+/**
+ * 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.
+ */
+export function vectorScopeShareLoader(load: () => Promise<PageSourceStats[]>): (opts?: SearchOpts) => Promise<number | 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);
+ };
+}
+
export function buildVectorSearchStatement(input: VectorSearchStatementInput): VectorSearchStatement {
const { dialect, limit, offset, opts } = input;
const resolvedCol = normalizeEngineColumn(opts?.embeddingColumn);
@@ -122,9 +169,11 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): V
let modelParam: string | undefined;
if (resolvedCol.name === 'embedding') modelParam = bind(resolvedCol.embeddingModel || null);
const relaxed = indexed && modelParam !== undefined && opts?.vectorLegacyGuard !== true;
- // A type or date filter is the caller narrowing the search; the walk would
- // usually come back short, so those keep the joined statement alone.
- const narrowed = !!(opts?.type || opts?.types?.length || opts?.afterDate || opts?.beforeDate);
+ // 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 narrowed = !!(opts?.type || opts?.types?.length || opts?.afterDate || opts?.beforeDate)
+ || (input.scopeShare !== undefined && input.scopeShare < INDEX_WALK_MIN_SCOPE_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.ts
index 1fe51165bf..bf1075d94a 100644
--- a/test/e2e/vector-plan-real-column-postgres.test.ts
+++ b/test/e2e/vector-plan-real-column-postgres.test.ts
@@ -13,7 +13,9 @@
* transaction and scan settings (PostgresEngine.explainVectorSearch),
* 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.
+ * 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.
*
* Runs in a dedicated 64-dim database created on the E2E server and dropped in
* afterAll, so the shared 1536-dim schema is untouched.
@@ -24,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 } from '../../src/core/search/vector-statement.ts';
+import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, PAGE_SOURCE_STATS_SQL, sourceScopeShare, 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';
@@ -372,4 +374,31 @@ function axis(d: number): Float32Array {
await engine.executeRaw('RESET enable_sort');
}
}, 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 () => {
+ 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
+ FROM generate_series(0, 19) i`);
+ await seedEngine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding)
+ SELECT p.id, 0, 'tiny ' || p.id, 'compiled_truth', '${MODEL}', md5('tiny ' || p.id), e.v
+ FROM pages p CROSS JOIN LATERAL (SELECT array_agg(random()::real - 0.5)::vector AS v FROM generate_series(1, ${DIM}) WHERE p.id > 0) e
+ WHERE p.source_id = 'tiny'`);
+ 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 start = statements.length;
+ 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(statements.slice(start).some(entry => entry.sql.includes('WITH ann AS MATERIALIZED'))).toBe(false);
+ expect(hits).toHaveLength(10);
+ expect(hits.every(hit => hit.source_id === 'tiny')).toBe(true);
+ }, 60_000);
});
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 0d249c80b9..0513aad603 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -1145,6 +1145,7 @@
"private transactionOn",
"private vectorIterativeScan",
"private vectorIterativeScanSupported",
+ "private vectorScopeShare",
"private withScopedReadTransaction",
"purgeDeletedPages: (olderThanHours: number, opts?: { dryRun?: boolean; }) => Promise<{ slugs: string[]; count: number; pages?: { slug: string; deleted_at: Date; }[]; }>",
"putContradictionCacheEntry: (opts: { chunk_a_hash: string; chunk_b_hash: string; model_id: string; prompt_version: string; truncation_policy: string; verdict: Record<string, unknown>; ttl_seconds?: number; }) => Promise<void>",
@@ -6307,6 +6308,7 @@
"private engineSql",
"private getBulkRetryOpts",
"private vectorIterativeScan",
+ "private vectorScopeShare",
"purgeDeletedPages: (olderThanHours: number, opts?: { dryRun?: boolean; }) => Promise<{ slugs: string[]; count: number; pages?: { slug: string; deleted_at: Date; }[]; }>",
"putContradictionCacheEntry: (opts: { chunk_a_hash: string; chunk_b_hash: string; model_id: string; prompt_version: string; truncation_policy: string; verdict: Record<string, unknown>; ttl_seconds?: number; }) => Promise<void>",
"putDreamVerdict: (filePath: string, contentHash: string, verdict: DreamVerdictInput) => Promise<void>",
diff --git a/test/search/vector-index-walk.test.ts b/test/search/vector-index-walk.test.ts
index 4afd21935f..71c4872bca 100644
--- a/test/search/vector-index-walk.test.ts
+++ b/test/search/vector-index-walk.test.ts
@@ -6,14 +6,16 @@
* Fixture (PGLite, 8-dim): three sources (one archived), five page types,
* 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. Both
+ * 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
* plan proof is test/e2e/vector-plan-real-column-postgres.test.ts.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
-import { buildVectorSearchStatement } from '../../src/core/search/vector-statement.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 type { SearchOpts } from '../../src/core/types.ts';
const MODEL = 'test:vector-index-walk';
@@ -47,7 +49,7 @@ beforeAll(async () => {
await engine.executeRaw('DROP INDEX IF EXISTS idx_chunks_embedding');
await engine.executeRaw(`ALTER TABLE content_chunks ALTER COLUMN embedding TYPE vector(${DIM})`);
await engine.executeRaw('CREATE INDEX idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops)');
- await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('side', 'side'), ('gone', 'gone') ON CONFLICT (id) DO NOTHING`);
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('side', 'side'), ('gone', 'gone'), ('tiny', 'tiny') ON CONFLICT (id) DO NOTHING`);
await engine.executeRaw(`UPDATE sources SET archived = true WHERE id = 'gone'`);
// Page i sits in block i / 20, which sets its source; inside a block,
// offsets 0-3 are hidden from remote readers by four private-page rules
@@ -65,6 +67,10 @@ beforeAll(async () => {
'00000000-0000-4000-8000-000000000001'::uuid, '00000000-0000-4000-8000-000000000001'::uuid, 4,
CASE WHEN i % 37 = 0 THEN now() END
FROM generate_series(0, ${PAGES - 1}) i`);
+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, knowledge_revision, text_projection_revision, chunker_version)
+ SELECT 'tiny/n-' || i, 'tiny', 'note', 'Tiny ' || i, 'body', '{}'::jsonb,
+ '00000000-0000-4000-8000-000000000001'::uuid, '00000000-0000-4000-8000-000000000001'::uuid, 4
+ FROM generate_series(1004, 1015) i`);
const pages = await engine.executeRaw<{ id: number; slug: string }>(`SELECT id, slug FROM pages ORDER BY id`);
const ids: number[] = [], idx: number[] = [], texts: string[] = [], hashes: (string | null)[] = [], vectors: string[] = [];
for (const page of pages) {
@@ -122,6 +128,48 @@ describe('vector index walk (PGLite)', () => {
}
});
+ async function statementsSearched(opts: SearchOpts) {
+ const seen: Array<string | undefined> = [];
+ const original = vectorPool.searchIndexWalk;
+ const spy = spyOn(vectorPool, 'searchIndexWalk').mockImplementation((stmt, limit, run) => {
+ seen.push(stmt.indexWalkSql);
+ return original(stmt, limit, run);
+ });
+ await engine.executeRaw('SET enable_indexscan = off');
+ try {
+ return { hits: await engine.searchVector(vec(7), opts), seen };
+ } finally {
+ await engine.executeRaw('RESET enable_indexscan');
+ spy.mockRestore();
+ }
+ }
+
+ test('a source scope below the share threshold skips the walk and returns the joined statement result', async () => {
+ const opts: SearchOpts = { limit: 10, embeddingColumn: column, sourceId: 'tiny', excludePrivate: true };
+ const [stats] = await engine.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL);
+ 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 });
+ expect(stmt.indexWalkSql).toBeUndefined();
+ const unscoped = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(7), limit: 10, offset: 0, opts });
+ expect(stmt.sql).toBe(unscoped.sql);
+ const joined = await exactRows(stmt.sql, [...stmt.params]);
+ const { hits, seen } = await statementsSearched(opts);
+ expect(seen).toEqual([undefined]);
+ expect(hits).toHaveLength(10);
+ expect(hits.map(hit => hit.slug)).toEqual(shape(joined).map(row => String(row[0])));
+ });
+
+ test('a source scope at or above the share threshold still runs the walk', async () => {
+ 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 { hits, seen } = await statementsSearched(opts);
+ expect(seen).toEqual([buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(7), limit: 20, offset: 0, opts }).indexWalkSql!]);
+ expect(hits).toHaveLength(20);
+ });
+
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-statement.test.ts b/test/search/vector-statement.test.ts
index 4e7a9f6923..364ababdbf 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, type VectorSearchStatementInput } from '../../src/core/search/vector-statement.ts';
+import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, sourceScopeShare, vectorScopeShareLoader, 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') {
- return buildVectorSearchStatement({ dialect, embedding: new Float32Array([1, 0, 0]), limit: 10, offset: 0, opts: { embeddingColumn: indexedColumn, ...overrides } });
+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 });
}
/** The WHERE of the `hnsw_candidates` CTE, between its FROM and its ORDER BY. */
@@ -139,6 +139,65 @@ 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 };
+
+ test('a scope share below the threshold omits the walk and leaves every other statement byte-identical', () => {
+ 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]);
+ }
+ }
+ });
+
+ test('scope share sums the planner frequencies of the scoped sources', () => {
+ expect(sourceScopeShare(stats, { sourceId: 'sessions' })).toBe(0.25);
+ expect(sourceScopeShare(stats, { sourceIds: ['notes', 'sessions', 'notes'] })).toBeCloseTo(0.95);
+ expect(sourceScopeShare(stats, { sourceIds: ['small'], sourceId: 'notes' })).toBe(0.01);
+ // Unlisted sources split what the MCV list leaves: (1 - 0.96) / (5 - 3).
+ expect(sourceScopeShare(stats, { sourceId: 'missing' })).toBeCloseTo(0.02);
+ // A negative n_distinct is a fraction of the row estimate.
+ expect(sourceScopeShare({ ...stats, n_distinct: -0.005 }, { sourceId: 'missing' })).toBeCloseTo(0.04 / 2);
+ expect(sourceScopeShare({ sources: null, freqs: null, n_distinct: 4, null_frac: 0, reltuples: 100 }, { sourceId: 'x' })).toBe(0.25);
+ });
+
+ test('no scope or no statistics leaves the walk on', () => {
+ expect(sourceScopeShare(stats, {})).toBeUndefined();
+ expect(sourceScopeShare(stats, { sourceIds: [] })).toBeUndefined();
+ expect(sourceScopeShare(undefined, { sourceId: 'small' })).toBeUndefined();
+ expect(build({ sourceId: 'small' }, 'postgres', undefined).indexWalkSql).toBeDefined();
+ });
+
+ 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();
+ expect(reads).toBe(0);
+ expect(await share({ sourceId: 'small' })).toBe(0.01);
+ expect(await share({ sourceIds: ['notes'] })).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(reads).toBe(2);
+ } finally {
+ clock.mockRestore();
+ }
+ const failing = vectorScopeShareLoader(async () => { throw new Error('permission denied for pg_stats'); });
+ expect(await failing({ sourceId: 'small' })).toBeUndefined();
+ const empty = vectorScopeShareLoader(async () => []);
+ expect(await empty({ sourceId: 'small' })).toBeUndefined();
+ });
+});
+
describe('vector legacy guard setting', () => {
afterEach(() => _resetVectorLegacyGuardForTests());