Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): run filtered HNSW iterative scans in relaxed_order (#6132)

garrytanf7f08506f141
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index 13dbb7aaf1..892e5b44cb 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -91,7 +91,15 @@ written up in [`RETRIEVAL_MAXPOOL_INCIDENT.md`](../incidents/RETRIEVAL_MAXPOOL_I
chunks fill the inner candidate pool, the engines escalate the pool in a
bounded loop (×4 per step, at most 3 escalations). SQL candidate limits and
offsets are independent of `ef_search`; supported pgvector versions use
- strict iterative scans with bounded visits. A filtered short pool is not
+ `relaxed_order` iterative scans with bounded visits (`ef_search` is still
+ sized to the candidate pool). Relaxed order keeps a closer candidate the
+ scan finds after farther ones, which strict order drops, so a selective
+ source or visibility filter fills more of its true neighbours; output order
+ never reaches callers because the inner `ORDER BY distance` and the pooled
+ outer sort re-sort it. `search.hnsw_iterative_scan` (`relaxed_order` |
+ `strict_order` | `off`; env `GBRAIN_HNSW_ITERATIVE_SCAN` wins) restores the
+ older mode without a release; it is latched once per process, so restart
+ serve and autopilot after changing it. A filtered short pool is not
proof that the corpus is exhausted. Postgres may make one exact fallback
inside the remaining eight-second arm budget; PGLite does not pretend that
a JavaScript timeout can cancel its WASM work. Unresolved shortfalls appear
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index cc92c573f2..8186250ad0 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -22,12 +22,14 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/tune-recommendations.ts` — tuning recommendations never propose enabling or tuning unavailable semantic result caching. Mode-reduction suggestions describe payload size, not expansion savings: shipped commands pin expansion independently of the bundle.
-- `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.
+- `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)` sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`).
- `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 }`. 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. 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.
+- `src/core/search/hnsw-iterative-scan.ts` — the pgvector `hnsw.iterative_scan` mode for filtered vector search (#6132 idea): `relaxed_order` by default, `strict_order` or `off` through `GBRAIN_HNSW_ITERATIVE_SCAN` (wins) or `search.hnsw_iterative_scan` (file > DB via loadConfigWithEngine). `resolveHnswIterativeScan(cfg)` latches once per process (hybrid `request.ts` passes it as `SearchOpts.hnswIterativeScan`; engines hand it to `withVectorSettings`), logging once when an override is active. `hnswIterativeScanValueProblem` backs the `config set` refusal through `search/config-values.ts` (`searchConfigValueRefusal`: enum/range rules for `search.*` keys, exit 2 `invalid_params`, nothing written). Pinned by `test/search/hnsw-iterative-scan.test.ts` and the Postgres recall fixture `test/e2e/hnsw-iterative-scan-recall-postgres.test.ts`; bench `scripts/bench/hnsw-iterative-scan.ts`.
+
- `src/core/search/internal-breadth.ts` — `INTERNAL_BREADTH_SEARCH_OPTS` (`autocut: false, adaptiveReturn: false`), the one option object internal callers spread into `hybridSearch` when they need the full ranked set rather than a reader-trimmed one (#5890): think gather (both legs), brainstorm close-set, grade-takes evidence, whoknows and enrich. Pinned by `test/internal-breadth-callers.serial.test.ts`; `eval-contradictions/runner.ts` still inherits both trims.
- `src/core/temporal-grammar.ts` + `src/core/search/time-range.ts` + `src/core/event-dates.ts` + `src/core/search/hybrid/time-scope.ts` — deterministic time expressions (no LLM). `findTimeMentions(text, refDay, direction)` resolves explicit cues only (ISO and written dates, `in/during <Month>`, capitalized bare months, `Qn YYYY`, `in YYYY`, yesterday/today/tomorrow, last/this/next week|weekend|month|year, rolling "past month", seasons, last/this <weekday>, `N units ago`, `in N units`) to inclusive day ranges; quoted spans, plural weekdays and modal "may" never resolve; overlapping matches keep the longest. `parseQueryTimeRange(query, refDay)` returns one range or abstains with `no_cue`, `duration_question` ("how long", "how many days ago/passed/before…") or `multi_role` (two times not joined by and/or/to/through). `extractEventDates(text, observationDay)` returns the observation day plus mentioned dates, resolving relative phrases only against a known observation day and skipping code fences, inline code and URLs. `applyTimeScope(results, range, datesOf, {mode, k, slackDays=2})` is a permutation: `reserved` keeps the top ⌈k/2⌉ in place and fills the rest of k with in-range results; `partition` moves every in-range result first. These are used by the eval-only `--time-scope` arm; no production search path calls them yet. Tests: `test/time-range-parse.test.ts` (published LongMemEval time-range examples as goldens), `test/time-scope-stage.test.ts`.
diff --git a/docs/guides/search-modes.md b/docs/guides/search-modes.md
index 55735d4668..847dcdb790 100644
--- a/docs/guides/search-modes.md
+++ b/docs/guides/search-modes.md
@@ -143,6 +143,14 @@ Seven of the knobs deserve a sentence:
to OR when strict AND matching finds nothing, so a multi-word query still
gets keyword recall instead of leaning on vectors alone. Set the config
key to `false` to keep strict AND matching.
+- **`hnsw_iterative_scan`** (Postgres with pgvector 0.8+; config key
+ `search.hnsw_iterative_scan`, string, default `relaxed_order`, one of
+ `relaxed_order | strict_order | off`; env `GBRAIN_HNSW_ITERATIVE_SCAN`
+ wins) is the iterative HNSW scan mode for filtered vector search. Relaxed
+ order keeps closer in-filter candidates that strict order drops; results
+ are re-sorted either way. `gbrain config set search.hnsw_iterative_scan
+ strict_order` restores the older mode (restart serve and autopilot: it is
+ read once per process); another value is refused with exit 2.
### Setting and resolving the mode
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 337aae2d80..50dcebd1cf 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -241,6 +241,14 @@ report the regression:
5. Remove it once the regression is fixed: `gbrain config set
search.vector_legacy_guard false` (or unset the variable) and restart again.
+**Filtered vector results changed after upgrading (#6132).** Iterative HNSW
+scans now run in `relaxed_order`, which returns more of a filtered query's
+true neighbours. To restore the previous ordering mode, run
+`gbrain config set search.hnsw_iterative_scan strict_order` (or export
+`GBRAIN_HNSW_ITERATIVE_SCAN=strict_order`) and restart `gbrain serve` and
+autopilot; `off` disables iterative scanning. Verify with
+`gbrain config get search.hnsw_iterative_scan`.
+
The guard is temporary. The release that retires it prints a one-time notice
when the inert setting is still present.
diff --git a/scripts/bench/hnsw-iterative-scan.ts b/scripts/bench/hnsw-iterative-scan.ts
new file mode 100644
index 0000000000..b7d11fbd7d
--- /dev/null
+++ b/scripts/bench/hnsw-iterative-scan.ts
@@ -0,0 +1,228 @@
+#!/usr/bin/env bun
+/**
+ * #6132 bench: pgvector `hnsw.iterative_scan` strict_order vs relaxed_order on
+ * filtered vector search. Opt-in, never run in CI, not shipped in the CLI.
+ *
+ * DATABASE_URL=postgresql://postgres:postgres@localhost:5434/gbrain_test \
+ * bun scripts/bench/hnsw-iterative-scan.ts --dims 1024 [--chunks 30000]
+ * [--queries 100] [--embed voyage|openai|synthetic] [--cache DIR] [--json] [--keep]
+ *
+ * Creates `gbrain_bench_hnsw_iter_<hex>` on the DATABASE_URL server (the role
+ * needs CREATEDB and CREATE EXTENSION vector), seeds one page per corpus
+ * document (chunks of up to 800 characters, at most 60 per page) from this
+ * repository's docs/, skills/, src/ and test/ text (fixtures excluded), spread over three sources by a
+ * slug hash (10% / 40% / 50%), embeds the chunks for real (`--embed voyage`:
+ * voyage-4 at 1024 dims; `--embed openai`: text-embedding-3-small at 1536
+ * dims; `synthetic`: a 16-dim latent tiled across the dimensions, no network),
+ * builds the HNSW index and ANALYZEs. Queries are the first sentence of
+ * randomly chosen chunks, embedded as queries. Embeddings are cached under
+ * `--cache` (default ~/.capy/work/w6/bench-cache) so reruns cost nothing.
+ *
+ * For each filter selectivity (10%: one source; 50%: two sources) and each k
+ * (10, 50), both modes run the same queries through PostgresEngine.searchVector
+ * and report recall@k of pages against an exact max-pooled scan with the same
+ * filter, p50 and p95 latency, and underfilled exits. A warm-up pass runs
+ * first; modes alternate per query so cache warmth is shared. Drops the
+ * database unless --keep.
+ */
+import { randomBytes, createHash } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join, relative } from 'node:path';
+import postgres from '#postgres';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { configureGateway } 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 type { HnswIterativeScanMode } from '../../src/core/search/hnsw-iterative-scan.ts';
+import type { SearchOpts } from '../../src/core/types.ts';
+
+function flag(name: string, fallback: string): string {
+ const i = process.argv.indexOf(`--${name}`);
+ return i > 0 && process.argv[i + 1] ? process.argv[i + 1]! : fallback;
+}
+const EMBED = flag('embed', 'voyage') as 'voyage' | 'openai' | 'synthetic';
+const DIMS = Number(flag('dims', EMBED === 'openai' ? '1536' : '1024'));
+const CHUNKS = Number(flag('chunks', '30000'));
+const QUERIES = Number(flag('queries', '100'));
+const CACHE = flag('cache', join(homedir(), '.capy/work/w6/bench-cache'));
+const KEEP = process.argv.includes('--keep');
+const JSON_OUT = process.argv.includes('--json');
+const MODES: HnswIterativeScanMode[] = ['strict_order', 'relaxed_order'];
+const ROOT = join(import.meta.dir, '../..');
+const adminUrl = process.env.DATABASE_URL;
+if (!adminUrl) throw new Error('Set DATABASE_URL to a Postgres server where this role may CREATE DATABASE.');
+const log = (m: string) => console.error(`[bench ${new Date().toISOString().slice(11, 19)}] ${m}`);
+
+interface Doc { slug: string; source: string; chunks: string[] }
+
+function corpus(): Doc[] {
+ const files: string[] = [];
+ const walk = (dir: string) => {
+ for (const name of readdirSync(dir).sort()) {
+ const p = join(dir, name);
+ if (statSync(p).isDirectory()) { if (name !== 'node_modules' && name !== 'fixtures' && !name.startsWith('.')) walk(p); continue; }
+ if (/\.(md|ts)$/.test(name)) files.push(p);
+ }
+ };
+ for (const d of ['docs', 'skills', 'src', 'test']) walk(join(ROOT, d));
+ const docs: Doc[] = [];
+ let total = 0;
+ for (const f of files) {
+ const text = readFileSync(f, 'utf8').replace(/\s+/g, ' ').trim();
+ if (text.length < 200) continue;
+ const chunks: string[] = [];
+ for (let i = 0; i < text.length && chunks.length < 60; i += 800) chunks.push(text.slice(i, i + 800).replaceAll('\u0000', '').toWellFormed());
+ const slug = `bench/${relative(ROOT, f).replace(/[^a-z0-9/]+/gi, '-').toLowerCase()}`;
+ const h = createHash('sha256').update(slug).digest()[0]! % 10;
+ docs.push({ slug, source: h === 0 ? 'bench-a' : h <= 4 ? 'bench-b' : 'bench-c', chunks });
+ total += chunks.length;
+ if (total >= CHUNKS) break;
+ }
+ return docs;
+}
+
+async function embedBatch(texts: string[], kind: 'document' | 'query'): Promise<number[][]> {
+ if (EMBED === 'voyage') {
+ const res = await fetch('https://api.voyageai.com/v1/embeddings', {
+ method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${process.env.VOYAGE_API_KEY}` },
+ body: JSON.stringify({ model: 'voyage-4', input: texts, input_type: kind, output_dimension: DIMS }),
+ });
+ if (!res.ok) throw new Error(`voyage ${res.status}: ${(await res.text()).slice(0, 200)}`);
+ return ((await res.json()) as { data: Array<{ embedding: number[] }> }).data.map(d => d.embedding);
+ }
+ const res = await fetch('https://api.openai.com/v1/embeddings', {
+ method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${process.env.OPENAI_API_KEY}` },
+ body: JSON.stringify({ model: 'text-embedding-3-small', input: texts, dimensions: DIMS }),
+ });
+ if (!res.ok) throw new Error(`openai ${res.status}: ${(await res.text()).slice(0, 200)}`);
+ return ((await res.json()) as { data: Array<{ embedding: number[] }> }).data.map(d => d.embedding);
+}
+
+const LATENT = 16;
+function syntheticVector(text: string): number[] {
+ const seed = createHash('sha256').update(text).digest();
+ const latent = Array.from({ length: LATENT }, (_, i) => seed[i]! / 255 - 0.5);
+ return Array.from({ length: DIMS }, (_, d) => latent[d % LATENT]! + ((seed[(d * 7) % 32]! / 255) - 0.5) * 0.05);
+}
+
+async function embedAll(texts: string[], kind: 'document' | 'query'): Promise<number[][]> {
+ if (EMBED === 'synthetic') return texts.map(syntheticVector);
+ mkdirSync(CACHE, { recursive: true });
+ const key = createHash('sha256').update(`${EMBED}:${DIMS}:${kind}:`).update(texts.join('\u0000')).digest('hex').slice(0, 24);
+ const file = join(CACHE, `${EMBED}-${DIMS}-${kind}-${key}.f32`);
+ if (existsSync(file)) {
+ const flat = new Float32Array(readFileSync(file).buffer.slice(0));
+ return Array.from({ length: flat.length / DIMS }, (_, i) => Array.from(flat.subarray(i * DIMS, (i + 1) * DIMS)));
+ }
+ const out: number[][] = [];
+ const batch = EMBED === 'voyage' ? 64 : 256;
+ for (let i = 0; i < texts.length; i += batch) {
+ for (let attempt = 0; ; attempt++) {
+ try { out.push(...await embedBatch(texts.slice(i, i + batch), kind)); break; }
+ catch (e) { if (attempt >= 4) throw e; log(`retry ${attempt + 1}: ${(e as Error).message}`); await Bun.sleep(2000 * (attempt + 1)); }
+ }
+ if ((i / batch) % 20 === 0) log(`embedded ${Math.min(i + batch, texts.length)}/${texts.length} ${kind}`);
+ }
+ writeFileSync(file, Buffer.from(Float32Array.from(out.flat()).buffer));
+ return out;
+}
+
+const docs = corpus();
+const chunkTexts = docs.flatMap(d => d.chunks);
+log(`corpus: ${docs.length} pages, ${chunkTexts.length} chunks; ${EMBED} @ ${DIMS} dims`);
+const vectors = await embedAll(chunkTexts, 'document');
+const rng = (() => { let s = 6132; return () => (s = (s * 1103515245 + 12345) % 2 ** 31) / 2 ** 31; })();
+const queryTexts = Array.from({ length: QUERIES }, () => {
+ const t = chunkTexts[Math.floor(rng() * chunkTexts.length)]!;
+ return (t.split(/(?<=[.!?])\s/)[0] ?? t).slice(0, 300);
+});
+const queryVectors = (await embedAll(queryTexts, 'query')).map(v => Float32Array.from(v));
+
+const column = { name: 'embedding', type: 'vector' as const, dimensions: DIMS, embeddingModel: `bench:${EMBED}` };
+const dbName = `gbrain_bench_hnsw_iter_${randomBytes(6).toString('hex')}`;
+const admin = postgres(adminUrl, { max: 1, prepare: false });
+await admin.unsafe(`CREATE DATABASE ${dbName}`);
+const url = new URL(adminUrl);
+url.pathname = `/${dbName}`;
+configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'bench-stub-no-network' } });
+const engine = new PostgresEngine();
+await engine.connect({ database_url: url.toString(), poolSize: 2 });
+
+type Row = { selectivity: string; k: number; mode: string; recall: number; p50: number; p95: number; underfilled: number };
+const results: Row[] = [];
+try {
+ 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(${DIMS})`);
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('bench-a', 'bench-a'), ('bench-b', 'bench-b'), ('bench-c', 'bench-c') ON CONFLICT DO NOTHING`);
+ let v = 0;
+ for (let i = 0; i < docs.length; i += 200) {
+ const slice = docs.slice(i, i + 200);
+ const pageRows = await engine.executeRaw<{ id: number; slug: string }>(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)
+ SELECT s, src, 'note', s, 'bench', '00000000-0000-4000-8000-000000000001'::uuid, '00000000-0000-4000-8000-000000000001'::uuid, 4
+ FROM unnest($1::text[], $2::text[]) AS t(s, src) RETURNING id, slug`, [slice.map(d => d.slug), slice.map(d => d.source)]);
+ const ids = new Map(pageRows.map(r => [r.slug, Number(r.id)]));
+ const pageIds: number[] = [], idx: number[] = [], texts: string[] = [], vecs: string[] = [];
+ for (const d of slice) d.chunks.forEach((c, j) => { pageIds.push(ids.get(d.slug)!); idx.push(j); texts.push(c); vecs.push(JSON.stringify(vectors[v++])); });
+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding)
+ SELECT p, ci, t, 'compiled_truth', $5, md5(t), e::vector FROM unnest($1::int[], $2::int[], $3::text[], $4::text[]) AS u(p, ci, t, e)`,
+ [pageIds, idx, texts, vecs, column.embeddingModel]);
+ }
+ await engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL maintenance_work_mem = '1GB'`);
+ 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)');
+ });
+ await engine.executeRaw('VACUUM ANALYZE content_chunks');
+ await engine.executeRaw('ANALYZE pages');
+ await engine.executeRaw('ANALYZE sources');
+ await refreshProjectionStatistics(engine);
+ log('seeded and indexed');
+
+ const filters: Array<[string, SearchOpts]> = [['10%', { sourceIds: ['bench-a'] }], ['50%', { sourceIds: ['bench-a', 'bench-b'] }]];
+ for (const [selectivity, filter] of filters) {
+ for (const k of [10, 50]) {
+ const truth: Array<Set<number>> = [];
+ for (const q of queryVectors) {
+ const exact = buildVectorSearchStatement({ dialect: 'postgres', embedding: q, limit: k, offset: 0, opts: { ...filter, embeddingColumn: column } });
+ const rows = await engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL statement_timeout = '120s'`);
+ const bound = [...exact.params];
+ bound[exact.innerLimitIdx] = null;
+ return tx.executeRaw<{ page_id: number | null }>(exact.exactSql, bound);
+ });
+ truth.push(new Set(rows.filter(r => r.page_id != null).slice(0, k).map(r => Number(r.page_id))));
+ }
+ for (const q of queryVectors.slice(0, 5)) for (const mode of MODES) await engine.searchVector(q, { ...filter, limit: k, embeddingColumn: column, hnswIterativeScan: mode });
+ const acc = new Map(MODES.map(m => [m, { ms: [] as number[], recall: 0, underfilled: 0 }]));
+ for (let i = 0; i < queryVectors.length; i++) {
+ for (const mode of i % 2 === 0 ? MODES : [...MODES].reverse()) {
+ const a = acc.get(mode)!;
+ const start = performance.now();
+ const hits = await engine.searchVector(queryVectors[i]!, { ...filter, limit: k, embeddingColumn: column, hnswIterativeScan: mode,
+ onVectorPoolMeta: m => { if (m.underfilled) a.underfilled++; } });
+ a.ms.push(performance.now() - start);
+ const t = truth[i]!;
+ a.recall += t.size === 0 ? 1 : hits.slice(0, k).filter(h => t.has(h.page_id)).length / t.size;
+ }
+ }
+ for (const mode of MODES) {
+ const a = acc.get(mode)!;
+ a.ms.sort((x, y) => x - y);
+ const pct = (p: number) => Number(a.ms[Math.min(a.ms.length - 1, Math.floor(p * a.ms.length))]!.toFixed(1));
+ results.push({ selectivity, k, mode, recall: Number((a.recall / queryVectors.length).toFixed(3)), p50: pct(0.5), p95: pct(0.95), underfilled: a.underfilled });
+ log(JSON.stringify(results.at(-1)));
+ }
+ }
+ }
+} finally {
+ await engine.disconnect();
+ if (!KEEP) await admin.unsafe(`DROP DATABASE IF EXISTS ${dbName} WITH (FORCE)`);
+ await admin.end();
+}
+
+const header = `| selectivity | k | mode | recall@k | p50 ms | p95 ms | underfilled |\n|---|---|---|---|---|---|---|`;
+const table = results.map(r => `| ${r.selectivity} | ${r.k} | ${r.mode} | ${r.recall} | ${r.p50} | ${r.p95} | ${r.underfilled} |`).join('\n');
+console.log(JSON_OUT ? JSON.stringify({ embed: EMBED, dims: DIMS, pages: docs.length, chunks: chunkTexts.length, queries: QUERIES, results }, null, 2) : `${EMBED} @ ${DIMS} dims, ${docs.length} pages, ${chunkTexts.length} chunks, ${QUERIES} queries\n${header}\n${table}`);
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 86d6d9188e..9994a99cfc 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -23,7 +23,7 @@ src/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown
src/core/pglite-engine.ts 2996 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows)
src/core/postgres-engine.ts 2941 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts)
src/core/search/hybrid.ts 1615 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts
-src/core/types.ts 2232 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields)
+src/core/types.ts 2234 ratchet +2 fix wave 11 W6.3 (#6132): SearchOpts.hnswIterativeScan (latched in search/hnsw-iterative-scan.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
src/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1916 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts)
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1896 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS
+src/core/config.ts 1901 ratchet +5 fix wave 11 W6.3 (#6132): search.hnsw_iterative_scan type field, DB-plane merge and KNOWN_CONFIG_KEYS row (logic in search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 671 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose
diff --git a/src/commands/config.ts b/src/commands/config.ts
index dc61c9b86c..598d15300f 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -380,6 +380,12 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:
if (err) { console.error(`[config] ${err}`); process.exit(1); }
}
(await import('./config/enumerated-keys.ts')).refuseUnregisteredEnumeratedKey(key, force);
+ const searchRefusal = key.startsWith('search.') ? (await import('../core/search/config-values.ts')).searchConfigValueRefusal(key, value) : null;
+ if (searchRefusal) {
+ const { exitCliError, usageError } = await import('../cli/cli-error.ts');
+ exitCliError(usageError(searchRefusal.message, `Re-run with a valid value, e.g. gbrain config set ${key} ${searchRefusal.example}.`,
+ { fix: { argv: ['gbrain', 'config', 'get', key], consent: [], actor: 'agent', why: 'Shows the value in effect; nothing was written.', requires_exclusive: false } }), 'config');
+ }
if (key === 'auto_chronicle' || key.startsWith('chronicle.')) await refuseInvalidChronicleValue(key, value, force);
if (key.startsWith('fences.')) {
const { validateFenceConfigValue } = await import('../core/fence-repair/config.ts');
diff --git a/src/core/config.ts b/src/core/config.ts
index df76fc1870..5316d5a718 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -261,6 +261,8 @@ export interface GBrainConfig {
adaptive_return_min_keep?: number;
/** #5824 rollback switch (search/vector-legacy-guard.ts); file > DB, env wins over both. */
vector_legacy_guard?: boolean;
+ /** #6132 pgvector iterative scan mode (search/hnsw-iterative-scan.ts); file > DB, env wins over both. */
+ hnsw_iterative_scan?: string;
};
/**
@@ -1173,6 +1175,8 @@ export async function loadConfigWithEngine(
}
const dbVectorLegacyGuard = await dbBoolStrict('search.vector_legacy_guard');
if (mergedSearch.vector_legacy_guard === undefined && dbVectorLegacyGuard !== undefined) mergedSearch.vector_legacy_guard = dbVectorLegacyGuard;
+ const dbHnswIterativeScan = await dbStr('search.hnsw_iterative_scan');
+ if (mergedSearch.hnsw_iterative_scan === undefined && dbHnswIterativeScan !== undefined) mergedSearch.hnsw_iterative_scan = dbHnswIterativeScan;
if (Object.keys(mergedSearch).length > 0) {
merged.search = mergedSearch;
}
@@ -1353,6 +1357,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// review). See docs/operations/spend-controls.md.
// #5824 one-release rollback, latched per process (search/vector-legacy-guard.ts).
'search.vector_legacy_guard',
+ 'search.hnsw_iterative_scan',
'search.adaptive_return',
'search.adaptive_return_entity_max',
'search.adaptive_return_other_max',
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 9a4156b3bd..c02002352c 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1697,7 +1697,7 @@ export class PGLiteEngine implements BrainEngine {
const bound = [...stmt.params];
bound[stmt.innerLimitIdx] = requested;
return readVectorPool((await tx.query<Record<string, unknown>>(stmt.sql, bound)).rows);
- });
+ }, undefined, opts?.hnswIterativeScan);
}),
async pool => {
const { rows } = await this.db.query<{ eligible: number }>(stmt.hasMoreSql, [...stmt.params.slice(0, stmt.innerLimitIdx), pool + 1]);
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 9bbfc2836f..d92ca200f5 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -1366,7 +1366,7 @@ export class PostgresEngine implements BrainEngine {
bound[stmt.innerLimitIdx] = exact ? null : innerLimit;
await tx.unsafe(SET_STATEMENT_TIMEOUT_SQL, [String(remainingVectorBudget(deadline))]);
return run(tx, exact ? stmt.exactSql : stmt.sql, bound as Parameters<typeof tx.unsafe>[1]);
- }, deadline);
+ }, deadline, opts?.hnswIterativeScan);
}, { alwaysTransaction: true, jitOff: true });
}
diff --git a/src/core/search/config-values.ts b/src/core/search/config-values.ts
new file mode 100644
index 0000000000..bbf290b798
--- /dev/null
+++ b/src/core/search/config-values.ts
@@ -0,0 +1,23 @@
+/**
+ * Set-time validation for the `search.*` keys whose value is an enum or a
+ * bounded number, so `gbrain config set` refuses a value the reader would
+ * ignore (exit 2, `invalid_params`, nothing written) instead of storing it.
+ */
+import { HNSW_ITERATIVE_SCAN_KEY, HNSW_ITERATIVE_SCAN_MODES, hnswIterativeScanValueProblem } from './hnsw-iterative-scan.ts';
+
+interface SearchValueRule {
+ problem: (value: string) => string | null;
+ /** A valid example for the fix line. */
+ example: string;
+}
+
+export const SEARCH_VALUE_RULES: Readonly<Record<string, SearchValueRule>> = {
+ [HNSW_ITERATIVE_SCAN_KEY]: { problem: hnswIterativeScanValueProblem, example: HNSW_ITERATIVE_SCAN_MODES[0] },
+};
+
+/** The refusal for an invalid value of a validated `search.*` key, or null. */
+export function searchConfigValueRefusal(key: string, value: string): { message: string; example: string } | null {
+ const rule = SEARCH_VALUE_RULES[key];
+ const message = rule?.problem(value) ?? null;
+ return rule && message ? { message, example: rule.example } : null;
+}
diff --git a/src/core/search/hnsw-iterative-scan.ts b/src/core/search/hnsw-iterative-scan.ts
new file mode 100644
index 0000000000..f9a4ae6880
--- /dev/null
+++ b/src/core/search/hnsw-iterative-scan.ts
@@ -0,0 +1,64 @@
+/**
+ * pgvector `hnsw.iterative_scan` mode for filtered vector search (#6132 idea).
+ * `relaxed_order` (the default) lets an iterative scan return a closer
+ * candidate it finds late, after farther ones; `strict_order` drops such a
+ * candidate to keep the scan's output in exact distance order. Both engines
+ * re-sort after the per-page pooling (the inner `ORDER BY distance` plus the
+ * pooled outer sort), so relaxed output order never reaches a caller, and a
+ * filtered query that strict order underfills finds more of its true
+ * neighbours.
+ *
+ * Escape hatch, no release needed: `GBRAIN_HNSW_ITERATIVE_SCAN` (wins when
+ * set) or the config key `search.hnsw_iterative_scan`, one of
+ * `relaxed_order | strict_order | off`. Resolved once per process by the
+ * caller that builds search options (like `search.vector_legacy_guard`), so
+ * the owning service picks a change up on restart and the hot path never
+ * re-reads config. An unreadable value falls back to the default.
+ */
+import type { GBrainConfig } from '../config.ts';
+
+export const HNSW_ITERATIVE_SCAN_ENV = 'GBRAIN_HNSW_ITERATIVE_SCAN';
+export const HNSW_ITERATIVE_SCAN_KEY = 'search.hnsw_iterative_scan';
+export const HNSW_ITERATIVE_SCAN_MODES = ['relaxed_order', 'strict_order', 'off'] as const;
+export type HnswIterativeScanMode = (typeof HNSW_ITERATIVE_SCAN_MODES)[number];
+export const HNSW_ITERATIVE_SCAN_DEFAULT: HnswIterativeScanMode = 'relaxed_order';
+
+export function parseHnswIterativeScan(value: unknown): HnswIterativeScanMode | undefined {
+ const v = typeof value === 'string' ? value.trim().toLowerCase() : '';
+ return (HNSW_ITERATIVE_SCAN_MODES as readonly string[]).includes(v) ? (v as HnswIterativeScanMode) : undefined;
+}
+
+/** What the setting says right now and where it came from. */
+export function readHnswIterativeScan(
+ cfg: Pick<GBrainConfig, 'search'> | null | undefined,
+ env: NodeJS.ProcessEnv = process.env,
+): { mode: HnswIterativeScanMode; via: 'env' | 'config' | null } {
+ const fromEnv = parseHnswIterativeScan(env[HNSW_ITERATIVE_SCAN_ENV]);
+ if (fromEnv) return { mode: fromEnv, via: 'env' };
+ const fromConfig = parseHnswIterativeScan(cfg?.search?.hnsw_iterative_scan);
+ if (fromConfig) return { mode: fromConfig, via: 'config' };
+ return { mode: HNSW_ITERATIVE_SCAN_DEFAULT, via: null };
+}
+
+let resolved: HnswIterativeScanMode | undefined;
+
+/** First call decides for the process; logs once to stderr when an override is active. */
+export function resolveHnswIterativeScan(cfg: Pick<GBrainConfig, 'search'> | null | undefined): HnswIterativeScanMode {
+ if (resolved !== undefined) return resolved;
+ const setting = readHnswIterativeScan(cfg);
+ resolved = setting.mode;
+ if (setting.via && setting.mode !== HNSW_ITERATIVE_SCAN_DEFAULT) {
+ console.error(`[gbrain] vector search uses hnsw.iterative_scan=${setting.mode} (${setting.via === 'env' ? HNSW_ITERATIVE_SCAN_ENV : HNSW_ITERATIVE_SCAN_KEY}); the default is ${HNSW_ITERATIVE_SCAN_DEFAULT}.`);
+ }
+ return resolved;
+}
+
+/** `config set search.hnsw_iterative_scan <value>` refusal text, or null when the value is valid. */
+export function hnswIterativeScanValueProblem(value: string): string | null {
+ return parseHnswIterativeScan(value) ? null : `${HNSW_ITERATIVE_SCAN_KEY} must be one of ${HNSW_ITERATIVE_SCAN_MODES.join(' | ')} (got '${value}'). Nothing was written.`;
+}
+
+/** @internal test seam */
+export function _resetHnswIterativeScanForTests(): void {
+ resolved = undefined;
+}
diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.ts
index 298231d95b..a8fa03dce5 100644
--- a/src/core/search/hybrid/request.ts
+++ b/src/core/search/hybrid/request.ts
@@ -23,6 +23,7 @@ import { recordSearchTelemetry } from '../telemetry.ts';
import { resolveBoostMap, resolveHardExcludes } from '../source-boost.ts';
import { resolveEmbeddingColumn } from '../embedding-column.ts';
import { resolveVectorLegacyGuard } from '../vector-legacy-guard.ts';
+import { resolveHnswIterativeScan } from '../hnsw-iterative-scan.ts';
import { resolveSearchDateBounds } from '../date-bounds.ts';
import { type DecideSearchContext, decideMetaFor, resolveAndLaunchDecide } from '../decide-stage.ts';
import { applySearchIntent } from '../decide-retrieval.ts';
@@ -235,6 +236,7 @@ export async function resolveHybridRequest(
embeddingColumn: resolvedCol,
// #5824 rollback switch, latched once per process from env/config.
vectorLegacyGuard: resolveVectorLegacyGuard(cfgForColumn),
+ hnswIterativeScan: resolveHnswIterativeScan(cfgForColumn),
// D2 fix (fix/title-retrieval-arm, Reviewer F1): the hybrid keyword arm
// is a recall arm — opt in to the engine's AND→OR zero-recall fallback.
// Direct searchKeyword consumers (countMentions, link-extraction, eval)
diff --git a/src/core/search/vector-settings.ts b/src/core/search/vector-settings.ts
index 7f149f8dd5..353df3d2e4 100644
--- a/src/core/search/vector-settings.ts
+++ b/src/core/search/vector-settings.ts
@@ -1,5 +1,6 @@
import { hnswEfSearchFor, HNSW_EF_SEARCH_DEFAULT } from '../vector-index.ts';
import { remainingVectorBudget } from './vector-pool.ts';
+import { HNSW_ITERATIVE_SCAN_DEFAULT, type HnswIterativeScanMode } from './hnsw-iterative-scan.ts';
export async function withVectorSettings<T>(
query: (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>,
@@ -8,11 +9,12 @@ export async function withVectorSettings<T>(
maxScanTuples: number,
run: () => Promise<T>,
deadline?: number,
+ iterativeMode: HnswIterativeScanMode = HNSW_ITERATIVE_SCAN_DEFAULT,
): Promise<T> {
const settings: Record<string, string> = { 'hnsw.ef_search': String(hnswEfSearchFor(candidateLimit)) };
const defaults: Record<string, string> = { 'hnsw.ef_search': String(HNSW_EF_SEARCH_DEFAULT), 'hnsw.iterative_scan': 'off', 'hnsw.max_scan_tuples': '20000' };
if (iterative) {
- settings['hnsw.iterative_scan'] = 'strict_order';
+ settings['hnsw.iterative_scan'] = iterativeMode;
settings['hnsw.max_scan_tuples'] = String(maxScanTuples);
}
if (deadline !== undefined) settings.statement_timeout = String(remainingVectorBudget(deadline));
diff --git a/src/core/types.ts b/src/core/types.ts
index 9e1b1f6860..49255f2f86 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1176,6 +1176,8 @@ export interface SearchOpts extends PageReadPolicy {
onVectorPoolMeta?: (m: VectorPoolMeta) => void;
/** #5824 rollback: keep the freshness guard inside the HNSW candidate CTE. Latched by the caller (search/vector-legacy-guard.ts). */
vectorLegacyGuard?: boolean;
+ /** #6132: pgvector `hnsw.iterative_scan` mode (default relaxed_order), latched by the caller (search/hnsw-iterative-scan.ts). */
+ hnswIterativeScan?: import('./search/hnsw-iterative-scan.ts').HnswIterativeScanMode;
/**
* v0.42 — intent-aware adaptive return-sizing. `true` enables with config/
* default caps; an object overrides caps per-call; omitted/`false` = off
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
index d523f5382d..7b2dd03649 100644
--- a/test/config-search-registry.test.ts
+++ b/test/config-search-registry.test.ts
@@ -33,6 +33,7 @@ const DIRECTLY_READ_SINGLETONS = [
'search.adaptive_return_other_max',
'search.adaptive_return_min_keep',
'search.vector_legacy_guard', // search/vector-legacy-guard.ts via loadConfigWithEngine
+ 'search.hnsw_iterative_scan', // search/hnsw-iterative-scan.ts via loadConfigWithEngine
'search.crag_escalation', // ops/search.ts
'search.crag_think', // ops/search.ts
'search.return_unit', // search/evidence-delivery.ts
diff --git a/test/e2e/hnsw-iterative-scan-recall-postgres.test.ts b/test/e2e/hnsw-iterative-scan-recall-postgres.test.ts
new file mode 100644
index 0000000000..2aa576c090
--- /dev/null
+++ b/test/e2e/hnsw-iterative-scan-recall-postgres.test.ts
@@ -0,0 +1,91 @@
+/**
+ * #6132 idea: under a selective source filter, pgvector's strict_order
+ * iterative scan drops closer candidates it finds late, so filtered vector
+ * search underfills its true neighbours; relaxed_order (the default now)
+ * keeps them, and both engines re-sort after pooling. The fixture amplifies
+ * the effect with a sparse HNSW graph (m = 4, ef_construction = 8) over 20k
+ * clustered 32-dim vectors, a 10% source filter and exact truth computed in
+ * process. HNSW construction is randomized, so the bounds sit about 0.1 away
+ * from the measured ranges (strict 0.44-0.49, relaxed 0.68-0.75 over four
+ * builds).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { refreshProjectionStatistics } from '../../src/core/search/projection-statistics.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+
+const RUN = hasDatabase();
+const D = 32, N = 20_000, K = 20, Q = 40;
+const column = { name: 'embedding_iterative_fixture', type: 'vector' as const, dimensions: D, embeddingModel: '' };
+let engine: PostgresEngine;
+let seed = 42;
+const rnd = () => (seed = (seed * 1103515245 + 12345) % 2 ** 31) / 2 ** 31;
+const gauss = () => Math.sqrt(-2 * Math.log(rnd() + 1e-12)) * Math.cos(2 * Math.PI * rnd());
+const centers = Array.from({ length: 40 }, () => Array.from({ length: D }, gauss));
+const vectors: number[][] = [];
+const pageIds: number[] = [];
+const allowed: boolean[] = [];
+
+function cosineDistance(a: number[], b: number[]): number {
+ let dot = 0, na = 0, nb = 0;
+ for (let i = 0; i < a.length; i++) { dot += a[i]! * b[i]!; na += a[i]! ** 2; nb += b[i]! ** 2; }
+ return 1 - dot / Math.sqrt(na * nb);
+}
+
+async function meanRecall(mode?: 'strict_order' | 'relaxed_order'): Promise<number> {
+ let qs = 9001;
+ const qr = () => (qs = (qs * 1103515245 + 12345) % 2 ** 31) / 2 ** 31;
+ const qg = () => Math.sqrt(-2 * Math.log(qr() + 1e-12)) * Math.cos(2 * Math.PI * qr());
+ let total = 0;
+ for (let qi = 0; qi < Q; qi++) {
+ const q = centers[qi % centers.length]!.map((x) => x + qg() * 0.6);
+ const truth = new Set(pageIds.map((id, i) => ({ id, d: cosineDistance(q, vectors[i]!), ok: allowed[i] }))
+ .filter((r) => r.ok).sort((a, b) => a.d - b.d).slice(0, K).map((r) => r.id));
+ const hits = await engine.searchVector(Float32Array.from(q), { sourceId: 'iter-allowed', limit: K, embeddingColumn: column, ...(mode ? { hnswIterativeScan: mode } : {}) });
+ total += hits.filter((h) => truth.has(h.page_id)).length / K;
+ }
+ return total / Q;
+}
+
+describe.skipIf(!RUN)('filtered HNSW recall under iterative scan modes (Postgres, #6132)', () => {
+ beforeAll(async () => {
+ engine = await setupDB();
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('iter-allowed', 'iter-allowed'), ('iter-other', 'iter-other') ON CONFLICT DO NOTHING`);
+ await engine.executeRaw(`ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_iterative_fixture vector(${D})`);
+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)
+ SELECT 'iter/p-' || i, CASE WHEN i % 10 = 0 THEN 'iter-allowed' ELSE 'iter-other' END, 'note', 'p' || i, 'fixture',
+ '00000000-0000-4000-8000-000000000001'::uuid, '00000000-0000-4000-8000-000000000001'::uuid, 4
+ FROM generate_series(1, ${N}) i`);
+ const pages = await engine.executeRaw<{ id: number; source_id: string }>(`SELECT id, source_id FROM pages WHERE slug LIKE 'iter/%' ORDER BY id`);
+ const embeddings: string[] = [];
+ for (const p of pages) {
+ const v = centers[Math.floor(rnd() * centers.length)]!.map((x) => x + gauss() * 0.6);
+ vectors.push(v);
+ pageIds.push(Number(p.id));
+ allowed.push(p.source_id === 'iter-allowed');
+ embeddings.push(JSON.stringify(v));
+ }
+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, embedding_iterative_fixture)
+ SELECT p, 0, 'fixture', 'compiled_truth', e::vector FROM unnest($1::int[], $2::text[]) u(p, e)`, [pageIds, embeddings]);
+ await engine.transaction(async (tx) => {
+ await tx.executeRaw('SET LOCAL max_parallel_maintenance_workers = 0');
+ await tx.executeRaw(`CREATE INDEX idx_chunks_iterative_fixture ON content_chunks USING hnsw (embedding_iterative_fixture vector_cosine_ops) WITH (m = 4, ef_construction = 8)`);
+ });
+ await engine.executeRaw('ANALYZE content_chunks');
+ await engine.executeRaw('ANALYZE pages');
+ await refreshProjectionStatistics(engine);
+ }, 300_000);
+
+ afterAll(async () => {
+ await engine.executeRaw('DROP INDEX IF EXISTS idx_chunks_iterative_fixture');
+ await engine.executeRaw('ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding_iterative_fixture');
+ await teardownDB();
+ }, 120_000);
+
+ test('the default keeps the late, closer in-filter neighbours strict order drops', async () => {
+ const byDefault = await meanRecall();
+ const strict = await meanRecall('strict_order');
+ expect(byDefault).toBeGreaterThanOrEqual(0.6);
+ expect(byDefault - strict).toBeGreaterThanOrEqual(0.1);
+ }, 300_000);
+});
diff --git a/test/mcp-feedback-visible-answer-id.test.ts b/test/mcp-feedback-visible-answer-id.test.ts
index 36de49a9c1..a81b3933af 100644
--- a/test/mcp-feedback-visible-answer-id.test.ts
+++ b/test/mcp-feedback-visible-answer-id.test.ts
@@ -89,7 +89,7 @@ describe('the rateable answer id is model-visible (#6192)', () => {
describe('retrieval_feedback_health: many answers, zero ratings (#6192)', () => {
async function doctorCheck() {
const { retrievalFeedbackEntry } = await import('../src/commands/doctor/checks/retrieval-feedback.ts');
- const checks = await retrievalFeedbackEntry.run({ engine, progress: { heartbeat() {} } } as never);
+ const checks = (await retrievalFeedbackEntry.run({ engine, progress: { heartbeat() {} } } as never)) as Array<{ name: string; status: string; message: string; fix?: unknown }>;
return checks.find((c) => c.name === 'retrieval_feedback_health')!;
}
async function seedAnswers(n: number) {
diff --git a/test/search/hnsw-iterative-scan.test.ts b/test/search/hnsw-iterative-scan.test.ts
new file mode 100644
index 0000000000..fffc5a71e7
--- /dev/null
+++ b/test/search/hnsw-iterative-scan.test.ts
@@ -0,0 +1,68 @@
+/**
+ * #6132 idea: filtered vector search runs pgvector's iterative scan in
+ * relaxed_order by default (strict_order drops a closer candidate found
+ * late); `search.hnsw_iterative_scan` / GBRAIN_HNSW_ITERATIVE_SCAN restore
+ * strict_order or off without a release. ef_search sizing is unchanged.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { withVectorSettings } from '../../src/core/search/vector-settings.ts';
+import { hnswEfSearchFor } from '../../src/core/vector-index.ts';
+import {
+ _resetHnswIterativeScanForTests,
+ readHnswIterativeScan,
+ resolveHnswIterativeScan,
+} from '../../src/core/search/hnsw-iterative-scan.ts';
+import { searchConfigValueRefusal } from '../../src/core/search/config-values.ts';
+
+async function appliedSettings(iterative: boolean, mode?: 'relaxed_order' | 'strict_order' | 'off'): Promise<Record<string, string>> {
+ const sets: Array<[string[], string[]]> = [];
+ const query = async (sql: string, params: unknown[]) => {
+ if (sql.includes('set_config')) sets.push(params as [string[], string[]]);
+ return (params[0] as string[]).map((name) => ({ name, value: null }));
+ };
+ const args: Parameters<typeof withVectorSettings> = [query, iterative, 200, 20_000, async () => 'ok', undefined];
+ if (mode) args.push(mode);
+ await withVectorSettings(...args);
+ const [names, values] = sets[0]!;
+ return Object.fromEntries(names.map((n, i) => [n, values[i]!]));
+}
+
+afterEach(() => _resetHnswIterativeScanForTests());
+
+describe('hnsw.iterative_scan mode', () => {
+ test('an iterative scan runs relaxed_order by default and keeps ef_search sizing', async () => {
+ const s = await appliedSettings(true);
+ expect(s['hnsw.iterative_scan']).toBe('relaxed_order');
+ expect(s['hnsw.ef_search']).toBe(String(hnswEfSearchFor(200)));
+ expect(s['hnsw.max_scan_tuples']).toBe('20000');
+ });
+
+ test('the override restores strict_order or turns iterative scanning off', async () => {
+ expect((await appliedSettings(true, 'strict_order'))['hnsw.iterative_scan']).toBe('strict_order');
+ expect((await appliedSettings(true, 'off'))['hnsw.iterative_scan']).toBe('off');
+ });
+
+ test('an engine without iterative scan support sets no iterative mode', async () => {
+ expect((await appliedSettings(false))['hnsw.iterative_scan']).toBeUndefined();
+ });
+
+ test('env wins over config; config over the default; an invalid value falls back to the default', () => {
+ expect(readHnswIterativeScan({ search: { hnsw_iterative_scan: 'strict_order' } }, {})).toEqual({ mode: 'strict_order', via: 'config' });
+ expect(readHnswIterativeScan({ search: { hnsw_iterative_scan: 'strict_order' } }, { GBRAIN_HNSW_ITERATIVE_SCAN: 'off' })).toEqual({ mode: 'off', via: 'env' });
+ expect(readHnswIterativeScan({ search: { hnsw_iterative_scan: 'sideways' } }, {})).toEqual({ mode: 'relaxed_order', via: null });
+ expect(readHnswIterativeScan(null, {})).toEqual({ mode: 'relaxed_order', via: null });
+ });
+
+ test('resolved once per process', () => {
+ expect(resolveHnswIterativeScan({ search: { hnsw_iterative_scan: 'strict_order' } })).toBe('strict_order');
+ expect(resolveHnswIterativeScan({ search: { hnsw_iterative_scan: 'off' } })).toBe('strict_order');
+ });
+
+ test('config set refuses an invalid value with the valid modes and an example', () => {
+ expect(searchConfigValueRefusal('search.hnsw_iterative_scan', 'relaxed_order')).toBeNull();
+ expect(searchConfigValueRefusal('search.hnsw_iterative_scan', 'Strict_Order')).toBeNull();
+ const refusal = searchConfigValueRefusal('search.hnsw_iterative_scan', 'sideways');
+ expect(refusal?.message).toContain('relaxed_order | strict_order | off');
+ expect(refusal?.example).toBe('relaxed_order');
+ });
+});