Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): widen the vector index walk when a full window's pages fall short
garrytan11135d2433b2
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 887a2a62f8..633d4fec3f 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -45,7 +45,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/tune-recommendations.ts` — tuning recommendations never propose enabling or tuning unavailable semantic result caching. Mode-reduction suggestions describe payload size, not expansion savings: shipped commands pin expansion independently of the bundle.-- `src/core/search/vector-pool.ts` + `vector-settings.ts` — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness instead. Every pooled attempt scans with `hnsw.max_scan_tuples` = `POOL_MAX_SCAN_TUPLES` (20,000, pgvector's default), so a filtered attempt fills its candidate window before it is accepted; the index walk and scope scan keep their own window-sized budget (`searchIndexWalk`). Settings are restored even inside caller-owned transactions. A batch carries the raw `candidatePool` (exhaustion: a short window means the index ran dry) and an optional `eligiblePool` (candidates that passed the freshness filter outside the candidate CTE); `hasMore` receives the eligible count, defaulting to the raw one. `vectorScanSettings(...)` computes one attempt's settings (Postgres applies them in its search transaction's one settings statement, `postgres-engine/search-settings.ts`); `withVectorSettings(..., iterativeMode, indexWalk)` (PGLite and the fact-relevance read) reads, sets and restores them and sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`); `indexWalk` adds `INDEX_WALK_SETTINGS` and sizes `ef_search` for the over-fetched window. `searchIndexWalk(stmt, limit, run)` runs the statement's index walk before the pool and returns its rows only when its window is full and they fill the limit; otherwise (or past its 2 s budget) both engines run the pool unchanged.+- `src/core/search/vector-pool.ts` + `vector-settings.ts` — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness instead. Every pooled attempt scans with `hnsw.max_scan_tuples` = `POOL_MAX_SCAN_TUPLES` (20,000, pgvector's default), so a filtered attempt fills its candidate window before it is accepted; the index walk and scope scan keep their own window-sized budget (`searchIndexWalk`). Settings are restored even inside caller-owned transactions. A batch carries the raw `candidatePool` (exhaustion: a short window means the index ran dry) and an optional `eligiblePool` (candidates that passed the freshness filter outside the candidate CTE); `hasMore` receives the eligible count, defaulting to the raw one. `vectorScanSettings(...)` computes one attempt's settings (Postgres applies them in its search transaction's one settings statement, `postgres-engine/search-settings.ts`); `withVectorSettings(..., iterativeMode, indexWalk)` (PGLite and the fact-relevance read) reads, sets and restores them and sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`); `indexWalk` adds `INDEX_WALK_SETTINGS` and sizes `ef_search` for the over-fetched window. `searchIndexWalk(stmt, limit, run)` runs the statement's index walk before the pool and returns its rows only when its window is full and they fill the limit. A full window with enough fresh chunks but too few pages widens x4 (`INDEX_WALK_ESCALATIONS`, 2) first. Otherwise (or past a 2 s budget) both engines run the pool.- `src/core/search/vector-statement.ts` — `buildVectorSearchStatement({ dialect, embedding, limit, offset, opts })` builds the vector-search SQL once for both engines, doctor `vector_plan` and the plan-proof E2E: `{ sql, exactSql, hasMoreSql, params, innerLimitIdx, innerLimit, indexed, relaxed, indexWalkSql?, indexWalkOverfetch, scopeScanSql? }`. On an HNSW-indexed `embedding` column (relaxed variant) the candidate CTE carries only the model check; content freshness (`embedded_text_hash = md5(chunk_text)` or NULL) is projected as `hash_current` and filtered in `scored`, because Postgres cannot estimate that expression and drops the index when it sits in the CTE (#5824). Non-indexed columns, the legacy guard, `exactSql` and `hasMoreSql` keep the full guard inside. The pool row reports `candidate_pool` (raw) and `eligible_pool` (fresh). Since/until bounds are spelled per column (`effective_date`, then `updated_at`, then `created_at`) so each arm has column statistics. `indexWalkSql` (relaxed variant without a type or date filter, same parameters) is the statement both engines run first: `ann` orders `content_chunks` alone with the chunk-level filters over twice the window, then pages and sources are joined by key and every page filter, visibility and the private-page rule apply to those rows, keeping the nearest `innerLimit`. Run with `enable_sort = off` (`INDEX_WALK_SETTINGS`) the HNSW scan is its only ordered path; the joined statement's plan sat on a cost knife edge (TOASTed vectors cost a sequential scan too little, the HNSW estimate grows with `ef_search`, the private-page rule's subplans priced every page lookup high) and flipped to a full scan and sort at a 50-row limit or on any remote read. A full walk window selects the same rows as the joined statement (`test/search/vector-index-walk.test.ts`); a short one falls back to it. Source scopes: each engine's `vectorScopeLoader` reads `PAGE_SOURCE_STATS_SQL` (`pages.source_id` planner statistics plus `content_chunks` reltuples) at most once a minute, only for source-scoped searches, and passes `scope` (`share`, and `chunks`). For a scope under `SCOPE_SCAN_MAX_SHARE`, `chunks` comes from `SCOPE_CHUNKS_SQL` (at most once a minute per scope): the scope's live pages times the chunks per page of a `hashint4` stride sample of about 400 of them (every page in a smaller scope), because the page share undercounts sources of long pages; otherwise, and when the count fails, it is the share times chunk reltuples. The walk over-fetches `indexWalkOverfetch(share)` = ceil(2 / share) rows per window slot (2 unscoped or for a whole-brain scope, so that statement is byte-identical), and a share below `INDEX_WALK_MIN_SCOPE_SHARE` (0.04) skips it. `scopeScanSql` (relaxed variant, same parameters) serves a scope under `SCOPE_SCAN_MAX_SHARE` (0.3) of pages with at most `SCOPE_SCAN_MAX_CHUNKS` (120k) counted chunks: an exact distance scan over the scope's chunks, page filters and visibility applied once per page inside `cc.page_id = ANY(ARRAY(...))` so chunks are always reached through `idx_chunks_page` (an inline join flipped to a sequential scan with the private-page rule), ordering only chunk ids with `(distance) + 0` to keep the index out, then the window joins back for its columns. Up to `SCOPE_SCAN_FIRST_MAX_CHUNKS` (25k) it replaces the walk; above that the walk runs first and the scan answers when the walk comes back short (a scope clustered away from the query). It returns the joined statement's rows (`test/search/vector-index-walk.test.ts`); recall across share buckets on 1024-dim vectors is pinned by `test/e2e/vector-scope-recall-postgres.test.ts`. Missing statistics leave only the unscoped walk and the joined statement. PGLite adds the timeline `stale` column; everything else is byte-identical across dialects. Also exports the extension-version probe and the transaction-local `statement_timeout` SQL the Postgres engine runs. Pinned by `test/search/vector-statement.test.ts`, `test/search/vector-freshness.test.ts` and `test/e2e/vector-plan-real-column-postgres.test.ts`.diff --git a/src/core/search/vector-pool.ts b/src/core/search/vector-pool.tsindex ed294f22b5..9d8b6f4280 100644--- a/src/core/search/vector-pool.ts+++ b/src/core/search/vector-pool.ts@@ -21,30 +21,46 @@ export interface VectorPoolAttempt {scopeScan?: boolean;}+/**+ * Times the index walk widens its window (x4 each) when a full window held+ * enough fresh chunks to fill the limit but too few pages: the nearest+ * chunks crowd into a few long pages. 250 -> 1,000 -> 4,000 for a 50-row+ * search. The joined statement the pool would run instead can plan the+ * private-page rule as a full page filter rescanned per candidate (2-3 s per+ * attempt at 50k pages), so its escalations ran into the 8 s vector deadline.+ */+export const INDEX_WALK_ESCALATIONS = 2;+/*** 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.+ * they fill the limit; a full window whose fresh chunks could fill the limit+ * but whose pages fall short widens (INDEX_WALK_ESCALATIONS). Scope-scan rows+ * answer 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' | 'scopeScanSql' | 'innerLimit' | 'indexWalkOverfetch'>,limit: number,run: (attempt: VectorPoolAttempt) => Promise<VectorPoolBatch>,): Promise<Record<string, unknown>[] | null> {- const attempt = async (kind: { indexWalk: true } | { scopeScan: true }) => {+ const attempt = async (kind: { indexWalk: true } | { scopeScan: true }, innerLimit = stmt.innerLimit) => {try {- return await run({ innerLimit: stmt.innerLimit, maxScanTuples: Math.max(2_000, stmt.innerLimit * stmt.indexWalkOverfetch), remainingMs: 2_000, exact: false, ...kind });+ return await run({ innerLimit, maxScanTuples: Math.max(2_000, 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;+ for (let innerLimit = stmt.innerLimit, escalations = 0; ; innerLimit *= 4, escalations++) {+ const batch = await attempt({ indexWalk: true }, innerLimit);+ if (!batch || batch.candidatePool < innerLimit) break;+ if (batch.rows.length >= limit) return batch.rows;+ if ((batch.eligiblePool ?? batch.candidatePool) < limit || escalations >= INDEX_WALK_ESCALATIONS) break;+ }}if (stmt.scopeScanSql) {const batch = await attempt({ scopeScan: true });diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.tsindex e15294de9b..7f1efe472a 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -31,7 +31,8 @@* 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+ * widen it when a full window's pages fall short of the limit+ * (searchIndexWalk), and otherwise run the joined statement as before, whose plans stay with the* planner for selective filters. A type or date filter skips the walk: it is* 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 pagesdiff --git a/test/e2e/vector-plan-real-column-postgres.test.ts b/test/e2e/vector-plan-real-column-postgres.test.tsindex 1bbb405b87..678cd023bb 100644--- a/test/e2e/vector-plan-real-column-postgres.test.ts+++ b/test/e2e/vector-plan-real-column-postgres.test.ts@@ -330,6 +330,41 @@ function axis(d: number): Float32Array {expect(events).toEqual([]);}, 60_000);+ test('a full walk window crowded into a few long pages widens the walk instead of running the joined pool statement', async () => {+ // 20 pages x 40 chunks along the (e_7, e_8) arc, each page's chunks+ // contiguous: the first 100-row window holds 3 pages, the 400-row one 10.+ const pages = 20, perPage = 40;+ await seedEngine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)+ SELECT 'long-page-' || k, 'default', 'note', 'long page ' || k, 'long', '00000000-0000-4000-8000-000000000001'::uuid,+ '00000000-0000-4000-8000-000000000001'::uuid, 4+ FROM generate_series(0, ${pages - 1}) k`);+ await seedEngine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding)+ SELECT p.id, j, 'long text ' || p.slug || ' ' || j, 'compiled_truth', '${MODEL}', md5('long text ' || p.slug || ' ' || j),+ (SELECT array_agg(CASE WHEN d = 7 THEN cos(a) WHEN d = 8 THEN sin(a) ELSE 0 END ORDER BY d)::real[]::vector FROM generate_series(1, ${DIM}) d)+ FROM pages p CROSS JOIN generate_series(0, ${perPage - 1}) j+ CROSS JOIN LATERAL (SELECT (split_part(p.slug, '-', 3)::int * ${perPage} + j) * 0.0005 AS a) ang+ WHERE p.slug LIKE 'long-page-%'`);+ await seedEngine.executeRaw('ANALYZE content_chunks');+ await seedEngine.executeRaw('ANALYZE pages');+ const walks: number[] = [];+ const original = vectorPool.searchIndexWalk;+ const walkSpy = spyOn(vectorPool, 'searchIndexWalk').mockImplementation((stmt, limit, run) => original(stmt, limit, async attempt => {+ walks.push(attempt.innerLimit);+ return run(attempt);+ }));+ try {+ const attempts = spyAttempts();+ const events: PoolMeta[] = [];+ const hits = await engine.searchVector(axis(7), { limit: 10, excludePrivate: true, embeddingColumn: column, onVectorPoolMeta: meta => events.push(meta) });+ expect(hits.map(hit => hit.slug)).toEqual(Array.from({ length: 10 }, (_, k) => `long-page-${k}`));+ expect(walks).toEqual([100, 400]);+ expect(attempts).toEqual([]);+ expect(events).toEqual([]);+ } finally {+ walkSpy.mockRestore();+ }+ }, 60_000);+test('without iterative scan the exact fallback still returns only current chunks', async () => {const capability = engine as unknown as { vectorIterativeScan?: Promise<boolean> };const previous = capability.vectorIterativeScan;diff --git a/test/search/vector-pool.test.ts b/test/search/vector-pool.test.tsindex 8e562e5f48..e68dbed094 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 { POOL_MAX_SCAN_TUPLES, readVectorPool, searchIndexWalk, searchVectorPool, type VectorPoolAttempt, type VectorPoolBatch } from '../../src/core/search/vector-pool.ts';+import { INDEX_WALK_ESCALATIONS, POOL_MAX_SCAN_TUPLES, 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';@@ -177,6 +177,34 @@ describe('first attempts: index walk, then scope scan', () => {expect(exhausted.attempts[0]).toMatchObject({ scopeScan: true, exact: false });});+ test('a full walk window whose fresh chunks crowd into too few pages widens the walk before any pool attempt', async () => {+ const windows: number[] = [];+ const result = await searchIndexWalk({ indexWalkSql: 'w', innerLimit: 250, indexWalkOverfetch: 2 }, 50, async attempt => {+ windows.push(attempt.innerLimit);+ expect(attempt).toMatchObject({ indexWalk: true, maxScanTuples: Math.max(2_000, attempt.innerLimit * 2), remainingMs: 2_000, exact: false });+ return { rows: rows(attempt.innerLimit >= 1_000 ? 50 : 49), candidatePool: attempt.innerLimit, eligiblePool: attempt.innerLimit };+ });+ expect(result).toHaveLength(50);+ expect(windows).toEqual([250, 1_000]);+ });++ test('the walk widens at most INDEX_WALK_ESCALATIONS times, and never for a stale-short or short window', async () => {+ const widen = async (batch: (innerLimit: number) => VectorPoolBatch, scopeScanSql?: string) => {+ const windows: number[] = [];+ const result = await searchIndexWalk({ indexWalkSql: 'w', ...(scopeScanSql ? { scopeScanSql } : {}), innerLimit: 250, indexWalkOverfetch: 2 }, 50, async attempt => {+ if (attempt.scopeScan) return { rows: rows(50), candidatePool: 250 };+ windows.push(attempt.innerLimit);+ return batch(attempt.innerLimit);+ });+ return { result, windows };+ };+ expect(INDEX_WALK_ESCALATIONS).toBe(2);+ expect(await widen(n => ({ rows: rows(10), candidatePool: n, eligiblePool: n }))).toEqual({ result: null, windows: [250, 1_000, 4_000] });+ expect(await widen(n => ({ rows: rows(10), candidatePool: n, eligiblePool: 40 }))).toEqual({ result: null, windows: [250] });+ expect(await widen(() => ({ rows: rows(10), candidatePool: 200, eligiblePool: 200 }))).toEqual({ result: null, windows: [250] });+ expect((await widen(n => ({ rows: rows(10), candidatePool: n, eligiblePool: n }), 's')).result).toHaveLength(50);+ });+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();