Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): the index walk probes chunks and pages by key per ANN row (LHF wave 2 item 7, #6728)
garrytan1303a43be3dc
diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.tsindex 2d63dca342..5084978e89 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -375,8 +375,13 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): V${hashCurrent} AS hash_current,1 - ann.distance AS raw_scoreFROM ann- JOIN content_chunks cc ON cc.id = ann.id- JOIN pages p ON p.id = cc.page_id+ -- Key probes behind OFFSET 0 fences: one chunk and one page lookup per+ -- ANN row, so the plan is bounded by the window whatever the scope+ -- size or page-filter estimate. A plain join let the planner+ -- materialize the whole scope's chunk-page join under the ANN loop+ -- and rescan it per row, spilling past work_mem on large scopes (#6728).+ CROSS JOIN LATERAL (SELECT * FROM content_chunks c WHERE c.id = ann.id OFFSET 0) cc+ CROSS JOIN LATERAL (SELECT * FROM pages pg WHERE pg.id = cc.page_id OFFSET 0) pCROSS JOIN LATERAL (SELECT src.archived FROM sources src WHERE src.id = p.source_id OFFSET 0) sWHERE true${pageFilters.join('\n ')}diff --git a/test/e2e/vector-index-walk-plan-postgres.test.ts b/test/e2e/vector-index-walk-plan-postgres.test.tsnew file mode 100644index 0000000000..68786b28ab--- /dev/null+++ b/test/e2e/vector-index-walk-plan-postgres.test.ts@@ -0,0 +1,45 @@+/**+ * #6728 on Postgres: the index walk reaches chunks and pages through one key+ * probe per ANN row, so no scope-wide chunk-page join is materialized and+ * rescanned under the ANN loop. Same fixture and assertions as the PGLite+ * plan test in test/search/vector-index-walk.test.ts, in a dedicated+ * database so the shared schema keeps its dimensions.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { buildVectorSearchStatement, INDEX_WALK_SETTINGS } from '../../src/core/search/vector-statement.ts';+import type { SearchOpts } from '../../src/core/types.ts';+import { column, planNodes, seedVectorWalkFixture, vec, type PlanNode } from '../helpers/vector-index-walk-fixture.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { hasDatabase } from './helpers.ts';++(hasDatabase() ? describe : describe.skip)('vector index walk key probes (Postgres)', () => {+ let engine: PostgresEngine;+ let close: () => Promise<void>;+ beforeAll(async () => {+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ await seedVectorWalkFixture(engine);+ }, 120_000);+ afterAll(async () => { await close?.(); });++ test('the walk probes chunks and pages by key per ANN row: no scope-wide join is materialized under the ANN loop (#6728)', async () => {+ for (const sourceIds of [['side'], ['tiny', 'side']]) {+ const opts: SearchOpts = { embeddingColumn: column, excludePrivate: true, sourceIds };+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding: vec(11), limit: 20, offset: 0, opts, scope: { share: 0.05 } });+ expect(stmt.indexWalkSql).toBeDefined();+ const plan = await engine.transaction(async tx => {+ for (const [key, value] of Object.entries(INDEX_WALK_SETTINGS)) await tx.executeRaw(`SET LOCAL ${key} = ${value}`);+ const [row] = await tx.executeRaw<{ 'QUERY PLAN': Array<{ Plan: PlanNode }> }>(`EXPLAIN (ANALYZE, FORMAT JSON) ${stmt.indexWalkSql!}`, [...stmt.params]);+ return row!['QUERY PLAN'][0]!.Plan;+ });+ const nodes = planNodes(plan);+ expect(nodes.filter(node => node['Node Type'] === 'Materialize')).toEqual([]);+ expect(nodes.filter(node => node['Join Filter']?.includes('ann.id'))).toEqual([]);+ expect(nodes.find(node => node['Index Name'] === 'idx_chunks_embedding')).toBeDefined();+ for (const index of ['content_chunks_pkey', 'pages_pkey']) {+ expect(nodes.find(node => node['Index Name'] === index && node['Actual Loops']! > 1)).toBeDefined();+ }+ expect(nodes.some(node => node['Index Name'] === 'idx_chunks_page')).toBe(false);+ }+ }, 60_000);+});diff --git a/test/helpers/vector-index-walk-fixture.ts b/test/helpers/vector-index-walk-fixture.tsnew file mode 100644index 0000000000..b1a15e021f--- /dev/null+++ b/test/helpers/vector-index-walk-fixture.ts@@ -0,0 +1,63 @@+/**+ * The vector index walk fixture (8-dim): three sources (one archived), five+ * page types, pages hidden by the private-page rule, quarantined and+ * soft-deleted pages, stale chunk hashes, three chunks per page, and a `tiny`+ * source with 2% of pages. Shared by test/search/vector-index-walk.test.ts+ * (PGLite) and test/e2e/vector-index-walk-plan-postgres.test.ts.+ */+import type { BrainEngine } from '../../src/core/engine.ts';++export const MODEL = 'test:vector-index-walk';+export const DIM = 8;+export const column = { name: 'embedding', type: 'vector' as const, dimensions: DIM, embeddingModel: MODEL };+export const PAGES = 600;++export function vec(seed: number): Float32Array {+ return Float32Array.from({ length: DIM }, (_, d) => Math.sin(seed * (d + 1) * 0.37 + d));+}++export async function seedVectorWalkFixture(engine: Pick<BrainEngine, 'executeRaw'>): Promise<void> {+ 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'), ('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+ // (offset 3 is `derived_from` offset 0 of the same block and source).+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, knowledge_revision, text_projection_revision, chunker_version, deleted_at)+ SELECT 'notes/n-' || i,+ CASE WHEN (i / 20) % 5 = 0 THEN 'side' WHEN (i / 20) % 7 = 3 THEN 'gone' ELSE 'default' END,+ CASE WHEN i % 20 = 1 THEN 'atom' WHEN i % 20 = 2 THEN 'concept' ELSE (ARRAY['note', 'person', 'company', 'meeting', 'note'])[1 + i % 5] END,+ 'Note ' || i, 'body',+ CASE WHEN i % 20 = 0 THEN '{"visibility": "private"}'::jsonb+ WHEN i % 20 = 2 THEN '{"synthesized_by": "dream"}'::jsonb+ WHEN i % 20 = 3 THEN jsonb_build_object('derived_from', 'notes/n-' || (i - 3))+ WHEN i % 31 = 0 THEN '{"quarantine": {"reason": "junk_pattern"}}'::jsonb+ ELSE '{}'::jsonb END,+ '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) {+ const n = Number(page.slug.split('-').at(-1));+ for (let c = 0; c < 3; c++) {+ ids.push(page.id); idx.push(c);+ texts.push(`chunk ${n} ${c}`);+ hashes.push(n % 13 === 0 && c === 0 ? 'stale-hash' : null);+ vectors.push(`[${Array.from(vec(n * 3 + c)).join(',')}]`);+ }+ }+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding)+ SELECT u.page_id, u.ci, u.t, 'compiled_truth', $6, COALESCE(u.h, md5(u.t)), u.v::vector+ FROM unnest($1::int[], $2::int[], $3::text[], $4::text[], $5::text[]) AS u(page_id, ci, t, h, v)`, [ids, idx, texts, hashes, vectors, MODEL]);+ await engine.executeRaw('ANALYZE');+}++export type PlanNode = { 'Node Type': string; 'Index Name'?: string; 'Relation Name'?: string; 'Join Filter'?: string; 'Actual Loops'?: number; Plans?: PlanNode[] };+export const planNodes = (node: PlanNode): PlanNode[] => [node, ...(node.Plans ?? []).flatMap(planNodes)];diff --git a/test/search/vector-index-walk.test.ts b/test/search/vector-index-walk.test.tsindex c76a4e198e..ed5c0372da 100644--- a/test/search/vector-index-walk.test.ts+++ b/test/search/vector-index-walk.test.ts@@ -16,20 +16,12 @@import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import * as vectorPool from '../../src/core/search/vector-pool.ts';-import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, PAGE_SOURCE_STATS_SQL, sourceScope, sourceScopeShare, type PageSourceStats } from '../../src/core/search/vector-statement.ts';+import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, INDEX_WALK_SETTINGS, PAGE_SOURCE_STATS_SQL, sourceScope, sourceScopeShare, type PageSourceStats } from '../../src/core/search/vector-statement.ts';import type { SearchOpts } from '../../src/core/types.ts';--const MODEL = 'test:vector-index-walk';-const DIM = 8;-const column = { name: 'embedding', type: 'vector' as const, dimensions: DIM, embeddingModel: MODEL };-const PAGES = 600;+import { column, planNodes, seedVectorWalkFixture, vec, type PlanNode } from '../helpers/vector-index-walk-fixture.ts';let engine: PGLiteEngine;-function vec(seed: number): Float32Array {- return Float32Array.from({ length: DIM }, (_, d) => Math.sin(seed * (d + 1) * 0.37 + d));-}-/** Rows a statement returns with its window computed exactly (no index scans). */async function exactRows(sql: string, params: unknown[]) {await engine.executeRaw('SET enable_indexscan = off');@@ -47,46 +39,7 @@ beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();- 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'), ('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- // (offset 3 is `derived_from` offset 0 of the same block and source).- await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, knowledge_revision, text_projection_revision, chunker_version, deleted_at)- SELECT 'notes/n-' || i,- CASE WHEN (i / 20) % 5 = 0 THEN 'side' WHEN (i / 20) % 7 = 3 THEN 'gone' ELSE 'default' END,- CASE WHEN i % 20 = 1 THEN 'atom' WHEN i % 20 = 2 THEN 'concept' ELSE (ARRAY['note', 'person', 'company', 'meeting', 'note'])[1 + i % 5] END,- 'Note ' || i, 'body',- CASE WHEN i % 20 = 0 THEN '{"visibility": "private"}'::jsonb- WHEN i % 20 = 2 THEN '{"synthesized_by": "dream"}'::jsonb- WHEN i % 20 = 3 THEN jsonb_build_object('derived_from', 'notes/n-' || (i - 3))- WHEN i % 31 = 0 THEN '{"quarantine": {"reason": "junk_pattern"}}'::jsonb- ELSE '{}'::jsonb END,- '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) {- const n = Number(page.slug.split('-').at(-1));- for (let c = 0; c < 3; c++) {- ids.push(page.id); idx.push(c);- texts.push(`chunk ${n} ${c}`);- hashes.push(n % 13 === 0 && c === 0 ? 'stale-hash' : null);- vectors.push(`[${Array.from(vec(n * 3 + c)).join(',')}]`);- }- }- await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding)- SELECT u.page_id, u.ci, u.t, 'compiled_truth', $6, COALESCE(u.h, md5(u.t)), u.v::vector- FROM unnest($1::int[], $2::int[], $3::text[], $4::text[], $5::text[]) AS u(page_id, ci, t, h, v)`, [ids, idx, texts, hashes, vectors, MODEL]);- await engine.executeRaw('ANALYZE');+ await seedVectorWalkFixture(engine);}, 120_000);afterAll(async () => {@@ -119,6 +72,36 @@ describe('vector index walk (PGLite)', () => {});}+ test('the walk probes chunks and pages by key per ANN row: no scope-wide join is materialized under the ANN loop (#6728)', async () => {+ // A narrow page scope with a large overfetch is what drew the planner to+ // materialize the scope's chunk-page join and rescan it once per ANN row+ // (on a real brain the materialized join spilled past work_mem: ~1 GB of+ // temp reads per search).+ for (const sourceIds of [['side'], ['tiny', 'side']]) {+ const opts: SearchOpts = { embeddingColumn: column, excludePrivate: true, sourceIds };+ const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(11), limit: 20, offset: 0, opts, scope: { share: 0.05 } });+ expect(stmt.indexWalkSql).toBeDefined();+ for (const [key, value] of Object.entries(INDEX_WALK_SETTINGS)) await engine.executeRaw(`SET ${key} = ${value}`);+ let plan: PlanNode;+ try {+ const [row] = await engine.executeRaw<{ 'QUERY PLAN': Array<{ Plan: PlanNode }> }>(`EXPLAIN (ANALYZE, FORMAT JSON) ${stmt.indexWalkSql!}`, [...stmt.params]);+ plan = row['QUERY PLAN'][0].Plan;+ } finally {+ for (const key of Object.keys(INDEX_WALK_SETTINGS)) await engine.executeRaw(`RESET ${key}`);+ }+ const nodes = planNodes(plan);+ expect(nodes.filter(node => node['Node Type'] === 'Materialize')).toEqual([]);+ expect(nodes.filter(node => node['Join Filter']?.includes('ann.id'))).toEqual([]);+ const annRows = nodes.find(node => node['Index Name'] === 'idx_chunks_embedding')!;+ expect(annRows).toBeDefined();+ for (const index of ['content_chunks_pkey', 'pages_pkey']) {+ const probe = nodes.find(node => node['Index Name'] === index && node['Actual Loops']! > 1);+ expect(probe).toBeDefined();+ }+ expect(nodes.some(node => node['Index Name'] === 'idx_chunks_page')).toBe(false);+ }+ });+test('the walk keeps every page filter: no hidden, deleted, archived or out-of-scope page reaches results', async () => {const hits = await engine.searchVector(vec(42), { limit: 50, embeddingColumn: column, excludePrivate: true, sourceIds: ['default', 'side'] });expect(hits).toHaveLength(50);diff --git a/test/search/vector-statement.test.ts b/test/search/vector-statement.test.tsindex 454ebf031f..a7706ccd40 100644--- a/test/search/vector-statement.test.ts+++ b/test/search/vector-statement.test.ts@@ -114,8 +114,8 @@ describe('vector index walk statement', () => {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('CROSS JOIN LATERAL (SELECT * FROM content_chunks c WHERE c.id = ann.id OFFSET 0) cc');+ expect(candidates).toContain('CROSS JOIN LATERAL (SELECT * FROM pages pg WHERE pg.id = cc.page_id OFFSET 0) p');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'`);