Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): raise hnsw.ef_search to match the vector candidate request (#3613)
Garry Tan42f810c4060c
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex f085ecfb76..355c139378 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -39,6 +39,7 @@ import {} from './search/recency-decay.ts';import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchExhausted } from './audit/batch-retry-audit.ts';import { runMigrations } from './migrate.ts';+import { hnswEfSearchFor } from './vector-index.ts';import { PGLITE_SCHEMA_SQL, getPGLiteSchema } from './pglite-schema.ts';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';import { DELETE_BATCH_SIZE } from './engine-constants.ts';@@ -2166,7 +2167,13 @@ export class PGLiteEngine implements BrainEngine {modalityFilter = `AND cc.modality = 'text'`;}- const { rows } = await this.db.query(+ // hnsw.ef_search: an HNSW scan returns at most ef_search rows (default+ // 40), so LIMIT $2 past 40 was silently unreachable — see hnswEfSearchFor.+ // SET LOCAL semantics need a transaction (PGLite autocommits bare+ // queries); scoping it locally keeps the engine's single session clean.+ const { rows } = await this.db.transaction(async (tx) => {+ await tx.query(`SELECT set_config('hnsw.ef_search', $1, true)`, [String(hnswEfSearchFor(innerLimit))]);+ return tx.query(`WITH hnsw_candidates AS (SELECTp.slug, p.id as page_id, p.title, p.type, p.source_id, p.updated_at,@@ -2215,7 +2222,8 @@ export class PGLiteEngine implements BrainEngine {LIMIT $3OFFSET $4`,params- );+ );+ });return (rows as Record<string, unknown>[]).map(rowToSearchResult);}diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex f99b3eec1f..ca3ff9cdc7 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -48,7 +48,7 @@ import { sanitizeForJsonb, buildLinkRows, buildTimelineRows, buildTakeRows } froimport { runMigrations } from './migrate.ts';import { SCHEMA_SQL } from './schema-embedded.ts';import { verifySchema } from './schema-verify.ts';-import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes } from './vector-index.ts';+import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, hnswEfSearchFor } from './vector-index.ts';import {normalizeEngineColumn,buildVectorCastFragment,@@ -2299,8 +2299,14 @@ export class PostgresEngine implements BrainEngine {// RLS scope binding + search-only timeout. alwaysTransaction: master// already wrapped this in sql.begin() for the SET LOCAL; flag off is// identical to that wrap, flag on adds set_config in the same tx.+ //+ // hnsw.ef_search: an HNSW scan returns at most ef_search rows (default+ // 40), so the inner CTE's LIMIT past 40 was silently unreachable — see+ // hnswEfSearchFor. Transaction-local (is_local=true); non-HNSW plans+ // (seq scan, or corpora without the index) ignore the GUC.const rows = await this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {await tx`SET LOCAL statement_timeout = '8s'`;+ await tx`SELECT set_config('hnsw.ef_search', ${String(hnswEfSearchFor(innerLimit))}, true)`;return await tx.unsafe(rawQuery, params as Parameters<typeof tx.unsafe>[1]);}, { alwaysTransaction: true });return rows.map(rowToSearchResult);diff --git a/src/core/vector-index.ts b/src/core/vector-index.tsindex 52fb67092f..f584fafb50 100644--- a/src/core/vector-index.ts+++ b/src/core/vector-index.ts@@ -43,6 +43,28 @@ export function applyChunkEmbeddingIndexPolicy(sql: string, dims: number): strinreturn sql.replaceAll(CHUNK_EMBEDDING_HNSW_INDEX, chunkEmbeddingIndexSql(dims));}+/** pgvector defaults hnsw.ef_search to 40; the GUC's hard ceiling is 1000. */+export const HNSW_EF_SEARCH_DEFAULT = 40;+export const HNSW_EF_SEARCH_MAX = 1000;++/**+ * `hnsw.ef_search` value for a vector search that wants `candidateLimit`+ * candidates back.+ *+ * An HNSW index scan returns at most `hnsw.ef_search` rows (default 40)+ * no matter what the query's LIMIT asks for — the GUC sizes the scan's+ * candidate list, so it caps the row count before LIMIT is even applied.+ * Both engines' searchVector ask the inner CTE for+ * `offset + max(limit*5, 100)` candidates; without raising the GUC the+ * pool silently truncates at ~40 and everything downstream (per-page+ * collapse, RRF fusion, rerankers) operates on a fraction of the pool it+ * was designed for. Shared helper keeps postgres + pglite in lockstep.+ */+export function hnswEfSearchFor(candidateLimit: number): number {+ const wanted = Math.ceil(candidateLimit);+ return Math.min(Math.max(wanted, HNSW_EF_SEARCH_DEFAULT), HNSW_EF_SEARCH_MAX);+}+// ---------------------------------------------------------------------------// v0.30.1 Lifecycle Manager (Fix 5)// ---------------------------------------------------------------------------diff --git a/test/e2e/vector-ef-search-postgres.test.ts b/test/e2e/vector-ef-search-postgres.test.tsnew file mode 100644index 0000000000..e5748722d7--- /dev/null+++ b/test/e2e/vector-ef-search-postgres.test.ts@@ -0,0 +1,78 @@+/**+ * Postgres half of the hnsw.ef_search regression — see+ * test/vector-ef-search.test.ts for the full rationale (PGLite half + the+ * hnswEfSearchFor unit tests) and test/helpers/ef-search-fixture.ts for the+ * fixture-geometry notes.+ *+ * Engine-specific mechanics:+ * - Planner forcing happens via `ALTER DATABASE … SET enable_seqscan/+ * enable_sort = off` because the engine runs searches on a connection+ * pool: a session-level SET would land on one pooled connection while+ * searchVector's transaction may run on another. Database-level settings+ * apply at connection start, so a fresh engine (fresh pool) created after+ * the ALTER sees them deterministically. afterAll RESETs both.+ * - Gated on DATABASE_URL like the other e2e files.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';+import {+ SEARCH_LIMIT,+ prngUnitVector,+ embeddingDims,+ seedCorpus,+} from '../helpers/ef-search-fixture.ts';++const SKIP = !hasDatabase();+const describeDb = SKIP ? describe.skip : describe;++describeDb('searchVector candidate pool vs hnsw.ef_search (Postgres)', () => {+ let searchEngine: PostgresEngine | null = null;+ let quotedDb: string | null = null;++ beforeAll(async () => {+ const seedEngine = await setupDB();+ const dim = await embeddingDims(seedEngine);+ await seedCorpus(seedEngine, dim);++ const rows = await seedEngine.executeRaw<{ db: string }>(+ `SELECT current_database() AS db`,+ );+ quotedDb = `"${rows[0]!.db.replaceAll('"', '""')}"`;+ await seedEngine.executeRaw(`ALTER DATABASE ${quotedDb} SET enable_seqscan = off`);+ await seedEngine.executeRaw(`ALTER DATABASE ${quotedDb} SET enable_sort = off`);++ // Fresh pool so its connections inherit the database-level GUCs.+ // poolSize is required: without it connect() reuses the module-level+ // singleton pool that setupDB() already opened BEFORE the ALTER, whose+ // connections still carry the default planner GUCs.+ searchEngine = new PostgresEngine();+ await searchEngine.connect({+ database_url: process.env.DATABASE_URL!,+ poolSize: 1,+ });+ }, 120_000);++ afterAll(async () => {+ try {+ if (quotedDb) {+ await getEngine().executeRaw(`ALTER DATABASE ${quotedDb} RESET enable_seqscan`);+ await getEngine().executeRaw(`ALTER DATABASE ${quotedDb} RESET enable_sort`);+ }+ } finally {+ if (searchEngine) await searchEngine.disconnect();+ await teardownDB();+ }+ }, 60_000);++ test('a limit past the ef_search default is honored', async () => {+ const dim = await embeddingDims(searchEngine!);+ const results = await searchEngine!.searchVector(prngUnitVector(0, dim), {+ limit: SEARCH_LIMIT,+ });+ // Pre-fix this was exactly 40 (the hnsw.ef_search default): the HNSW+ // scan exhausted its candidate list long before the inner CTE's LIMIT.+ expect(results.length).toBe(SEARCH_LIMIT);+ }, 60_000);+});diff --git a/test/helpers/ef-search-fixture.ts b/test/helpers/ef-search-fixture.tsnew file mode 100644index 0000000000..f788406461--- /dev/null+++ b/test/helpers/ef-search-fixture.ts@@ -0,0 +1,65 @@+/**+ * Shared fixture for the hnsw.ef_search regression tests+ * (test/vector-ef-search.test.ts + test/e2e/vector-ef-search-postgres.test.ts).+ *+ * Embeddings are seeded-PRNG unit vectors on purpose: structured fixtures+ * (basis vectors, smooth angle gradients) build degenerate HNSW graphs whose+ * greedy search terminates early no matter how high ef_search goes —+ * measured: a basis-vector corpus plateaued at ~34 rows even with+ * ef_search=500. Random geometry keeps the graph connected, so the only+ * cap left is the GUC under test.+ */++import type { BrainEngine } from '../../src/core/engine.ts';+import type { ChunkInput } from '../../src/core/types.ts';++export const CORPUS_SIZE = 150;+export const SEARCH_LIMIT = 100; // MAX_SEARCH_LIMIT — innerLimit becomes 500++/** Deterministic pseudo-random unit vector (LCG-seeded per index). */+export function prngUnitVector(idx: number, dim: number): Float32Array {+ const emb = new Float32Array(dim);+ let x = ((idx + 1) * 2654435761) % 4294967296;+ let norm = 0;+ for (let d = 0; d < dim; d++) {+ x = (1103515245 * x + 12345) % 2147483648;+ const v = (x / 2147483648) * 2 - 1;+ emb[d] = v;+ norm += v * v;+ }+ norm = Math.sqrt(norm);+ for (let d = 0; d < dim; d++) emb[d] /= norm;+ return emb;+}++/** Dims of content_chunks.embedding as created (pgvector typmod = dims). */+export async function embeddingDims(eng: BrainEngine): Promise<number> {+ const rows = await eng.executeRaw<{ dims: number }>(+ `SELECT atttypmod AS dims FROM pg_attribute+ WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding'`,+ );+ const dims = rows[0]?.dims;+ if (!dims || dims < 1) throw new Error(`unexpected embedding typmod: ${dims}`);+ return dims;+}++export async function seedCorpus(eng: BrainEngine, dim: number): Promise<void> {+ for (let i = 0; i < CORPUS_SIZE; i++) {+ const slug = `notes/ef-search-${String(i).padStart(3, '0')}`;+ await eng.putPage(slug, {+ type: 'note',+ title: `ef-search fixture ${i}`,+ compiled_truth: `ef search fixture page ${i}`,+ timeline: '',+ });+ const chunks: ChunkInput[] = [+ {+ chunk_index: 0,+ chunk_text: `ef search fixture page ${i}`,+ chunk_source: 'compiled_truth',+ embedding: prngUnitVector(i, dim),+ },+ ];+ await eng.upsertChunks(slug, chunks);+ }+}diff --git a/test/vector-ef-search.test.ts b/test/vector-ef-search.test.tsnew file mode 100644index 0000000000..78c3b442c2--- /dev/null+++ b/test/vector-ef-search.test.ts@@ -0,0 +1,81 @@+/**+ * Regression: hnsw.ef_search (pgvector default 40) silently caps the vector+ * candidate pool below what searchVector asks for.+ *+ * searchVector's inner CTE requests `offset + max(limit*5, 100)` candidates,+ * but an HNSW index scan returns at most `hnsw.ef_search` rows (default 40) —+ * the GUC sizes the scan's candidate list, so any LIMIT past 40 was+ * unreachable. Measured on this fixture before the fix: 150 matching pages,+ * limit=100 → 40 rows. The fix (hnswEfSearchFor) raises the GUC+ * transaction-locally to match the candidate request.+ *+ * Planner forcing: on a 150-row corpus the planner prefers a seq scan (or a+ * different index + explicit Sort), which bypasses the HNSW cap entirely and+ * would let this test pass without the fix. `enable_seqscan=off` ++ * `enable_sort=off` make the HNSW-ordered scan the only cheap plan — the+ * same forcing technique pgvector's own regression suite uses. Session GUCs+ * persist into the search's transaction; the fix's SET LOCAL is orthogonal+ * to them. Fixture geometry notes: test/helpers/ef-search-fixture.ts.+ *+ * Postgres half: test/e2e/vector-ef-search-postgres.test.ts.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ hnswEfSearchFor,+ HNSW_EF_SEARCH_DEFAULT,+ HNSW_EF_SEARCH_MAX,+} from '../src/core/vector-index.ts';+import {+ SEARCH_LIMIT,+ prngUnitVector,+ embeddingDims,+ seedCorpus,+} from './helpers/ef-search-fixture.ts';++describe('hnswEfSearchFor', () => {+ test('floors at the pgvector default', () => {+ expect(hnswEfSearchFor(0)).toBe(HNSW_EF_SEARCH_DEFAULT);+ expect(hnswEfSearchFor(39)).toBe(HNSW_EF_SEARCH_DEFAULT);+ });++ test('tracks the candidate request past the default', () => {+ expect(hnswEfSearchFor(100)).toBe(100);+ expect(hnswEfSearchFor(500)).toBe(500); // limit=100 → innerLimit 500+ });++ test('caps at the GUC maximum', () => {+ expect(hnswEfSearchFor(5000)).toBe(HNSW_EF_SEARCH_MAX);+ });+});++describe('searchVector candidate pool vs hnsw.ef_search (PGLite)', () => {+ let engine: PGLiteEngine;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const dim = await embeddingDims(engine);+ await seedCorpus(engine, dim);+ // Force the HNSW-ordered plan (see header). Session-level on PGLite's+ // single connection, so it holds for the searches below.+ await engine.executeRaw(`SET enable_seqscan = off`);+ await engine.executeRaw(`SET enable_sort = off`);+ }, 240_000);++ afterAll(async () => {+ await engine.disconnect();+ });++ test('a limit past the ef_search default is honored', async () => {+ const dim = await embeddingDims(engine);+ const results = await engine.searchVector(prngUnitVector(0, dim), {+ limit: SEARCH_LIMIT,+ });+ // Pre-fix this was exactly 40 (the hnsw.ef_search default): the HNSW+ // scan exhausted its candidate list long before the inner CTE's LIMIT.+ expect(results.length).toBe(SEARCH_LIMIT);+ }, 60_000);+});