Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(vector): skip the index walk for type and date filters

time-attack259dfa195da8
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 59b3b44edd..f9893eb7ad 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 only, 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. 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.ts
index dc1d98eb28..eb1e745ede 100644
--- a/src/core/search/vector-statement.ts
+++ b/src/core/search/vector-statement.ts
@@ -31,7 +31,9 @@
* 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.
+ * 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.
*/
import type { SearchOpts } from '../types.ts';
import { hnswIndexExpected } from '../vector-index.ts';
@@ -64,7 +66,7 @@ export interface VectorSearchStatement {
indexed: boolean;
/** True when freshness moved out of the candidate CTE (indexed `embedding`, legacy guard off). */
relaxed: boolean;
- /** Index-walk statement (relaxed variant only), same parameters as `sql`; trusted when `candidate_pool` reaches the window. */
+ /** Index-walk statement (relaxed variant without a type or date filter), same parameters as `sql`; trusted when `candidate_pool` reaches the window. */
indexWalkSql?: string;
}
@@ -120,6 +122,9 @@ 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);
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})
@@ -243,6 +248,6 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): V
innerLimit,
indexed,
relaxed,
- ...(relaxed ? { indexWalkSql: statement(indexWalkCandidates, true) } : {}),
+ ...(relaxed && !narrowed ? { indexWalkSql: statement(indexWalkCandidates, true) } : {}),
};
}
diff --git a/test/search/vector-index-walk.test.ts b/test/search/vector-index-walk.test.ts
index 252e6da2b4..4afd21935f 100644
--- a/test/search/vector-index-walk.test.ts
+++ b/test/search/vector-index-walk.test.ts
@@ -92,8 +92,7 @@ describe('vector index walk (PGLite)', () => {
['remote reader (private-page rule)', { excludePrivate: true }],
['remote reader, limit 50', { excludePrivate: true, limit: 50 }],
['granted sources', { excludePrivate: true, sourceIds: ['default', 'side'] }],
- ['common types', { types: ['note', 'person', 'company'] }],
- ['date range and slug exclusion', { afterDate: '2000-01-01', beforeDate: '2100-01-01', exclude_slugs: ['notes/n-5'] }],
+ ['slug exclusion', { exclude_slugs: ['notes/n-5', 'notes/n-6'] }],
['compiled truth only', { detail: 'low', excludePrivate: true }],
];
diff --git a/test/search/vector-statement.test.ts b/test/search/vector-statement.test.ts
index 92902f0d23..4e7a9f6923 100644
--- a/test/search/vector-statement.test.ts
+++ b/test/search/vector-statement.test.ts
@@ -103,30 +103,33 @@ describe('vector index walk statement', () => {
}
test('orders content_chunks alone and applies page filters and visibility after the key joins', () => {
- const stmt = build({ type: 'note', sourceIds: ['a'], afterDate: '2026-01-01', language: 'typescript', detail: 'low', excludePrivate: true });
+ const stmt = build({ exclude_slugs: ['x'], sourceIds: ['a'], language: 'typescript', detail: 'low', excludePrivate: true });
const walk = stmt.indexWalkSql!;
const ann = annCte(walk);
expect(ann).toContain('FROM content_chunks cc');
expect(ann).not.toMatch(/JOIN|pages|sources|p\./);
expect(ann).toContain(`AND cc.chunk_source = 'compiled_truth'`);
expect(ann).toContain('AND cc.language = $3');
- expect(ann).toContain('AND (cc.model=$6 OR');
+ expect(ann).toContain('AND (cc.model=$5 OR');
expect(ann).not.toContain(MD5);
expect(ann).toContain(`LIMIT $${stmt.innerLimitIdx + 1}::int * 2`);
const candidates = walk.slice(walk.indexOf('hnsw_candidates AS ('), walk.indexOf('scored AS ('));
expect(candidates).toContain('JOIN content_chunks cc ON cc.id = ann.id');
expect(candidates).toContain('JOIN pages p ON p.id = cc.page_id');
- expect(candidates).toContain('AND p.type = $2');
- expect(candidates).toContain('AND p.source_id = ANY($5::text[])');
+ expect(candidates).toContain('AND p.slug != ALL($2::text[])');
+ expect(candidates).toContain('AND p.source_id = ANY($4::text[])');
expect(candidates).toContain(`COALESCE(p.frontmatter->>'visibility'`);
expect(candidates).toContain('ORDER BY ann.distance, ann.id');
expect(candidates).toContain(`LIMIT $${stmt.innerLimitIdx + 1}::int`);
- expect(scoredCte(walk)).toContain('WHERE $6::text IS NULL OR hash_current');
+ expect(scoredCte(walk)).toContain('WHERE $5::text IS NULL OR hash_current');
});
- test('exists only for the relaxed variant and binds the same parameters', () => {
+ test('exists only for the relaxed variant without a type or date filter, and binds the same parameters', () => {
expect(build({ vectorLegacyGuard: true }).indexWalkSql).toBeUndefined();
expect(build({ embeddingColumn: wideColumn }).indexWalkSql).toBeUndefined();
+ for (const narrowing of [{ type: 'note' }, { types: ['note'] }, { afterDate: '2026-01-01' }, { beforeDate: '2026-01-01' }]) {
+ expect(build(narrowing).indexWalkSql).toBeUndefined();
+ }
const pg = build({ excludePrivate: true });
const lite = build({ excludePrivate: true }, 'pglite');
const placeholders = (sql: string) => [...new Set(sql.match(/\$\d+/g))].sort();