Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(doctor): vector_plan warns when vector search misses its HNSW index (#5824)

garrytand97db3059fc9
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index f853f42803..545df4bbd4 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -35,6 +35,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/commands/jobs/authorize-legacy.ts": ["test/e2e/minions-legacy-journey-postgres.test.ts"],
"src/commands/jobs/cancel.ts": ["test/e2e/minions-legacy-journey-postgres.test.ts"],
"src/commands/doctor/checks/legacy-job-authority.ts": ["test/e2e/minions-legacy-journey-postgres.test.ts"],
+ // #5824: the vector-plan doctor check EXPLAINs the real searchVector statement.
+ "src/commands/doctor/checks/vector-plan.ts": ["test/e2e/vector-plan-real-column-postgres.test.ts", "test/e2e/doctor-json-golden.test.ts"],
// Fix wave 5 #5401: projection drain CLI and the budgeted resident drain.
"src/commands/projections.ts": ["test/e2e/projection-drain-postgres.test.ts", "test/e2e/fix-wave-5-integration.test.ts"],
"src/core/persistence/consumer.ts": ["test/e2e/projection-drain-postgres.test.ts"],
@@ -112,6 +114,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/projection-statistics-postgres.test.ts",
"test/e2e/search-query-contract-postgres.test.ts",
"test/e2e/vector-candidate-safety-postgres.test.ts",
+ "test/e2e/vector-plan-real-column-postgres.test.ts",
"test/e2e/projection-readiness-currency.test.ts",
"test/e2e/chunk-canonical-text-privacy.test.ts",
"test/e2e/engine-content-privacy.test.ts",
@@ -349,6 +352,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/postgres-engine-disconnect-idempotency.test.ts",
"test/e2e/db-singleton-shared-recovery.test.ts",
"test/e2e/postgres-reconnect-singleton.test.ts",
+ // #5824: searchVector + explainVectorSearch plan proof.
+ "test/e2e/vector-candidate-safety-postgres.test.ts",
+ "test/e2e/vector-plan-real-column-postgres.test.ts",
],
// PGLite bootstrap path + parity guard.
"src/core/pglite-engine.ts": [
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index ebef87d566..70d92b0b20 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -273,6 +273,7 @@ export const timelineHistoryEntry: DoctorEntry = {
'unbound_source',
'writer_version',
'self_capture',
+ 'vector_plan',
'stale_embedding_effects',
'extractor_facts_expired',
],
diff --git a/src/commands/doctor/checks/vector-plan.ts b/src/commands/doctor/checks/vector-plan.ts
new file mode 100644
index 0000000000..63b615cbd3
--- /dev/null
+++ b/src/commands/doctor/checks/vector-plan.ts
@@ -0,0 +1,142 @@
+/**
+ * vector_plan (#5824): EXPLAINs (no ANALYZE) the statement `searchVector`
+ * would run for the active embedding column, through the same builder,
+ * scoped read transaction and scan settings (PostgresEngine.explainVectorSearch),
+ * and warns when an HNSW-indexed column's plan does not use its HNSW index.
+ * A sequential scan there can push vector candidates past the 8 s budget, and
+ * hybrid search then answers from the keyword arm alone.
+ *
+ * Skipped on PGLite, on columns wider than pgvector's HNSW cap (exact scan by
+ * design) and below 10,000 embedded chunks (`pg_class.reltuples`; a seq scan
+ * is the right plan for a small brain). The legacy guard rollback is reported
+ * as configured, because a running service only picks it up on restart.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { PostgresEngine } from '../../../core/postgres-engine.ts';
+import type { ResolvedColumn } from '../../../core/types.ts';
+import type { Check } from '../../doctor.ts';
+import { hnswIndexExpected } from '../../../core/vector-index.ts';
+import { readContentChunksColumnDim } from '../../../core/embedding-dim-check.ts';
+import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../../../core/config.ts';
+import { resolveEmbeddingColumn } from '../../../core/search/embedding-column.ts';
+import { readVectorLegacyGuard, VECTOR_LEGACY_GUARD_ENV, VECTOR_LEGACY_GUARD_KEY } from '../../../core/search/vector-legacy-guard.ts';
+
+const NAME = 'vector_plan';
+const DOCS = 'docs/guides/troubleshooting.md#hybrid-search-returns-only-keyword-hits';
+export const VECTOR_PLAN_MIN_CHUNKS = 10_000;
+const STALE_SAMPLE = 5_000;
+const STALE_WARN = 0.05;
+
+interface PlanNode { 'Node Type'?: string; 'Index Name'?: string; 'Relation Name'?: string; Plans?: PlanNode[] }
+
+function planNodes(node: PlanNode | undefined, out: PlanNode[] = []): PlanNode[] {
+ if (!node) return out;
+ out.push(node);
+ for (const child of node.Plans ?? []) planNodes(child, out);
+ return out;
+}
+
+/** Scan nodes over content_chunks, e.g. `Index Scan using idx_chunks_embedding` or `Seq Scan`. */
+function describeChunkScans(nodes: PlanNode[]): string[] {
+ return nodes.filter(n => n['Relation Name'] === 'content_chunks')
+ .map(n => n['Index Name'] ? `${n['Node Type']} using ${n['Index Name']}` : String(n['Node Type']));
+}
+
+export interface VectorPlanOpts {
+ /** Active column override (tests); production resolves it from the brain config. */
+ column?: ResolvedColumn;
+ env?: NodeJS.ProcessEnv;
+}
+
+export async function vectorPlanCheck(engine: BrainEngine, opts: VectorPlanOpts = {}): Promise<Check> {
+ if (engine.kind !== 'postgres') {
+ return { name: NAME, status: 'ok', message: 'Skipped: PGLite runs vector search in-process; the plan check applies to Postgres brains.',
+ details: { outcome: 'skipped', reason: 'pglite' } };
+ }
+ try {
+ const cfg = await loadConfigWithEngine(engine).catch(() => loadConfig());
+ const guard = readVectorLegacyGuard(cfg, opts.env);
+ const resolved = opts.column ?? resolveEmbeddingColumn(undefined, cfg ?? { engine: 'postgres' } as GBrainConfig);
+ const actual = await readContentChunksColumnDim(engine, resolved.name);
+ const column: ResolvedColumn = { ...resolved, dimensions: actual.dims ?? resolved.dimensions };
+ const base = { column: column.name, column_type: `${column.type}(${column.dimensions})`, docs: DOCS };
+ if (!hnswIndexExpected(column.type, column.dimensions)) {
+ return { name: NAME, status: 'ok', message: `Skipped: ${column.name} is ${column.type}(${column.dimensions}), wider than pgvector's HNSW cap, so vector search is an exact scan by design.`,
+ details: { ...base, outcome: 'skipped', reason: 'not_indexed' } };
+ }
+ const embedded = await embeddedChunkEstimate(engine, column.name);
+ if (embedded < VECTOR_PLAN_MIN_CHUNKS) {
+ return { name: NAME, status: 'ok', message: `Skipped: about ${embedded} embedded chunk(s) in ${column.name}; below ${VECTOR_PLAN_MIN_CHUNKS} a sequential scan is the right plan.`,
+ details: { ...base, outcome: 'skipped', reason: 'small_brain', embedded_chunks_estimate: embedded } };
+ }
+
+ const indexes = await engine.executeRaw<{ name: string; valid: boolean }>(
+ `SELECT c.relname AS name, i.indisvalid AS valid
+ FROM pg_index i
+ JOIN pg_class c ON c.oid = i.indexrelid
+ JOIN pg_am am ON am.oid = c.relam
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = to_regclass('content_chunks') AND am.amname = 'hnsw' AND a.attname = $1
+ ORDER BY c.relname`, [column.name]);
+ const plan = await (engine as PostgresEngine).explainVectorSearch(new Float32Array(column.dimensions), {
+ limit: 20, embeddingColumn: column, vectorLegacyGuard: guard.enabled,
+ });
+ const scans = describeChunkScans(planNodes(plan.Plan as PlanNode));
+ const usesHnsw = indexes.some(index => scans.some(scan => scan.endsWith(` using ${index.name}`)));
+ const stale = column.name === 'embedding' ? await staleFraction(engine, embedded) : null;
+ const staleNote = stale && stale.fraction > STALE_WARN
+ ? ` About ${(stale.fraction * 100).toFixed(1)}% of sampled embedded chunks have stale text; run \`gbrain embed --stale\` to re-embed them.` : '';
+ const details = { ...base, embedded_chunks_estimate: embedded, plan_scans: scans, hnsw_indexes: indexes, legacy_guard: guard,
+ stale_fraction: stale?.fraction ?? null, stale_sampled_chunks: stale?.sampled ?? null };
+
+ if (guard.enabled) {
+ const via = guard.via === 'env' ? `${VECTOR_LEGACY_GUARD_ENV} (unset it)` : `${VECTOR_LEGACY_GUARD_KEY} (gbrain config set ${VECTOR_LEGACY_GUARD_KEY} false)`;
+ return { name: NAME, status: 'warn', details: { ...details, outcome: 'legacy_guard' },
+ message: `Vector legacy guard configured via ${via}; active after restarting the owning service (serve, autopilot, workers). `
+ + `It restores the pre-#5824 statement, which large brains plan as ${scans.join(', ') || 'a sequential scan'}. `
+ + `Legacy guard active; remove after upgrade unless it rolled back a regression, then restart the service. See ${DOCS}.${staleNote}` };
+ }
+ if (usesHnsw) {
+ return { name: NAME, status: 'ok', details: { ...details, outcome: 'ok' },
+ message: `Vector search uses its HNSW index (${scans.join(', ')}) on ${column.name}.${staleNote}` };
+ }
+ const indexState = indexes.length === 0
+ ? `no HNSW index exists on content_chunks.${column.name}; create it on the brain host: CREATE INDEX CONCURRENTLY idx_chunks_${column.name} ON content_chunks USING hnsw (${column.name} ${column.type}_cosine_ops)`
+ : indexes.every(index => !index.valid)
+ ? `${indexes.map(index => index.name).join(', ')} is INVALID (an interrupted build); rebuild it on the brain host: REINDEX INDEX CONCURRENTLY ${indexes[0].name}`
+ : `${indexes.filter(index => index.valid).map(index => index.name).join(', ')} exists and is valid`;
+ return { name: NAME, status: 'warn', details: { ...details, outcome: 'index_unused' },
+ message: `Vector search plan does not use the HNSW index on content_chunks.${column.name}: the planner chose ${scans.join(', ') || 'a non-index plan'}. `
+ + `Risk: vector candidates may hit the 8 s budget on large brains, and hybrid search then returns keyword-only results (vector_candidates_incomplete). `
+ + `Index: ${indexState}. Fix: upgrade gbrain on the brain host (gbrain upgrade) and rerun gbrain doctor; `
+ + `if this started right after an upgrade, roll back with ${VECTOR_LEGACY_GUARD_KEY} and report it on #5824. See ${DOCS}.${staleNote}` };
+ } catch (error) {
+ return { name: NAME, status: 'warn', message: `Vector plan could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,
+ details: { health: 'unknown', docs: DOCS } };
+ }
+}
+
+/** Embedded rows from planner statistics; a never-analyzed table falls back to a count bounded at the threshold. */
+async function embeddedChunkEstimate(engine: BrainEngine, column: string): Promise<number> {
+ const [stats] = await engine.executeRaw<{ reltuples: number; null_frac: number | null }>(
+ `SELECT c.reltuples::float8 AS reltuples, s.null_frac::float8 AS null_frac
+ FROM pg_class c
+ LEFT JOIN pg_stats s ON s.schemaname = 'public' AND s.tablename = 'content_chunks' AND s.attname = $1
+ WHERE c.oid = to_regclass('content_chunks')`, [column]);
+ if (stats && stats.reltuples >= 0 && stats.null_frac !== null) return Math.round(stats.reltuples * (1 - stats.null_frac));
+ const [bounded] = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM (SELECT 1 FROM content_chunks WHERE "${column.replaceAll('"', '""')}" IS NOT NULL LIMIT ${VECTOR_PLAN_MIN_CHUNKS}) bounded`);
+ return Number(bounded?.n ?? 0);
+}
+
+/** Share of embedded chunks whose text changed after embedding, from a page sample of about 5,000 rows. */
+async function staleFraction(engine: BrainEngine, embedded: number): Promise<{ fraction: number; sampled: number } | null> {
+ const percent = Math.min(100, Math.max(0.01, (STALE_SAMPLE * 2 * 100) / Math.max(embedded, 1)));
+ const [row] = await engine.executeRaw<{ sampled: number; stale: number }>(
+ `SELECT count(*)::int AS sampled,
+ (count(*) FILTER (WHERE embedded_text_hash IS NOT NULL AND embedded_text_hash <> md5(chunk_text)))::int AS stale
+ FROM (SELECT embedded_text_hash, chunk_text FROM content_chunks TABLESAMPLE SYSTEM (${percent.toFixed(4)})
+ WHERE embedding IS NOT NULL LIMIT ${STALE_SAMPLE}) sampled`);
+ if (!row || !row.sampled) return null;
+ return { fraction: row.stale / row.sampled, sampled: row.sampled };
+}
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index 0622791c93..0a3c13aa67 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -142,6 +142,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
instruction: 'Quarantine the listed corpus files by hand with the commands in docs/guides/repair.md#quarantine-self-captured-corpus-files; nothing is deleted automatically.',
run: async engine => (await import('./checks/self-capture.ts')).selfCaptureCheck(engine),
},
+ {
+ id: 'vector_plan', resolution: 'operator', registration: 'wave',
+ count: d => (d.outcome === 'index_unused' || d.outcome === 'legacy_guard' ? 1 : 0),
+ impact: 'Vector search on the active embedding column does not use its HNSW index, so vector candidates can time out and hybrid search falls back to keyword hits',
+ instruction: 'Upgrade gbrain on the brain host and rerun `gbrain doctor`; check the HNSW index state doctor reports; remove `search.vector_legacy_guard` / GBRAIN_VECTOR_LEGACY_GUARD unless it rolled back a regression, then restart the owning service (docs/guides/troubleshooting.md#hybrid-search-returns-only-keyword-hits).',
+ run: async engine => (await import('./checks/vector-plan.ts')).vectorPlanCheck(engine),
+ },
{
id: 'stale_embedding_effects', resolution: 'repair', registration: 'wave',
count: d => Number(d.stale_effects ?? 0),
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index ad12770464..8356c51ff5 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -210,6 +210,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'persistence_request_growth',
'persistence_request_indexes',
'stale_embedding_effects',
+ 'vector_plan',
'writer_version',
'pgbouncer_prepare',
'pglite_data_dir',
diff --git a/test/e2e/vector-plan-real-column-postgres.test.ts b/test/e2e/vector-plan-real-column-postgres.test.ts
new file mode 100644
index 0000000000..725a3a5660
--- /dev/null
+++ b/test/e2e/vector-plan-real-column-postgres.test.ts
@@ -0,0 +1,368 @@
+/**
+ * #5824 plan proof on the real `embedding` column. The content-freshness test
+ * (`embedded_text_hash = md5(chunk_text)`) has no planner statistics; inside
+ * the HNSW candidate CTE Postgres estimated it at 0.5%, dropped
+ * idx_chunks_embedding for a sequential scan, and the vector arm hit its 8 s
+ * deadline on large brains. EXPLAIN is the discriminator, not latency:
+ *
+ * 1. precondition: the pre-fix guard placement (the legacy-guard variant,
+ * byte-for-byte the guard 3a284ae emitted) does NOT use the index on this
+ * fixture, so an undersized fixture fails loudly instead of passing;
+ * 2. the statement searchVector emits now uses idx_chunks_embedding, through
+ * the same tx.unsafe path, scoped read transaction and scan settings
+ * (PostgresEngine.explainVectorSearch), across a filter matrix incl. RLS;
+ * 3. stale-heavy pools escalate or fall back exactly instead of underfilling;
+ * 4. doctor `vector_plan` reports each outcome.
+ *
+ * Runs in a dedicated 64-dim database created on the E2E server and dropped in
+ * afterAll, so the shared 1536-dim schema is untouched.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import postgres from '#postgres';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import { refreshProjectionStatistics } from '../../src/core/search/projection-statistics.ts';
+import { buildVectorSearchStatement } from '../../src/core/search/vector-statement.ts';
+import * as vectorPool from '../../src/core/search/vector-pool.ts';
+import type { VectorPoolAttempt, VectorPoolBatch } from '../../src/core/search/vector-pool.ts';
+import { vectorPlanCheck } from '../../src/commands/doctor/checks/vector-plan.ts';
+import type { SearchOpts } from '../../src/core/types.ts';
+import { hasDatabase } from './helpers.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+
+const DIM = 64;
+const MODEL = 'openai:text-embedding-3-small';
+// Fixture size, measured once on PostgreSQL 16.15 + pgvector 0.8.7 with
+// ANALYZE'd statistics: the fixed statement switches to idx_chunks_embedding
+// at about 2,000 chunks while the pre-fix guard never does. 3,000 pages x 4
+// chunks = 12,000 keeps a 6x margin and clears doctor's 10,000-chunk floor.
+// Re-measure (scale PAGES until the precondition holds) when a Postgres or
+// pgvector upgrade moves the flip point.
+const PAGES = 3_000;
+const column = { name: 'embedding', type: 'vector' as const, dimensions: DIM, embeddingModel: MODEL };
+const query = new Float32Array(DIM).map((_, i) => Math.sin(i * 1.7) * 0.5);
+type PoolMeta = Parameters<NonNullable<SearchOpts['onVectorPoolMeta']>>[0];
+
+const adminUrl = process.env.GBRAIN_PGBOUNCER_DIRECT_URL ?? process.env.DATABASE_URL ?? '';
+const dbName = `gbrain_test_vector_plan_${randomUUID().replaceAll('-', '')}`;
+const role = `gbrain_vector_plan_${randomUUID().replaceAll('-', '').slice(0, 12)}`;
+let admin: ReturnType<typeof postgres> | undefined;
+let seedEngine: PostgresEngine;
+let engine: PostgresEngine;
+const statements: Array<{ sql: string; params: unknown[] }> = [];
+const originalPool = vectorPool.searchVectorPool;
+let poolSpy: ReturnType<typeof spyOn> | undefined;
+
+function usesIndex(plan: unknown): boolean {
+ return JSON.stringify(plan).includes('"Index Name":"idx_chunks_embedding"');
+}
+
+function scans(plan: unknown): string {
+ return JSON.stringify(plan).match(/"Node Type":"[^"]+"/g)?.join(' > ') ?? '';
+}
+
+async function versions(): Promise<string> {
+ const [row] = await engine.executeRaw<{ pg: string; vector: string }>(
+ `SELECT current_setting('server_version') AS pg, (SELECT extversion FROM pg_extension WHERE extname = 'vector') AS vector`);
+ return `PostgreSQL ${row.pg}, pgvector ${row.vector}`;
+}
+
+/** Records each `run` attempt and the pool counts it returned. */
+function spyAttempts(): Array<VectorPoolAttempt & { batch?: VectorPoolBatch }> {
+ const attempts: Array<VectorPoolAttempt & { batch?: VectorPoolBatch }> = [];
+ poolSpy = spyOn(vectorPool, 'searchVectorPool').mockImplementation((limit, initial, iterative, indexed, kind, run, hasMore, onMeta) =>
+ originalPool(limit, initial, iterative, indexed, kind, async attempt => {
+ const record: VectorPoolAttempt & { batch?: VectorPoolBatch } = { ...attempt };
+ attempts.push(record);
+ record.batch = await run(attempt);
+ return record.batch;
+ }, hasMore, onMeta));
+ return attempts;
+}
+
+/** A cluster of `count` chunks along the (e_a, e_b) arc at angle i * step, closer to e_a than any background row. */
+async function seedCluster(prefix: string, count: number, axes: [number, number], step: number, row: (i: number) => { hash: 'current' | 'stale'; type?: string }) {
+ const values = Array.from({ length: count }, (_, i) => row(i));
+ await seedEngine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)
+ SELECT '${prefix}-' || i, 'default', t.type, '${prefix} ' || i, 'cluster', '00000000-0000-4000-8000-000000000001'::uuid,
+ '00000000-0000-4000-8000-000000000001'::uuid, 4
+ FROM unnest($1::text[]) WITH ORDINALITY AS t(type, n), LATERAL (SELECT n - 1 AS i) idx`, [values.map(v => v.type ?? 'note')]);
+ await seedEngine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding)
+ SELECT p.id, 0, 'cluster text ' || p.slug, 'compiled_truth', '${MODEL}',
+ CASE WHEN h.stale = 'stale' THEN md5('text before the edit') ELSE md5('cluster text ' || p.slug) END,
+ (SELECT array_agg(CASE WHEN d = ${axes[0]} THEN cos(a) WHEN d = ${axes[1]} THEN sin(a) ELSE 0 END ORDER BY d)::real[]::vector
+ FROM generate_series(1, ${DIM}) d)
+ FROM pages p
+ JOIN unnest($1::text[]) WITH ORDINALITY AS h(stale, n) ON p.slug = '${prefix}-' || (h.n - 1)
+ CROSS JOIN LATERAL (SELECT (h.n - 1) * ${step} AS a) ang`, [values.map(v => v.hash)]);
+ await seedEngine.executeRaw('ANALYZE content_chunks');
+ await seedEngine.executeRaw('ANALYZE pages');
+}
+
+function axis(d: number): Float32Array {
+ const v = new Float32Array(DIM);
+ v[d - 1] = 1;
+ return v;
+}
+
+(hasDatabase() ? describe : describe.skip)('#5824 vector plan on the real embedding column (Postgres)', () => {
+ beforeAll(async () => {
+ assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);
+ admin = postgres(adminUrl, { max: 1, prepare: false });
+ try {
+ await admin.unsafe(`CREATE DATABASE ${dbName}`);
+ } catch (error) {
+ throw new Error(`Lane A plan test needs CREATEDB on the E2E server; run via \`bun run ci:local\`. The connecting role needs CREATEDB `
+ + `and permission to CREATE EXTENSION vector in the new database (${error instanceof Error ? error.message : String(error)}).`);
+ }
+ // Default planner costs and parallelism for every session, so the
+ // baseline flip is deterministic regardless of the server's postgresql.conf.
+ await admin.unsafe(`ALTER DATABASE ${dbName} SET max_parallel_workers_per_gather = 2`);
+ for (const [name, value] of [['random_page_cost', '4'], ['seq_page_cost', '1'], ['cpu_tuple_cost', '0.01'], ['cpu_index_tuple_cost', '0.005'],
+ ['cpu_operator_cost', '0.0025'], ['effective_cache_size', "'4GB'"], ['jit', 'off']]) {
+ await admin.unsafe(`ALTER DATABASE ${dbName} SET ${name} = ${value}`);
+ }
+ const url = new URL(adminUrl);
+ url.pathname = `/${dbName}`;
+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIM, env: {} });
+ seedEngine = new PostgresEngine();
+ await seedEngine.connect({ database_url: url.toString(), poolSize: 2 });
+ await seedEngine.initSchema();
+ engine = new PostgresEngine();
+ await engine.connect({ database_url: url.toString(), poolSize: 1 });
+
+ const scoped = engine as unknown as { withScopedReadTransaction: (...args: any[]) => Promise<any> };
+ const original = scoped.withScopedReadTransaction;
+ scoped.withScopedReadTransaction = function (sourceIds, sourceId, fn, options) {
+ return original.call(this, sourceIds, sourceId, (tx: any) => fn(new Proxy(tx, {
+ get(target, key) {
+ if (key !== 'unsafe') return Reflect.get(target, key);
+ return (sql: string, params: unknown[]) => {
+ if (sql.includes('WITH hnsw_candidates')) statements.push({ sql, params: [...params] });
+ return target.unsafe(sql, params);
+ };
+ },
+ })), options);
+ };
+ }, 120_000);
+
+ afterAll(async () => {
+ poolSpy?.mockRestore();
+ await engine?.disconnect();
+ await seedEngine?.disconnect();
+ resetGateway();
+ if (admin) {
+ await admin.unsafe(`DROP DATABASE IF EXISTS ${dbName} WITH (FORCE)`);
+ await admin.unsafe(`DROP ROLE IF EXISTS ${role}`);
+ await admin.end();
+ }
+ }, 60_000);
+
+ afterEach(() => {
+ poolSpy?.mockRestore();
+ poolSpy = undefined;
+ });
+
+ test('doctor skips an empty brain and a small one', async () => {
+ const empty = await vectorPlanCheck(engine, { column });
+ expect(empty).toMatchObject({ name: 'vector_plan', status: 'ok', details: { outcome: 'skipped', reason: 'small_brain', embedded_chunks_estimate: 0 } });
+ await seedEngine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)
+ SELECT 'notes/n-' || i, 'default', 'note', 'Note ' || i, 'body', '00000000-0000-4000-8000-000000000001'::uuid, '00000000-0000-4000-8000-000000000001'::uuid, 4
+ FROM generate_series(0, 99) i`);
+ await seedEngine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding)
+ SELECT p.id, 0, 'chunk ' || p.id, 'compiled_truth', '${MODEL}', md5('chunk ' || p.id), e.v
+ FROM pages p CROSS JOIN LATERAL (SELECT array_agg(random()::real - 0.5)::vector AS v FROM generate_series(1, ${DIM}) WHERE p.id > 0) e`);
+ await seedEngine.executeRaw('ANALYZE content_chunks');
+ const small = await vectorPlanCheck(engine, { column });
+ expect(small).toMatchObject({ status: 'ok', details: { outcome: 'skipped', reason: 'small_brain', embedded_chunks_estimate: 100 } });
+ expect(small.message).toContain('below 10000');
+ await seedEngine.executeRaw('DELETE FROM content_chunks');
+ await seedEngine.executeRaw('DELETE FROM pages');
+ }, 60_000);
+
+ test('the fixture reproduces the pre-fix seq scan, and the emitted statement uses idx_chunks_embedding', async () => {
+ await seedEngine.executeRaw(`INSERT INTO sources (id, name) VALUES ('side', 'side') ON CONFLICT (id) DO NOTHING`);
+ await seedEngine.executeRaw('DROP INDEX IF EXISTS idx_chunks_embedding');
+ await seedEngine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version, effective_date)
+ SELECT 'notes/n-' || i, CASE WHEN i % 10 = 0 THEN 'side' ELSE 'default' END, CASE WHEN i % 5 = 0 THEN 'concept' ELSE 'note' END,
+ 'Note ' || i, 'body', '00000000-0000-4000-8000-000000000001'::uuid, '00000000-0000-4000-8000-000000000001'::uuid, 4,
+ DATE '2024-01-01' + (i % 600)
+ FROM generate_series(0, ${PAGES - 1}) i`);
+ // 99.9% current hashes, 0.1% legacy NULL hashes: the reporter's shape.
+ await seedEngine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding)
+ SELECT p.id, c, 'chunk ' || p.id || ' ' || c, 'compiled_truth', '${MODEL}',
+ CASE WHEN (p.id * 4 + c) % 1000 = 0 THEN NULL ELSE md5('chunk ' || p.id || ' ' || c) END, e.v
+ FROM pages p CROSS JOIN generate_series(0, 3) c
+ CROSS JOIN LATERAL (SELECT array_agg(random()::real - 0.5)::vector AS v FROM generate_series(1, ${DIM}) WHERE p.id > 0 AND c >= 0) e`);
+ await seedEngine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL max_parallel_maintenance_workers = 0');
+ await tx.executeRaw('CREATE INDEX idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops)');
+ });
+ for (const table of ['content_chunks', 'pages', 'sources']) await seedEngine.executeRaw(`ANALYZE ${table}`);
+ await refreshProjectionStatistics(seedEngine);
+
+ const legacy = await engine.explainVectorSearch(query, { limit: 20, embeddingColumn: column, vectorLegacyGuard: true });
+ if (usesIndex(legacy)) {
+ throw new Error(`Precondition failed on ${await versions()}: the pre-fix guard placement already uses idx_chunks_embedding at ${PAGES * 4} chunks, `
+ + `so this fixture cannot discriminate. Re-measure: raise PAGES until the legacy-guard EXPLAIN shows a sequential scan, then pin it here.`);
+ }
+ console.info(JSON.stringify({ metric: 'vector-plan-5824', variant: 'pre-fix guard', plan: scans(legacy) }));
+
+ const start = statements.length;
+ const fixed = await engine.explainVectorSearch(query, { limit: 20, embeddingColumn: column });
+ console.info(JSON.stringify({ metric: 'vector-plan-5824', variant: 'emitted', plan: scans(fixed) }));
+ expect(usesIndex(fixed)).toBe(true);
+
+ const events: PoolMeta[] = [];
+ const hits = await engine.searchVector(query, { limit: 20, embeddingColumn: column, onVectorPoolMeta: meta => events.push(meta) });
+ expect(hits).toHaveLength(20);
+ expect(events).toEqual([]);
+ // The EXPLAIN ran exactly the statement and parameters searchVector sent.
+ const [explained, searched] = statements.slice(start);
+ expect(explained.sql).toBe(`EXPLAIN (FORMAT JSON) ${searched.sql}`);
+ expect(explained.params).toEqual(searched.params);
+ expect(searched.sql).toBe(buildVectorSearchStatement({ dialect: 'postgres', embedding: query, limit: 20, offset: 0, opts: { embeddingColumn: column } }).sql);
+
+ // Diagnostic only: the generic plan (no parameter values), PG16+.
+ const generic = await engine.executeRaw(`EXPLAIN (GENERIC_PLAN, FORMAT JSON) ${searched.sql}`).catch(error => String(error));
+ console.info(JSON.stringify({ metric: 'vector-plan-5824', variant: 'generic plan (diagnostic)', usesIndex: usesIndex(generic) }));
+ }, 60_000);
+
+ test('the indexed path keeps idx_chunks_embedding across common filters and RLS scope binding', async () => {
+ const matrix: Array<[string, SearchOpts]> = [
+ ['default scope', {}],
+ ['sourceIds covering most rows', { sourceIds: ['default', 'side'] }],
+ ['common type', { type: 'note' }],
+ ['wide date range', { afterDate: '2000-01-01', beforeDate: '2100-01-01' }],
+ ];
+ for (const [label, opts] of matrix) {
+ const plan = await engine.explainVectorSearch(query, { limit: 20, embeddingColumn: column, ...opts });
+ expect({ label, uses: usesIndex(plan), plan: scans(plan) }).toMatchObject({ label, uses: true });
+ }
+
+ await seedEngine.executeRaw(`CREATE ROLE ${role} NOLOGIN NOSUPERUSER NOBYPASSRLS`);
+ await seedEngine.executeRaw(`GRANT USAGE ON SCHEMA public TO ${role}`);
+ await seedEngine.executeRaw(`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${role}`);
+ await seedEngine.executeRaw(`CREATE POLICY ${role}_pages ON pages FOR SELECT TO ${role}
+ USING (current_setting('app.scopes', true) = '*' OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')))`);
+ await seedEngine.executeRaw('ALTER TABLE pages ENABLE ROW LEVEL SECURITY');
+ const open = (await seedEngine.executeRaw<{ t: string }>(
+ `SELECT tablename AS t FROM pg_tables WHERE schemaname = current_schema() AND rowsecurity AND tablename <> 'pages'`)).map(row => row.t);
+ for (const table of open) await seedEngine.executeRaw(`CREATE POLICY ${role}_open ON ${table} FOR SELECT TO ${role} USING (true)`);
+ const saved = process.env.GBRAIN_RLS_SCOPE_BINDING;
+ process.env.GBRAIN_RLS_SCOPE_BINDING = '1';
+ try {
+ const plan = await engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL ROLE ${role}`);
+ return (tx as PostgresEngine).explainVectorSearch(query, { limit: 20, embeddingColumn: column, sourceIds: ['default', 'side'] });
+ });
+ expect({ label: 'RLS scope binding', uses: usesIndex(plan), plan: scans(plan) }).toMatchObject({ uses: true });
+ const hits = await engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL ROLE ${role}`);
+ return tx.searchVector(query, { limit: 20, embeddingColumn: column, sourceId: 'side' });
+ });
+ expect(hits).toHaveLength(20);
+ expect(hits.every(hit => hit.source_id === 'side')).toBe(true);
+ } finally {
+ if (saved === undefined) delete process.env.GBRAIN_RLS_SCOPE_BINDING;
+ else process.env.GBRAIN_RLS_SCOPE_BINDING = saved;
+ await seedEngine.executeRaw('ALTER TABLE pages DISABLE ROW LEVEL SECURITY');
+ }
+ }, 60_000);
+
+ test('doctor reports ok, an unused valid index, an INVALID index, and a configured legacy guard', async () => {
+ const ok = await vectorPlanCheck(engine, { column });
+ expect(ok).toMatchObject({ status: 'ok', details: { outcome: 'ok' } });
+ expect(ok.message).toContain('idx_chunks_embedding');
+
+ await engine.executeRaw('SET enable_indexscan = off');
+ try {
+ const unused = await vectorPlanCheck(engine, { column });
+ expect(unused).toMatchObject({ status: 'warn', details: { outcome: 'index_unused' } });
+ expect(unused.message).toContain('does not use the HNSW index');
+ expect(unused.message).toContain('idx_chunks_embedding exists and is valid');
+ expect(unused.message).toContain('8 s budget');
+ expect(unused.message).toContain('search.vector_legacy_guard');
+ } finally {
+ await engine.executeRaw('RESET enable_indexscan');
+ }
+
+ await seedEngine.executeRaw(`UPDATE pg_index SET indisvalid = false WHERE indexrelid = 'idx_chunks_embedding'::regclass`);
+ try {
+ const invalid = await vectorPlanCheck(engine, { column });
+ expect(invalid).toMatchObject({ status: 'warn', details: { outcome: 'index_unused' } });
+ expect(invalid.message).toContain('idx_chunks_embedding is INVALID');
+ expect(invalid.message).toContain('REINDEX INDEX CONCURRENTLY idx_chunks_embedding');
+ } finally {
+ await seedEngine.executeRaw(`UPDATE pg_index SET indisvalid = true WHERE indexrelid = 'idx_chunks_embedding'::regclass`);
+ }
+
+ const viaEnv = await vectorPlanCheck(engine, { column, env: { GBRAIN_VECTOR_LEGACY_GUARD: '1' } });
+ expect(viaEnv).toMatchObject({ status: 'warn', details: { outcome: 'legacy_guard', legacy_guard: { enabled: true, via: 'env' } } });
+ expect(viaEnv.message).toContain('active after restarting the owning service');
+ expect(viaEnv.message).toContain('Legacy guard active; remove after upgrade');
+ await seedEngine.setConfig('search.vector_legacy_guard', 'true');
+ try {
+ const viaConfig = await vectorPlanCheck(engine, { column, env: {} });
+ expect(viaConfig).toMatchObject({ status: 'warn', details: { outcome: 'legacy_guard', legacy_guard: { enabled: true, via: 'config' } } });
+ } finally {
+ await seedEngine.executeRaw(`DELETE FROM config WHERE key = 'search.vector_legacy_guard'`);
+ }
+ }, 60_000);
+
+ test('a window full of stale chunks escalates and fills from current chunks', async () => {
+ // 300 stale chunks nearest e_1, then 30 current ones: the first 100-row
+ // raw window is entirely stale.
+ await seedCluster('stale-wall', 330, [1, 2], 0.0005, i => ({ hash: i < 300 ? 'stale' : 'current' }));
+ const attempts = spyAttempts();
+ const events: PoolMeta[] = [];
+ const hits = await engine.searchVector(axis(1), { limit: 10, embeddingColumn: column, onVectorPoolMeta: meta => events.push(meta) });
+ expect(hits.map(hit => hit.slug)).toEqual(Array.from({ length: 10 }, (_, i) => `stale-wall-${300 + i}`));
+ expect(attempts.map(a => [a.innerLimit, a.exact])).toEqual([[100, false], [400, false]]);
+ expect(attempts[0].batch).toMatchObject({ candidatePool: 100, eligiblePool: 0 });
+ expect(events).toEqual([]);
+ }, 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;
+ capability.vectorIterativeScan = Promise.resolve(false);
+ try {
+ const attempts = spyAttempts();
+ const events: PoolMeta[] = [];
+ const hits = await engine.searchVector(axis(1), { limit: 10, embeddingColumn: column, onVectorPoolMeta: meta => events.push(meta) });
+ expect(attempts.map(a => a.exact)).toEqual([false, true]);
+ expect(hits.map(hit => hit.slug)).toEqual(Array.from({ length: 10 }, (_, i) => `stale-wall-${300 + i}`));
+ expect(events).toEqual([]);
+ } finally {
+ capability.vectorIterativeScan = previous;
+ }
+ }, 60_000);
+
+ test('a short raw window holding stale rows escalates on the fresh count instead of stopping short', async () => {
+ // 3,000 chunks along the e_3 arc; every 30th is type 'rare' (100 rows),
+ // the nearest 60 rare rows stale. hnsw.max_scan_tuples (2,000 on the
+ // first attempt) cuts the filtered walk short with mostly stale rows.
+ await seedCluster('short-window', 3_000, [3, 4], 0.0002, i => ({
+ type: i % 30 === 0 ? 'rare' : 'note', hash: i % 30 === 0 && i / 30 < 60 ? 'stale' : 'current',
+ }));
+ await engine.executeRaw('SET enable_seqscan = off');
+ await engine.executeRaw('SET enable_sort = off');
+ try {
+ const attempts = spyAttempts();
+ const events: PoolMeta[] = [];
+ const hits = await engine.searchVector(axis(3), { limit: 10, type: 'rare', embeddingColumn: column, onVectorPoolMeta: meta => events.push(meta) });
+ const first = attempts[0].batch!;
+ expect(first.candidatePool).toBeLessThan(100);
+ expect(first.eligiblePool!).toBeLessThan(10);
+ expect(first.candidatePool).toBeGreaterThan(first.eligiblePool!);
+ expect(attempts.length).toBeGreaterThan(1);
+ expect(hits).toHaveLength(10);
+ expect(hits.every(hit => Number(hit.slug.split('-').at(-1)) / 30 >= 60)).toBe(true);
+ } finally {
+ await engine.executeRaw('RESET enable_seqscan');
+ await engine.executeRaw('RESET enable_sort');
+ }
+ }, 60_000);
+});
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index f2d51150a4..0bedacedcf 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -655,6 +655,16 @@
"name": "self_capture",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "outcome": "skipped",
+ "reason": "pglite"
+ },
+ "message": "Skipped: PGLite runs vector search in-process; the plan check applies to Postgres brains.",
+ "name": "vector_plan",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index d3975d0980..5c39d39005 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -655,6 +655,16 @@
"name": "self_capture",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "outcome": "skipped",
+ "reason": "pglite"
+ },
+ "message": "Skipped: PGLite runs vector search in-process; the plan check applies to Postgres brains.",
+ "name": "vector_plan",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 3d3b4b6be5..b51b79624d 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -661,6 +661,20 @@
"name": "self_capture",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "column": "embedding",
+ "column_type": "vector(1024)",
+ "docs": "docs/guides/troubleshooting.md#hybrid-search-returns-only-keyword-hits",
+ "embedded_chunks_estimate": 0,
+ "outcome": "skipped",
+ "reason": "small_brain"
+ },
+ "message": "Skipped: about 0 embedded chunk(s) in embedding; below 10000 a sequential scan is the right plan.",
+ "name": "vector_plan",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index cf14433975..4cb784c18b 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -369,6 +369,10 @@
"category": "brain",
"name": "self_capture"
},
+ {
+ "category": "ops",
+ "name": "vector_plan"
+ },
{
"category": "ops",
"name": "stale_embedding_effects"
diff --git a/test/fixtures/goldens/doctor/registry-report-remote.json b/test/fixtures/goldens/doctor/registry-report-remote.json
index 0a4fb8f93e..9f8374ab18 100644
--- a/test/fixtures/goldens/doctor/registry-report-remote.json
+++ b/test/fixtures/goldens/doctor/registry-report-remote.json
@@ -237,6 +237,10 @@
"category": "brain",
"name": "self_capture"
},
+ {
+ "category": "ops",
+ "name": "vector_plan"
+ },
{
"category": "ops",
"name": "stale_embedding_effects"