Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): scope scan cap in counted chunks; tests for the sampled count
time-attacke7a06ebca2f3
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 776f667136..7c8d9538e0 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, walkOverfetch)` sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`); `walkOverfetch` (the statement's `indexWalkOverfetch`, index walk only) adds `INDEX_WALK_SETTINGS` and sizes `ef_search` for the over-fetched window. `searchIndexWalk(stmt, limit, run)` runs the statement's index walk, then its scope scan (each when present), before the pool: walk rows answer when its window is full and they fill the limit, scope-scan rows when they fill the limit or the scope ran out of eligible chunks; otherwise (or past an attempt's 2 s budget) both engines run the pool unchanged. The walk's `hnsw.max_scan_tuples` covers its whole over-fetched window.-- `src/core/search/vector-statement.ts` — `buildVectorSearchStatement({ dialect, embedding, limit, offset, opts })` builds the vector-search SQL once for both engines, doctor `vector_plan` and the plan-proof E2E: `{ sql, exactSql, hasMoreSql, params, innerLimitIdx, innerLimit, indexed, relaxed, indexWalkSql?, 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` = 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` (60k) estimated chunks: an exact distance scan over the scope's chunks, page filters and visibility applied once per page inside `cc.page_id = ANY(ARRAY(...))` so chunks are always reached through `idx_chunks_page` (an inline join flipped to a sequential scan with the private-page rule), ordering only chunk ids with `(distance) + 0` to keep the index out, then the window joins back for its columns. Up to `SCOPE_SCAN_FIRST_MAX_CHUNKS` (25k) it replaces the walk; above that the walk runs first and the scan answers when the walk comes back short (a scope clustered away from the query). It returns the joined statement's rows (`test/search/vector-index-walk.test.ts`); recall across share buckets on 1024-dim vectors is pinned by `test/e2e/vector-scope-recall-postgres.test.ts`. Missing statistics leave only the unscoped walk and the joined statement. PGLite adds the timeline `stale` column; everything else is byte-identical across dialects. Also exports the extension-version probe and the transaction-local `statement_timeout` SQL the Postgres engine runs. Pinned by `test/search/vector-statement.test.ts`, `test/search/vector-freshness.test.ts` and `test/e2e/vector-plan-real-column-postgres.test.ts`.+- `src/core/search/vector-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`.- `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/search/vector-statement.ts b/src/core/search/vector-statement.tsindex 665e0edc75..f164815eb5 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -116,12 +116,18 @@ 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+ * up to SCOPE_SCAN_MAX_CHUNKS (counted, SCOPE_CHUNKS_SQL): first when at most* SCOPE_SCAN_FIRST_MAX_CHUNKS, otherwise after the walk comes back short.+ * The scan costs about 5 µs per scope chunk (75k chunks: 340 ms, 157k:+ * 760 ms on a 50k-page brain), so the 120k cap keeps the fallback near+ * 600 ms, under the joined statement's 820 ms on a clustered 75k-chunk scope+ * and well inside the attempt's 2 s budget. The cap was 60k when the count+ * was the page share of chunk reltuples, which put that 75k-chunk scope at+ * 39k.*/export const SCOPE_SCAN_MAX_SHARE = 0.3;export const SCOPE_SCAN_FIRST_MAX_CHUNKS = 25_000;-export const SCOPE_SCAN_MAX_CHUNKS = 60_000;+export const SCOPE_SCAN_MAX_CHUNKS = 120_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 {diff --git a/test/search/vector-scope-chunks.test.ts b/test/search/vector-scope-chunks.test.tsnew file mode 100644index 0000000000..1d6ff96175--- /dev/null+++ b/test/search/vector-scope-chunks.test.ts@@ -0,0 +1,96 @@+/**+ * SCOPE_CHUNKS_SQL on a real engine (PGLite): a scope of at most+ * SCOPE_CHUNK_SAMPLE_PAGES pages is counted exactly (soft-deleted pages+ * excluded), a larger one through its hash-stride sample lands near the true+ * count, and the engine's loader routes a source of long pages on that count+ * where the page share would have undercounted it. No embeddings are needed:+ * routing reads only pages, chunks and planner statistics.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import {+ buildVectorSearchStatement,+ PAGE_SOURCE_STATS_SQL,+ SCOPE_CHUNK_SAMPLE_PAGES,+ SCOPE_CHUNKS_SQL,+ SCOPE_SCAN_FIRST_MAX_CHUNKS,+ sourceScope,+ type PageSourceStats,+ type ScopeChunkCount,+ type VectorScope,+} from '../../src/core/search/vector-statement.ts';+import type { SearchOpts } from '../../src/core/types.ts';++const column = { name: 'embedding', type: 'vector' as const, dimensions: 1536, embeddingModel: 'test:scope-chunks' };+/** Source, pages, chunks per page; `notes` pages interleave with `sessions` pages by id. */+const SOURCES: Array<[string, number, number]> = [['notes', 6_000, 2], ['sessions', 1_000, 28], ['tiny', 60, 3]];++let engine: PGLiteEngine;++async function trueChunks(ids: string[]): Promise<number> {+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE p.source_id = ANY($1::text[]) AND p.deleted_at IS NULL`, [ids]);+ return Number(row!.n);+}++async function counted(ids: string[]): Promise<ScopeChunkCount> {+ const [row] = await engine.executeRaw<ScopeChunkCount>(SCOPE_CHUNKS_SQL, [ids]);+ return row!;+}++describe('SCOPE_CHUNKS_SQL', () => {+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw(`INSERT INTO sources (id, name) SELECT s, s FROM unnest($1::text[]) s ON CONFLICT (id) DO NOTHING`, [SOURCES.map(([id]) => id)]);+ // Interleave notes and sessions ids (every 7th page is a session) so a plain id stride would alias.+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, deleted_at)+ SELECT 'p-' || i, CASE WHEN i % 7 = 0 THEN 'sessions' ELSE 'notes' END, 'note', 'P' || i, 'body',+ CASE WHEN i % 97 = 0 THEN now() END+ FROM generate_series(1, 7000) i`);+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, deleted_at)+ SELECT 't-' || i, 'tiny', 'note', 'T' || i, 'body', CASE WHEN i = 1 THEN now() END FROM generate_series(1, 60) i`);+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source)+ SELECT p.id, ci, 'c', 'compiled_truth' FROM pages p+ CROSS JOIN LATERAL generate_series(0, CASE p.source_id WHEN 'sessions' THEN 27 WHEN 'tiny' THEN 2 ELSE 1 END) ci`);+ await engine.executeRaw('ANALYZE pages');+ await engine.executeRaw('ANALYZE content_chunks');+ }, 120_000);++ afterAll(async () => {+ await engine?.disconnect();+ });++ test('a scope of at most SCOPE_CHUNK_SAMPLE_PAGES pages is counted exactly, without soft-deleted pages', async () => {+ const row = await counted(['tiny']);+ expect(Number(row.pages)).toBe(59);+ expect(Number(row.sampled)).toBe(59);+ expect(Number(row.sample_chunks)).toBe(await trueChunks(['tiny']));+ });++ test('a larger scope samples about SCOPE_CHUNK_SAMPLE_PAGES pages and lands within 5% of the true count', async () => {+ for (const ids of [['sessions'], ['notes'], ['sessions', 'tiny']]) {+ const row = await counted(ids);+ const truth = await trueChunks(ids);+ expect(Number(row.sampled)).toBeGreaterThan(SCOPE_CHUNK_SAMPLE_PAGES * 0.5);+ expect(Number(row.sampled)).toBeLessThan(SCOPE_CHUNK_SAMPLE_PAGES * 2.5);+ const estimate = (Number(row.pages) * Number(row.sample_chunks)) / Number(row.sampled);+ expect(Math.abs(estimate - truth) / truth).toBeLessThan(0.05);+ }+ });++ test('the engine routes a source of long pages on its counted chunks, not its page share', async () => {+ const opts: SearchOpts = { embeddingColumn: column, sourceId: 'sessions' };+ const [stats] = await engine.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL);+ const byShare = sourceScope(stats, opts)!;+ const routed = await (engine as unknown as { vectorScope: (o?: SearchOpts) => Promise<VectorScope | undefined> }).vectorScope(opts);+ const truth = await trueChunks(['sessions']);+ expect(byShare.chunks!).toBeLessThan(SCOPE_SCAN_FIRST_MAX_CHUNKS);+ expect(Math.abs(routed!.chunks! - truth) / truth).toBeLessThan(0.05);+ expect(routed!.chunks!).toBeGreaterThan(SCOPE_SCAN_FIRST_MAX_CHUNKS);+ const stmt = (scope: VectorScope) => buildVectorSearchStatement({ dialect: 'pglite', embedding: new Float32Array(1536), limit: 20, offset: 0, opts, scope });+ expect([!!stmt(byShare).indexWalkSql, !!stmt(byShare).scopeScanSql]).toEqual([false, true]);+ expect([!!stmt(routed!).indexWalkSql, !!stmt(routed!).scopeScanSql]).toEqual([true, true]);+ });+});diff --git a/test/search/vector-statement.test.ts b/test/search/vector-statement.test.tsindex 19f159bf55..afb1231f21 100644--- a/test/search/vector-statement.test.ts+++ b/test/search/vector-statement.test.ts@@ -243,6 +243,49 @@ describe('source scope strategy: walk overfetch, walk skip and scope scan', () =expect(sourceScope(stats, {})).toBeUndefined();});+ test('a sampled chunk count replaces the share estimate; an empty sample falls back to it', () => {+ expect(sourceScope(stats, { sourceId: 'sessions' }, { pages: 250, sampled: 125, sample_chunks: 1_200 })).toEqual({ share: 0.25, chunks: 2_400 });+ expect(sourceScope(stats, { sourceId: 'sessions' }, { pages: 7_900, sampled: 416, sample_chunks: 3_922 })).toEqual({ share: 0.25, chunks: 74_480 });+ expect(sourceScope(stats, { sourceId: 'sessions' }, { pages: 0, sampled: 0, sample_chunks: 0 })).toEqual({ share: 0.25, chunks: 50_000 });+ expect(sourceScope({ ...stats, chunk_reltuples: -1 }, { sourceId: 'sessions' }, { pages: 0, sampled: 0, sample_chunks: 0 })).toEqual({ share: 0.25 });+ });++ test('a scope of long pages routes on its counted chunks: walk first with the scan as fallback instead of scan first', () => {+ const estimated = sourceScope(stats, { sourceId: 'sessions' })!;+ const counted = sourceScope(stats, { sourceId: 'sessions' }, { pages: 250, sampled: 250, sample_chunks: 100_000 })!;+ expect(estimated.chunks!).toBeLessThanOrEqual(SCOPE_SCAN_FIRST_MAX_CHUNKS * 2);+ expect(counted.chunks!).toBeGreaterThan(SCOPE_SCAN_FIRST_MAX_CHUNKS);+ expect(counted.chunks!).toBeLessThanOrEqual(SCOPE_SCAN_MAX_CHUNKS);+ const scanFirst = buildVectorSearchStatement({ dialect: 'postgres', embedding: new Float32Array([1, 0, 0]), limit: 10, offset: 0, opts: { embeddingColumn: indexedColumn, sourceId: 'sessions' }, scope: { share: 0.25, chunks: SCOPE_SCAN_FIRST_MAX_CHUNKS } });+ const walkFirst = buildVectorSearchStatement({ dialect: 'postgres', embedding: new Float32Array([1, 0, 0]), limit: 10, offset: 0, opts: { embeddingColumn: indexedColumn, sourceId: 'sessions' }, scope: counted });+ expect([!!scanFirst.indexWalkSql, !!scanFirst.scopeScanSql]).toEqual([false, true]);+ expect([!!walkFirst.indexWalkSql, !!walkFirst.scopeScanSql]).toEqual([true, true]);+ expect(walkFirst.scopeScanSql).toBe(scanFirst.scopeScanSql!);+ });++ test('the loader counts chunks only for scopes under SCOPE_SCAN_MAX_SHARE, once a minute per scope, and falls back on a failed count', async () => {+ const asked: string[][] = [];+ const scope = vectorScopeLoader(async () => [stats], async ids => { asked.push(ids); return [{ pages: 250, sampled: 250, sample_chunks: 90_000 }]; });+ expect(await scope({ sourceIds: ['notes'] })).toEqual({ share: 0.7, chunks: 140_000 });+ expect(asked).toEqual([]);+ expect(await scope({ sourceId: 'sessions' })).toEqual({ share: 0.25, chunks: 90_000 });+ expect(await scope({ sourceIds: ['sessions', 'sessions'] })).toEqual({ share: 0.25, chunks: 90_000 });+ expect(asked).toEqual([['sessions']]);+ expect((await scope({ sourceIds: ['small', 'sessions'] }))?.chunks).toBe(90_000);+ expect((await scope({ sourceIds: ['sessions', 'small'] }))?.chunks).toBe(90_000);+ expect(asked).toEqual([['sessions'], ['small', 'sessions']]);+ const now = performance.now();+ const clock = spyOn(performance, 'now').mockReturnValue(now + 61_000);+ try {+ await scope({ sourceId: 'sessions' });+ expect(asked).toHaveLength(3);+ } finally {+ clock.mockRestore();+ }+ const failing = vectorScopeLoader(async () => [stats], async () => { throw new Error('canceling statement due to statement timeout'); });+ expect(await failing({ sourceId: 'sessions' })).toEqual({ share: 0.25, chunks: 50_000 });+ });+test('no scope or no statistics leaves the walk on', () => {expect(sourceScopeShare(stats, {})).toBeUndefined();expect(sourceScopeShare(stats, { sourceIds: [] })).toBeUndefined();