Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): scope scan only below 30% of pages; wider scopes keep the share-scaled walk
time-attackec8e694f045f
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 3c69b3c99c..776f667136 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 `scopeShare` and `scopeChunks` (share times chunk reltuples). The walk over-fetches `indexWalkOverfetch(share)` = ceil(2 / share) rows per window slot (2 unscoped or for a whole-brain scope, so that statement is byte-identical), and a share below `INDEX_WALK_MIN_SCOPE_SHARE` (0.04) skips it. `scopeScanSql` (relaxed variant, same parameters) serves a scope under `SCOPE_SCAN_MAX_SHARE` (0.5) of pages with at most `SCOPE_SCAN_MAX_CHUNKS` (60k) estimated chunks: an exact distance scan over the scope's chunks, page filters and visibility applied once per page inside `cc.page_id = ANY(ARRAY(...))` so chunks are always reached through `idx_chunks_page` (an inline join flipped to a sequential scan with the private-page rule), ordering only chunk ids with `(distance) + 0` to keep the index out, then the window joins back for its columns. Up to `SCOPE_SCAN_FIRST_MAX_CHUNKS` (25k) it replaces the walk; above that the walk runs first and the scan answers when the walk comes back short (a scope clustered away from the query). It returns the joined statement's rows (`test/search/vector-index-walk.test.ts`); recall across share buckets on 1024-dim vectors is pinned by `test/e2e/vector-scope-recall-postgres.test.ts`. Missing statistics leave only the unscoped walk and the joined statement. PGLite adds the timeline `stale` column; everything else is byte-identical across dialects. Also exports the extension-version probe and the transaction-local `statement_timeout` SQL the Postgres engine runs. Pinned by `test/search/vector-statement.test.ts`, `test/search/vector-freshness.test.ts` and `test/e2e/vector-plan-real-column-postgres.test.ts`.+- `src/core/search/vector-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-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 6df38012fb..51212c7f60 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -119,7 +119,7 @@ export const INDEX_WALK_MIN_SCOPE_SHARE = 0.04;* 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_MAX_SHARE = 0.3;export const SCOPE_SCAN_FIRST_MAX_CHUNKS = 25_000;export const SCOPE_SCAN_MAX_CHUNKS = 60_000;