Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.60.131.0 fix(search): pooled vector attempts scan up to 20,000 tuples; refresh content_chunks and pages statistics after bulk writes and embed drains; HNSW scale bench

garrytanfc920367e366
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 6feb4e2ce6..4dd183f706 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -171,6 +171,40 @@ the object is absent. Highly selective queries may correctly choose an exact
plan. The [retrieval guide](architecture/RETRIEVAL.md#named-thing-retrieval-per-page-pool--title--alias--evidence)
describes bounded candidate recovery and incomplete-result metadata.
+On Postgres the same refresh also analyzes the page columns every search
+filter reads (`deleted_at`, `source_id`, `type`, `slug`) and
+`content_chunks(model, modality, page_id)`, and an embed drain that embedded
+anything analyzes those chunk columns once at its end (each ANALYZE bounded by
+a 30 s statement and 2 s lock timeout). Without those statistics the vector
+candidate statement sorts every eligible chunk instead of walking the HNSW
+index, and at 1M chunks and above that sort runs past the 8 s vector budget,
+so hybrid search falls back to keyword-only results until autovacuum
+analyzes the tables. If a refresh is skipped (a lock, or a role that does not
+own the tables), run `ANALYZE content_chunks(model, modality, page_id)` and
+`ANALYZE pages` as the table owner.
+
+### Vector index sizing
+
+The chunk HNSW index stores each vector beside its graph links, so at 1,024
+dimensions it takes about 7.6 GiB per million chunks as `vector` (about
+9.8 GiB for a 1.28M-chunk brain) and a third of that as `halfvec`. The
+deferred ANN build (`gbrain migrate embeddings`, `gbrain reindex --vectors`)
+runs `CREATE INDEX CONCURRENTLY` with the server's `maintenance_work_mem`.
+When the graph does not fit, pgvector logs `hnsw graph no longer fits into
+maintenance_work_mem` and the build slows several-fold: 4.3x at 250k chunks
+with 256 MB. Before a large build, raise it on the brain host to the index
+size plus about 10% (Supabase: `supabase postgres-config update --config
+maintenance_work_mem=12GB --project-ref <ref> --experimental`, which reloads
+without a restart; self-hosted: `ALTER SYSTEM SET maintenance_work_mem =
+'12GB'` and `SELECT pg_reload_conf()`), and give it
+`max_parallel_maintenance_workers` of about half the cores: a 1M-chunk build
+took 103 s on 16 vCPU with 12 GB and 8 workers. Measured, not shipped:
+`halfvec` gives the same recall with an index a third the size, and
+`ef_construction` 128 adds about 0.02 to 0.03 unfiltered recall@10 for about
+25% more build time. Both need a migration or a rebuild, so the defaults stay
+(m 16, ef_construction 64, `vector`). Measurements and method:
+[`docs/eval/hnsw-scale-bench.md`](eval/hnsw-scale-bench.md).
+
### Opt-in RLS source-scope binding (`GBRAIN_RLS_SCOPE_BINDING`)
Defense-in-depth layer for Postgres deployments that want the database itself
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index 892e5b44cb..bab477331d 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -92,7 +92,10 @@ written up in [`RETRIEVAL_MAXPOOL_INCIDENT.md`](../incidents/RETRIEVAL_MAXPOOL_I
bounded loop (×4 per step, at most 3 escalations). SQL candidate limits and
offsets are independent of `ef_search`; supported pgvector versions use
`relaxed_order` iterative scans with bounded visits (`ef_search` is still
- sized to the candidate pool). Relaxed order keeps a closer candidate the
+ sized to the candidate pool; each pooled attempt may visit 20,000 index
+ tuples, so a source or visibility filter covering a tenth of the brain fills
+ its candidate window instead of stopping at the first few hundred eligible
+ chunks). 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
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index 2a0fa9825a..d0e09aa5a5 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -58,7 +58,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/projection-readiness.ts` — EXISTS probe for unsealed text revisions in the visible scope: ready, projection_pending or unknown. Cached per scope by DB generation (page clock, `pages` filenode, archive flags, no open transaction); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.
-- `src/core/search/projection-statistics.ts` — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. Migration 161 adds the scoped pending-projection index.
+- `src/core/search/projection-statistics.ts` — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. On Postgres the refresh also samples the page columns search filters read (`SEARCH_PAGE_STATISTICS_SQL`) and, behind a savepoint so a held lock skips only that step, `content_chunks(model, modality, page_id)`; `refreshChunkStatistics` runs the chunk step alone once at the end of an embed drain that embedded: without them the vector candidate statement sorts every eligible chunk instead of walking the HNSW index (`test/e2e/vector-chunk-statistics-postgres.test.ts`). Migration 161 adds the scoped pending-projection index.
- `src/core/search/query-cache.ts` — stored semantic-cache data and maintenance remain, but `semanticResultCacheAvailable()` is false. `hybridSearchCached` bypasses both result lookup and writes regardless of configuration or `useCache`, and skips the key/config setup (merged config, cache config, intent-pattern state) so the wrapper adds no engine round-trips; request-local query embeddings still work. Search metadata, cache_stats and the mode dashboard report effective caching as disabled. Historical hit counts and search_telemetry remain intact. Restoration requires complete response-dependency provenance.
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 434fd651cc..f05d1c052e 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -22,14 +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. `withVectorSettings(..., iterativeMode, indexWalk)` sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`); `indexWalk` adds `INDEX_WALK_SETTINGS` and sizes `ef_search` for the over-fetched window. `searchIndexWalk(stmt, limit, run)` runs the statement's index walk before the pool and returns its rows only when its window is full and they fill the limit; otherwise (or past its 2 s budget) both engines run the pool unchanged.
+- `src/core/search/vector-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. Every pooled attempt scans with `hnsw.max_scan_tuples` = `POOL_MAX_SCAN_TUPLES` (20,000, pgvector's default), so a filtered attempt fills its candidate window before it is accepted; the index walk keeps 2,000 because it accepts only a full window. Settings are restored even inside caller-owned transactions. A batch carries the raw `candidatePool` (exhaustion: a short window means the index ran dry) and an optional `eligiblePool` (candidates that passed the freshness filter outside the candidate CTE); `hasMore` receives the eligible count, defaulting to the raw one. `withVectorSettings(..., iterativeMode, indexWalk)` sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`); `indexWalk` adds `INDEX_WALK_SETTINGS` and sizes `ef_search` for the over-fetched window. `searchIndexWalk(stmt, limit, run)` runs the statement's index walk before the pool and returns its rows only when its window is full and they fill the limit; otherwise (or past its 2 s budget) both engines run the pool unchanged.
- `src/core/search/vector-statement.ts` — `buildVectorSearchStatement({ dialect, embedding, limit, offset, opts })` builds the vector-search SQL once for both engines, doctor `vector_plan` and the plan-proof E2E: `{ sql, exactSql, hasMoreSql, params, innerLimitIdx, innerLimit, indexed, relaxed, indexWalkSql? }`. On an HNSW-indexed `embedding` column (relaxed variant) the candidate CTE carries only the model check; content freshness (`embedded_text_hash = md5(chunk_text)` or NULL) is projected as `hash_current` and filtered in `scored`, because Postgres cannot estimate that expression and drops the index when it sits in the CTE (#5824). Non-indexed columns, the legacy guard, `exactSql` and `hasMoreSql` keep the full guard inside. The pool row reports `candidate_pool` (raw) and `eligible_pool` (fresh). Since/until bounds are spelled per column (`effective_date`, then `updated_at`, then `created_at`) so each arm has column statistics. `indexWalkSql` (relaxed variant without a type or date filter, same parameters) is the statement both engines run first: `ann` orders `content_chunks` alone with the chunk-level filters over twice the window, then pages and sources are joined by key and every page filter, visibility and the private-page rule apply to those rows, keeping the nearest `innerLimit`. Run with `enable_sort = off` (`INDEX_WALK_SETTINGS`) the HNSW scan is its only ordered path; the joined statement's plan sat on a cost knife edge (TOASTed vectors cost a sequential scan too little, the HNSW estimate grows with `ef_search`, the private-page rule's subplans priced every page lookup high) and flipped to a full scan and sort at a 50-row limit or on any remote read. A full walk window selects the same rows as the joined statement (`test/search/vector-index-walk.test.ts`); a short one falls back to it. A source scope whose share of pages (`pages.source_id` planner statistics, `PAGE_SOURCE_STATS_SQL`, read by each engine's `vectorScopeShareLoader` at most once a minute) is below `INDEX_WALK_MIN_SCOPE_SHARE` (0.1) skips the walk like a type or date filter, because the nearest chunks overall never fill its window; the input `scopeShare` only removes `indexWalkSql`, every other statement stays byte-identical, and missing statistics leave the walk on. 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/evidence-packing.ts` — the explicit-budget packing surface of evidence delivery: `AUTO_PACKINGS` (`off`, `cap_only` default, `breadth_capped`, `depth_first`) for `search.auto_packing`, `MIN_EXPLICIT_AUTO_BUDGET` (32; an explicit `auto` budget below it, or non-finite, is refused with `invalid_params` naming it), `parseAutoPacking` (the library override, unknown values refused), `configPacking` (unknown stored values read as the default) and `autoPackingValueProblem` (the `config set` refusal wired through `search/config-values.ts`). Tests: `test/evidence-delivery.test.ts`.
-- `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/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` (its `--corpus latent` mode, with `scripts/bench/hnsw-latent-corpus.ts` and the VM bootstrap `scripts/bench/hnsw-scale-vm-setup.sh`, is the E5.4 scale and index-build bench; results in `docs/eval/hnsw-scale-bench.md`).
- `src/core/search/cjk-keyword-sql.ts` + `src/core/engine-sql/cjk-search.ts` + `src/core/search/cjk-keyword-deadline.ts` — the CJK keyword fallback shared by both engines. `buildCJKKeywordSql(query, ctx, variant)` keeps today's strict-AND SQL byte-identical by default; `match: 'any'` (the OR fallback, #6043) qualifies a chunk on any term and orders by matched-term count, then the TF score (the count enters the score as 1000 x matched outside the source factor, so a boosted partial match never outranks an all-term chunk); `candidateIds` scores only a candidate set by joining `unnest($n::bigint[])` to `content_chunks` (an `= ANY` filter was a sequential scan). `buildCJKCandidateSql` is the unordered capped LIKE scan for ids (all-term, or any-term excluding ids already taken). `searchKeywordCJK(scoped, query, ctx, engine)` runs strict AND and, with `opts.orFallback` and 2+ terms, the OR pass only when strict AND returns fewer than `limit` rows; with `opts.cjkKeyword` (hybrid only, deadline from `search.cjk_keyword_deadline_ms`, integer ms 500..30000, default 3000) it bounds the arm: Postgres runs full scoring in its own scoped read transaction within 2/3 of the deadline (counted from before the pool wait; every statement of an attempt gets `statement_timeout` = what is left of that attempt, minus a 40 ms rollback margin), and on SQLSTATE 57014 a capped retry (`CJK_CANDIDATE_CAP` = 2000; all-term ids first, partial ids only when the all-term rows fall short) in a fresh scoped transaction with the remaining third (a fresh transaction, not a savepoint, because the driver rethrows any failed statement at the end of its transaction scope); PGLite runs the capped stage whenever `pg_class.reltuples` exceeds `PGLITE_CJK_CAPPED_CHUNKS` = 50,000. `onMeta` gets `{ incomplete, reason (timeout | candidate_budget), capped, arm_ms }` (test seams: `candidateCap`, `pgliteCappedChunks`, `fullBudgetMs`); hybrid `request.ts` turns `incomplete` into degraded `keyword_candidates_incomplete` and `emitHybridMeta` adds `keyword_candidates` (keyword-arm wall time, separate from total hybrid latency) to every return path's meta. Pinned by `test/cjk-keyword-fallback.test.ts`, `test/e2e/cjk-keyword-deadline-postgres.test.ts` and `test/cjk-keyword-sql.test.ts`; bench `scripts/bench/cjk-keyword-deadline.ts`.
diff --git a/docs/eval/hnsw-scale-bench.md b/docs/eval/hnsw-scale-bench.md
new file mode 100644
index 0000000000..cdcddb7fa9
--- /dev/null
+++ b/docs/eval/hnsw-scale-bench.md
@@ -0,0 +1,599 @@
+# HNSW vector search at production scale (E5.4.1, E5.4.2)
+
+gbrain's Postgres vector arm finds unfiltered and broadly filtered neighbours well from 250k to 2M chunks.
+After this wave's two fixes, it also does so under selective random scopes and right after a bulk load.
+
+**Fix 1: scoped search scans deeper.** Every pooled attempt now visits up to 20,000 index tuples
+(`POOL_MAX_SCAN_TUPLES` in `src/core/search/vector-pool.ts`, pgvector's own `hnsw.max_scan_tuples` default).
+Before, the first attempt stopped at 2,000. Under a 10% source or visibility scope, that budget found about
+200 eligible chunks. That covered enough pages to be accepted, but it was too shallow to hold the true
+neighbours. The deeper scan has these effects:
+- **Synthetic, 1M and 2M chunks, same database, `limit 50`:** 10%-scope recall@50 rises from 0.52–0.63 to
+ 0.96–0.99, and recall@10 from 0.92 to 0.98–0.99.
+- **1M real voyage-4 chunks, random 10% scope:** recall@50 goes from 0.77 to 0.97.
+- **Cost:** 16 to 36 ms more p50 per scoped search.
+- **Unscoped searches** return identical results.
+
+**Fix 2: statistics follow bulk writes.** Import, sync, reindex and embed drains now analyze
+`content_chunks(model, modality, page_id)` and the page columns search filters read. Without those
+statistics, the pooled statement sorted every eligible chunk instead of walking the index. At 1M to 2M
+chunks that ran past the 8 s budget on 44% to 100% of 50%-scoped searches. In the post-import statistics
+state, 1M and 2M chunks now plan on HNSW with no incomplete results.
+
+**One gap remains: topic-coherent selective scopes.** Real vectors with a scope that is both selective
+and topically coherent (a 10% source made of whole topic clusters) still miss. Fix 1 lifts recall@10
+from 0.63 to 0.84 and recall@50 from 0.64 to 0.78, but most queries come from other topics. For those,
+the nearest in-scope chunks sit outside the region an HNSW scan reaches, and 50,000 or 100,000 tuples
+change nothing. An exact pass gets 0.96 but costs 1.0 to 1.6 s per search, so it is proposed below,
+not shipped.
+
+Index build options don't change any of this, so the defaults stay (m 16, ef_construction 64, `vector`).
+`ef_construction` 128 adds about 0.02 to 0.03 unfiltered recall@10 for about 25% more build time.
+`halfvec` gives the same recall with an index a third the size (5.1 GiB against 15.3 GiB at 2M chunks).
+
+The numbers come from three sources:
+- synthetic-latent vectors at voyage-4's 1,024 dimensions (`src/core/ai/recipes/voyage.ts`, `default_dims: 1024`),
+ from 250k to 2M chunks;
+- a 1M-chunk English Wikipedia corpus embedded with voyage-4, which cost $13.07 by the API's own token counts;
+- 100 queries per cell, on Ubicloud standard-16 VMs.
+
+## Decision rule
+
+The plan's rule (E5.4.1): keep defaults unless recall@10 < 0.95 or underfill > 1% at the shipped `ef_search`.
+The shipped code failed it. On master, 10%-scope recall@10 was 0.886 to 0.950 synthetic and 0.63 to 0.92 real.
+Stats-less loads made 44% to 100% of 50%-scoped searches incomplete.
+
+The plan's proposed remedy, a per-brain `search.hnsw_ef_search_floor` knob, was measured and rejected.
+On real vectors, `ef_search` 1,000 left topic-scoped recall@50 at 0.71 and random 10% at 0.93. Fix 1
+reaches 0.97 on the random scope at the shipped `ef_search`. So no knob ships.
+
+After both fixes:
+
+| check (shipped settings) | synthetic 1M / 2M | real 1M | verdict |
+|---|---|---|---|
+| unfiltered recall@10 | 0.972 / 0.935 | 0.968 | 2M below 0.95 on this load (0.965 on the first load); build variance, the same before and after |
+| random 10% visibility recall@10 | 0.989 / 0.979 | 0.990 | pass |
+| 10% source recall@10 | 0.986 / 0.990 (random) | 0.837 (topic-coherent) | pass random; **fail** topic-coherent |
+| 50% source / visibility recall@10 | 0.981 / 0.928–0.941 | 0.959 / 0.967 | pass except 2M synthetic (0.93 to 0.94, unchanged by either fix) |
+| incomplete, post-import statistics | 0% / 0% | not measured | pass |
+
+The 2M synthetic unfiltered and 50%-scope recall@10 sit at 0.93 to 0.94 on this load and at 0.965 to 0.978
+on the first load of the same corpus. HNSW graph variance between builds explains the difference, and
+neither fix touches it. `ef_construction` 128 measured 0.981 there (E5.4.2 below).
+
+## Fix 1: which mechanism
+
+The two options were to start pooled attempts at 20,000 tuples, or to keep 2,000 and refuse a short window
+(escalate, or run the exact fallback, while `hasMore` says more eligible rows exist). Both were measured on
+the same database, after the same index build, against master. Escalate-when-short keeps master's
+2,000 × 4^n schedule. Its window stays short at every step, so it ends in the exact fallback: 1.0 to
+8.5 s per search, and incomplete when that misses the 8 s budget. The deeper first scan wins at equal or
+better recall everywhere except topic-coherent 10% scopes, where only exact search gets past 0.84. There
+the trade is about 1.5 s per search, which is a product decision.
+
+Synthetic-latent corpus (shipped `ef_search`, relaxed_order, 100 queries; recall@k at `limit k`):
+
+| chunks | filter | k | master recall@k | escalate-when-short | fixed (20,000) | master p50 / p95 ms | escalate p50 / p95 ms | fixed p50 / p95 ms |
+|---|---|---|---|---|---|---|---|---|
+| 1M | none | 10 | 0.972 | 0.972 | **0.972** | 17.9 / 23 | 15.9 / 23.2 | 9.7 / 12.1 |
+| 1M | none | 50 | 0.990 | 0.990 | **0.990** | 27.7 / 32.8 | 22.7 / 29.3 | 19.9 / 23.8 |
+| 1M | source10 | 10 | 0.922 | 0.922 | **0.986** | 29 / 36.4 | 25.3 / 32.4 | 27.6 / 36.9 |
+| 1M | source10 | 50 | 0.612 | 0.747 | **0.986** | 36.7 / 44.6 | 39.5 / 1342.8 | 54 / 62.5 |
+| 1M | vis10 | 10 | 0.924 | 0.924 | **0.989** | 24.5 / 31.9 | 27.3 / 32.2 | 31.5 / 40.5 |
+| 1M | vis10 | 50 | 0.631 | 0.715 | **0.983** | 40.1 / 104.5 | 49.3 / 8471.6 | 56 / 64.4 |
+| 1M | source50 | 10 | 0.981 | 0.981 | **0.981** | 11.1 / 18.9 | 13.2 / 25.8 | 10.2 / 19.6 |
+| 1M | source50 | 50 | 0.970 | 0.970 | **0.975** | 37.4 / 93.2 | 39.2 / 93.3 | 40.7 / 93.9 |
+| 1M | vis50 | 10 | 0.981 | 0.981 | **0.981** | 13.3 / 24.3 | 13.2 / 23.8 | 13.4 / 22.9 |
+| 1M | vis50 | 50 | 0.959 | 0.959 | **0.973** | 37.9 / 100.5 | 38.7 / 92.8 | 38.4 / 97.4 |
+| 2M | none | 10 | 0.935 | 0.935 | **0.935** | 16 / 23.4 | 15.8 / 26 | 13.6 / 66.5 |
+| 2M | none | 50 | 0.981 | 0.981 | **0.981** | 21.2 / 27 | 22.2 / 36.2 | 17.8 / 24.3 |
+| 2M | source10 | 10 | 0.921 | 0.921 | **0.990** | 22.3 / 26.7 | 23 / 29.2 | 28.1 / 182.7 |
+| 2M | source10 | 50 | 0.560 | 0.646 | **0.958** | 38.6 / 119.7 | 38.5 / 142 | 74.6 / 320.8 |
+| 2M | vis10 | 10 | 0.915 | 0.915 | **0.979** | 23.5 / 27.2 | 22.7 / 25.6 | 29.1 / 41.3 |
+| 2M | vis10 | 50 | 0.518 | 0.669 | **0.957** | 37.9 / 43.4 | 143.3 / 8592 | 63.5 / 125.7 |
+| 2M | source50 | 10 | 0.928 | 0.928 | **0.928** | 16 / 20.2 | 16.2 / 22.6 | 15.6 / 24.1 |
+| 2M | source50 | 50 | 0.962 | 0.962 | **0.979** | 28.9 / 90 | 28.3 / 104 | 28 / 102.2 |
+| 2M | vis50 | 10 | 0.936 | 0.936 | **0.941** | 19.4 / 23.8 | 18.6 / 23.6 | 19.2 / 24.9 |
+| 2M | vis50 | 50 | 0.963 | 0.963 | **0.981** | 31.8 / 84.7 | 32 / 86.5 | 32.4 / 114.5 |
+
+1M voyage-4 Wikipedia chunks. The source scopes are topic-coherent: whole k-means clusters fill 10.4% and
+50.5% of chunks. The visibility scopes are random. Recall@10 inside the `limit 50` call is in parentheses:
+
+| filter | k | master recall@k (@10 in call) | fixed recall@k (@10 in call) | escalate-when-short | master p50 / p95 ms | fixed p50 / p95 ms | escalate p50 / p95 ms |
+|---|---|---|---|---|---|---|---|
+| none | 10 | 0.968 (0.968) | **0.968** (0.968) | 0.968 | 12.9 / 19.9 | 11.5 / 21.3 | 17.3 / 31.5 |
+| none | 50 | 0.981 (0.984) | **0.981** (0.984) | 0.981 | 23.4 / 38.9 | 22.8 / 27.8 | 25.7 / 32.4 |
+| topic 10% (source) | 10 | 0.629 (0.629) | **0.837** (0.837) | 0.956 | 30.8 / 169.3 | 61.9 / 101.9 | 1577.9 / 1779.8 |
+| topic 10% (source) | 50 | 0.638 (0.813) | **0.777** (0.889) | 0.955 | 50 / 1087 | 91 / 1078.1 | 1027.2 / 1138.9 |
+| topic 50% (source) | 10 | 0.875 (0.875) | **0.959** (0.959) | 0.905 | 14 / 24.5 | 19 / 58.9 | 19.1 / 83.5 |
+| topic 50% (source) | 50 | 0.852 (0.908) | **0.951** (0.974) | 0.913 | 29.5 / 47 | 42.7 / 97 | 31.2 / 6857.4 |
+| random 10% (visibility) | 10 | 0.916 (0.916) | **0.990** (0.990) | 0.916 | 24.9 / 29.5 | 42.4 / 58.5 | 25 / 27.6 |
+| random 10% (visibility) | 50 | 0.765 (0.939) | **0.970** (0.994) | 0.809 | 40.8 / 48.7 | 73 / 87.4 | 47.8 / 6535.8 |
+| random 50% (visibility) | 10 | 0.957 (0.957) | **0.967** (0.967) | 0.957 | 13.6 / 24.9 | 18.4 / 32.5 | 14.4 / 24.1 |
+| random 50% (visibility) | 50 | 0.945 (0.978) | **0.971** (0.986) | 0.945 | 30.7 / 41.6 | 37.9 / 58.1 | 32 / 43.6 |
+
+At 1M real chunks, pinning 50,000 or 100,000 tuples on top of fix 1 gave the same recall to three
+decimals in every cell. The topic-coherent gap is not a scan budget.
+
+## Fix 2: statistics
+
+`refreshProjectionStatistics` (`src/core/search/projection-statistics.ts`) used to run
+`ANALYZE pages(text_projection_revision, knowledge_revision)` only. That is what import, sync, reindex and
+projection recovery end with. On Postgres it now runs two steps:
+1. `ANALYZE pages(text_projection_revision, knowledge_revision, deleted_at, source_id, type, slug)`.
+2. `ANALYZE content_chunks(model, modality, page_id)`, in the same transaction (30 s statement and 2 s lock
+ timeouts) behind a savepoint, so a concurrent index build only skips this step, with a warning that
+ names the command.
+
+An embed drain that embedded anything also runs step 2 once at its end. Both halves are needed:
+- `content_chunks` alone still sorts, because `p.deleted_at IS NULL` is priced at 0.5% and the planner
+ drives from a few pages.
+- `pages(deleted_at)` alone still sorts on the chunk filters.
+
+`test/e2e/vector-chunk-statistics-postgres.test.ts` proves both on a 12,000-chunk fixture: the stats-less
+plan misses `idx_chunks_embedding`, and the refreshed plan uses it. That test fails on master.
+
+The same synthetic corpora loaded with the fixed code, after only the refresh that import and sync run
+(`--states projection`), give these results:
+
+| chunks | filter | k | recall@k | p50 ms | p95 ms | incomplete | pooled plan |
+|---|---|---|---|---|---|---|---|
+| 1M | none | 50 | 0.990 | 20.3 | 23.7 | 0% | HNSW, 13 ms |
+| 1M | source10 | 50 | 0.986 | 56.5 | 65.3 | 0% | HNSW, 20 ms |
+| 1M | vis50 | 50 | 0.980 | 38.1 | 90.1 | 0% | HNSW, 9 ms |
+| 2M | none | 50 | 0.990 | 56.2 | 71.9 | 0% | HNSW, 11 ms |
+| 2M | source10 | 50 | 0.958 | 100.1 | 126.8 | 0% | HNSW, 22 ms |
+| 2M | vis50 | 50 | 0.986 | 39.5 | 173.3 | 0% | HNSW, 10 ms |
+
+Before the fix, the same state at 250k sorted every candidate and hit the 8 s budget (57% incomplete,
+unfiltered, k=50; "Statistics states and EXPLAIN" below). In the fully stats-less state at 1M and 2M,
+50%-scoped searches were 44% to 100% incomplete.
+
+## Recommendations (proposed, not shipped)
+
+1. **Topic-coherent selective scopes need an exact pass.** When a source scope is small and topically
+ coherent, the HNSW scan returns a full but wrong window, and no scan budget fixes that. The measured
+ way past it is the exact statement the escalate-when-short variant reached: recall@50 0.955 at about
+ 1.0 to 1.6 s per search on 1M real chunks. One option is to route scopes under a share threshold to
+ that exact statement first (master already skips the index walk for a small source share,
+ `INDEX_WALK_MIN_SCOPE_SHARE`). The other is a per-source partial HNSW index for large sources. Both
+ trade latency or storage for recall, so both are product decisions and need a preregistered confirmation on
+ real vectors.
+2. **Keep the index defaults (m 16, ef_construction 64, `vector`).** Measured candidates for a later
+ migration: `halfvec` for size (a third of the index, about 1.4x faster build, same recall), and
+ `ef_construction` 128 for about +0.02 to 0.03 unfiltered recall@10 at 1M and 2M.
+3. **Size `maintenance_work_mem` for the deferred ANN build.** `buildDeferredAnnIndexes`
+ (`src/core/embedding-ann-build.ts`) builds with the server's `maintenance_work_mem`. At 250k chunks,
+ 256 MB with 2 workers took 103 s against 24 s with 4 GB and 8 workers, after pgvector reported
+ `hnsw graph no longer fits into maintenance_work_mem after 55308 tuples`. `docs/ENGINES.md`
+ ("Vector index sizing") now gives the operator the sizing rule and the commands.
+
+The sections below record the pre-fix measurement of master (E5.4.1) and the build options (E5.4.2), which
+led to the fixes above.
+
+## What was measured
+
+**Query path.** Every cell calls `PostgresEngine.searchVector`, the vector arm hybrid search runs. That
+means `buildVectorSearchStatement`, the index walk (`searchIndexWalk`), the pooled statement with its
+escalations, `hasMore`, the exact fallback, `withVectorSettings`, `hnswEfSearchFor`, the
+`relaxed_order` iterative scan and the 8 s deadline. The bench wraps the engine's private
+`runVectorAttempt` and records which attempts ran. For pinned cells it also sets `hnsw.ef_search` (or
+`hnsw.max_scan_tuples`) inside the engine's transaction, after the engine's own settings. Shipped cells
+make the same extra round trip with a no-op value. "shipped" means the engine's own sizing:
+`ef_search` = the attempt window, so 200 or 500 for the index walk at limit 10 or 50, and 100 or 250 for
+the first pooled attempt, ×4 per escalation.
+
+**Metrics.**
+- **recall@k:** page recall against an exact per-page max-pooled ranking under the same filter.
+- **recall@10 in the call:** the first 10 results of a `limit 50` call.
+- **short:** fewer results than `min(k, eligible pages)`.
+- **incomplete:** `onVectorPoolMeta` fired; hybrid turns this into `vector_candidates_incomplete`.
+- **served by index walk:** the walk answered alone.
+- **mean attempts:** statements per search.
+
+Hybrid search calls the vector arm with `limit` = `min(max(limit×2, 50), 100)`, so the `k = 50` rows are
+the realistic ones.
+
+**Truth.** Exact top 100 pages per query and filter, computed in float64 from the exact float4 values
+loaded. 15 queries per corpus (3 per filter) were checked against gbrain's own `exactSql`, and all 15
+matched in identical order at every size.
+
+**Filters.**
+- **sourceN:** `sourceIds` covering N% of pages.
+- **visN:** `excludePrivate: true` with (100-N)% of pages `visibility: private`.
+
+Assignment is independent of topic.
+
+**Corpus** (`scripts/bench/hnsw-latent-corpus.ts`). Each chunk is a unit vector built from four parts:
+a shared mean direction, a super-topic and a topic direction, a rank-16 topic subspace (page plus chunk
+coefficients), and isotropic noise. Topics grow as 4·sqrt(pages). Each page holds 1 to 60 chunks (mean 7.0)
+of about 1,500 characters of text. A query is a random chunk moved within its subspace, with fresh noise.
+
+| chunks | pages | topics | LID (MLE, k=20) median [p10, p90] | cos random pair | same topic | same page | query to source chunk | query to top-1 |
+|---|---|---|---|---|---|---|---|---|
+| 250k | 35,588 | 730 | 14.6 [10.3, 19.2] | 0.174 | 0.492 | 0.725 | 0.789 | 0.790 |
+| 1M | 141,871 | 1,461 | 16.5 [11.7, 22.9] | 0.179 | 0.478 | 0.725 | 0.792 | 0.793 |
+| 2M | 284,410 | 2,066 | 17.2 [12.9, 25.7] | 0.179 | 0.488 | 0.722 | 0.790 | 0.793 |
+| 1M "hard" (rank 32, noise ×2) | 142,609 | 1,461 | 18.2 [12.7, 25.8] | 0.158 | 0.415 | 0.658 | 0.750 | 0.751 |
+
+On disk at 2M (after VACUUM ANALYZE), `content_chunks` takes 32 GB including its indexes. That is
+2.8 GB of heap, 13 GB of TOAST (vectors are stored out of line) and the 15.3 GiB HNSW index.
+
+**Server.** Ubicloud standard-16 (16 vCPU, 64 GB RAM, 320 GB disk), `pgvector/pgvector:pg16`
+(PostgreSQL 16.15, pgvector 0.8.7) in Docker, client on the same VM, one client, warm cache. Settings
+come from `scripts/bench/hnsw-scale-vm-setup.sh`: shared_buffers 16 GB, effective_cache_size 48 GB,
+random_page_cost 1.1, effective_io_concurrency 200, work_mem 4 MB, jit on (gbrain's read transaction
+turns it off). Default builds use maintenance_work_mem 4 GB, 12 GB or 20 GB by size, with 8 parallel
+maintenance workers and `CREATE INDEX CONCURRENTLY`, as the deferred ANN build does. Production adds
+network round trips: about 7 per attempt by the code path (BEGIN, settings read, settings write,
+timeout, statement, settings restore, COMMIT; counted from the code, not measured), with 2 attempts on a
+filtered search.
+
+## E5.4.1 results on the pre-fix code
+
+### A. Recall by `ef_search`, VACUUM ANALYZEd
+
+relaxed_order. The 40 to 400 and shipped columns share one index build. The 800 and 1000 columns come from a second load of the same corpus (`sweep-*`), so they also carry build-to-build variance of about ±0.02.
+
+| chunks | filter | k | 40 | 100 | 200 | 400 | 800 | 1000 | shipped | recall@10 in the call (shipped) |
+|---|---|---|---|---|---|---|---|---|---|---|
+| 250k | none | 10 | 0.963 | 0.974 | 0.974 | 0.994 | 0.990 | 0.990 | **0.974** | 0.974 |
+| 250k | none | 50 | 0.943 | 0.967 | 0.973 | 0.993 | 0.997 | 0.997 | **0.995** | 0.995 |
+| 250k | source10 | 10 | 0.856 | 0.886 | 0.908 | 0.952 | 0.983 | 0.990 | **0.886** | 0.886 |
+| 250k | source10 | 50 | 0.733 | 0.739 | 0.786 | 0.854 | 0.938 | 0.979 | **0.798** | 0.934 |
+| 250k | source50 | 10 | 0.964 | 0.974 | 0.974 | 0.993 | 0.998 | 0.998 | **0.974** | 0.974 |
+| 250k | source50 | 50 | 0.893 | 0.911 | 0.927 | 0.961 | 0.991 | 0.994 | **0.947** | 0.994 |
+| 250k | vis50 | 10 | 0.965 | 0.975 | 0.975 | 0.995 | 0.997 | 0.997 | **0.975** | 0.975 |
+| 250k | vis50 | 50 | 0.885 | 0.901 | 0.922 | 0.958 | 0.992 | 0.995 | **0.941** | 0.996 |
+| 250k | vis10 | 10 | 0.882 | 0.899 | 0.916 | 0.954 | 0.988 | 0.993 | **0.899** | 0.899 |
+| 250k | vis10 | 50 | 0.706 | 0.739 | 0.792 | 0.856 | 0.953 | 0.969 | **0.813** | 0.947 |
+| 1M | none | 10 | 0.963 | 0.963 | 0.963 | 0.980 | 0.987 | 0.987 | **0.963** | 0.963 |
+| 1M | none | 50 | 0.973 | 0.982 | 0.982 | 0.993 | 0.993 | 0.993 | **0.992** | 0.981 |
+| 1M | source10 | 10 | 0.901 | 0.912 | 0.924 | 0.952 | 0.958 | 0.979 | **0.912** | 0.912 |
+| 1M | source10 | 50 | 0.541 | 0.564 | 0.604 | 0.672 | 0.691 | 0.800 | **0.614** | 0.939 |
+| 1M | source50 | 10 | 0.969 | 0.969 | 0.969 | 0.990 | 0.987 | 0.987 | **0.969** | 0.969 |
+| 1M | source50 | 50 | 0.938 | 0.950 | 0.956 | 0.981 | 0.982 | 0.989 | **0.961** | 0.983 |
+| 1M | vis50 | 10 | 0.965 | 0.966 | 0.966 | 0.983 | 0.986 | 0.986 | **0.966** | 0.966 |
+| 1M | vis50 | 50 | 0.938 | 0.946 | 0.954 | 0.979 | 0.980 | 0.987 | **0.958** | 0.975 |
+| 1M | vis10 | 10 | 0.916 | 0.929 | 0.943 | 0.966 | 0.964 | 0.980 | **0.929** | 0.929 |
+| 1M | vis10 | 50 | 0.525 | 0.558 | 0.593 | 0.666 | 0.694 | 0.798 | **0.626** | 0.943 |
+| 2M | none | 10 | 0.945 | 0.965 | 0.965 | 0.973 | 0.974 | 0.976 | **0.965** | 0.965 |
+| 2M | none | 50 | 0.956 | 0.977 | 0.977 | 0.978 | 0.988 | 0.989 | **0.977** | 0.973 |
+| 2M | source10 | 10 | 0.928 | 0.950 | 0.954 | 0.959 | 0.970 | 0.970 | **0.950** | 0.950 |
+| 2M | source10 | 50 | 0.490 | 0.511 | 0.547 | 0.589 | 0.690 | 0.676 | **0.558** | 0.954 |
+| 2M | source50 | 10 | 0.951 | 0.975 | 0.975 | 0.978 | 0.978 | 0.980 | **0.975** | 0.975 |
+| 2M | source50 | 50 | 0.949 | 0.974 | 0.977 | 0.979 | 0.991 | 0.991 | **0.977** | 0.978 |
+| 2M | vis50 | 10 | 0.952 | 0.978 | 0.978 | 0.982 | 0.984 | 0.988 | **0.978** | 0.978 |
+| 2M | vis50 | 50 | 0.952 | 0.974 | 0.977 | 0.980 | 0.991 | 0.992 | **0.979** | 0.981 |
+| 2M | vis10 | 10 | 0.929 | 0.950 | 0.957 | 0.961 | 0.966 | 0.976 | **0.950** | 0.950 |
+| 2M | vis10 | 50 | 0.482 | 0.507 | 0.549 | 0.583 | 0.676 | 0.657 | **0.565** | 0.957 |
+
+### B. Shipped settings: latency and failure signals
+
+| chunks | filter | k | recall@k | p50 ms | p95 ms | p99 ms | short | incomplete | served by index walk | mean attempts |
+|---|---|---|---|---|---|---|---|---|---|---|
+| 250k | none | 10 | 0.974 | 7.9 | 15.8 | 20.8 | 0% | 0% | 100% | 1 |
+| 250k | none | 50 | 0.995 | 49 | 56 | 61.8 | 0% | 0% | 42% | 2.16 |
+| 250k | source10 | 10 | 0.886 | 16.1 | 18.6 | 34.8 | 0% | 0% | 0% | 2.01 |
+| 250k | source10 | 50 | 0.798 | 28.9 | 314.3 | 325 | 0% | 0% | 0% | 2.31 |
+| 250k | source50 | 10 | 0.974 | 13.3 | 22.4 | 26.6 | 0% | 0% | 43% | 1.57 |
+| 250k | source50 | 50 | 0.947 | 21.1 | 51.7 | 57.2 | 0% | 0% | 36% | 1.72 |
+| 250k | vis50 | 10 | 0.975 | 10.7 | 18.7 | 23.6 | 0% | 0% | 51% | 1.49 |
+| 250k | vis50 | 50 | 0.941 | 26.2 | 34.2 | 63.2 | 0% | 0% | 40% | 1.64 |
+| 250k | vis10 | 10 | 0.899 | 18.5 | 30.2 | 41.9 | 0% | 0% | 0% | 2.01 |
+| 250k | vis10 | 50 | 0.813 | 30.1 | 135.2 | 149.3 | 0% | 0% | 0% | 2.36 |
+| 1M | none | 10 | 0.963 | 12.6 | 18.9 | 21.6 | 0% | 0% | 100% | 1 |
+| 1M | none | 50 | 0.992 | 15 | 26.2 | 38.1 | 0% | 0% | 100% | 1 |
+| 1M | source10 | 10 | 0.912 | 17.9 | 26.9 | 44.1 | 0% | 0% | 0% | 2 |
+| 1M | source10 | 50 | 0.614 | 29.4 | 59.5 | 84.2 | 0% | 0% | 0% | 2.03 |
+| 1M | source50 | 10 | 0.969 | 12.1 | 22.9 | 86.1 | 0% | 0% | 55% | 1.45 |
+| 1M | source50 | 50 | 0.961 | 38.8 | 88.7 | 119.1 | 0% | 0% | 18% | 2.27 |
+| 1M | vis50 | 10 | 0.966 | 14.1 | 20.3 | 29.1 | 0% | 0% | 53% | 1.47 |
+| 1M | vis50 | 50 | 0.958 | 33.5 | 81 | 91.7 | 0% | 0% | 25% | 2.19 |
+| 1M | vis10 | 10 | 0.929 | 21.3 | 44.5 | 77.8 | 0% | 0% | 0% | 2 |
+| 1M | vis10 | 50 | 0.626 | 35.1 | 86.9 | 148.8 | 0% | 0% | 0% | 2.05 |
+| 2M | none | 10 | 0.965 | 9.1 | 17.4 | 25.4 | 0% | 0% | 100% | 1 |
+| 2M | none | 50 | 0.977 | 16.7 | 20.3 | 24.4 | 0% | 0% | 100% | 1 |
+| 2M | source10 | 10 | 0.950 | 21 | 26 | 29.8 | 0% | 0% | 0% | 2 |
+| 2M | source10 | 50 | 0.558 | 32.8 | 46 | 104.1 | 0% | 0% | 0% | 2.03 |
+| 2M | source50 | 10 | 0.975 | 14.5 | 19.3 | 23.2 | 0% | 0% | 39% | 1.61 |
+| 2M | source50 | 50 | 0.977 | 26.9 | 87.2 | 119 | 0% | 0% | 39% | 1.72 |
+| 2M | vis50 | 10 | 0.978 | 17.2 | 28.4 | 33.5 | 0% | 0% | 39% | 1.61 |
+| 2M | vis50 | 50 | 0.979 | 31.9 | 92.2 | 121.9 | 0% | 0% | 39% | 1.76 |
+| 2M | vis10 | 10 | 0.950 | 23.4 | 31.3 | 35 | 0% | 0% | 0% | 2 |
+| 2M | vis10 | 50 | 0.565 | 37.6 | 108.3 | 187.1 | 0% | 0% | 0% | 2.05 |
+
+Latency stays well inside budget once statistics exist: p95 is under 60 ms unfiltered and under 110 ms
+filtered at 2M. The k=50 filtered p95 tail (90 to 310 ms) comes from searches whose index walk was
+rejected and whose pooled statement re-ran.
+
+### C. `relaxed_order` against `strict_order`
+
+At the shipped `ef_search`, strict order is never better. It costs up to 0.11 recall@10 on 10% filters
+at 250k and 1M (for example source10 k=10: 0.889 relaxed against 0.780 strict at 250k, 0.916 against
+0.859 at 1M). At 2M the two are within 0.03, and at k=50 under a 10% filter both modes sit at 0.58 to 0.79.
+The #6132 default stands.
+
+### D. The cause: the first pool attempt's `max_scan_tuples`
+
+Shipped `ef_search`, relaxed_order. Each size is a separate load. The 250k rows ran on the 4-vCPU Capy
+machine, so compare their recall, not their latency.
+
+| chunks | filter | k | max_scan_tuples | recall@k | recall@10 in call | p50 ms | p95 ms |
+|---|---|---|---|---|---|---|---|
+| 250k | source10 | 10 | shipped (2,000) | 0.899 | 0.899 | - | - |
+| 250k | source10 | 10 | 8,000 | 0.994 | 0.994 | - | - |
+| 250k | source10 | 50 | shipped | 0.794 | 0.953 | - | - |
+| 250k | source10 | 50 | 8,000 | 0.982 | 0.997 | - | - |
+| 250k | vis10 | 50 | shipped | 0.794 | 0.938 | - | - |
+| 250k | vis10 | 50 | 20,000 | 0.985 | 0.997 | - | - |
+| 1M | source10 | 10 | shipped | 0.898 | 0.898 | 19.2 | 26.1 |
+| 1M | source10 | 10 | 20,000 | 0.982 | 0.982 | 25.7 | 41.4 |
+| 1M | source10 | 50 | shipped | 0.594 | 0.918 | 29.7 | 51.6 |
+| 1M | source10 | 50 | 8,000 | 0.913 | 0.990 | 38.7 | 46.9 |
+| 1M | source10 | 50 | 20,000 | 0.987 | 0.994 | 48.0 | 57.9 |
+| 1M | vis10 | 50 | shipped | 0.620 | 0.926 | 32.5 | 83.4 |
+| 1M | vis10 | 50 | 20,000 | 0.985 | 0.997 | 49.2 | 57.0 |
+| 2M | source10 | 10 | shipped | 0.927 | 0.927 | 23.2 | 28.8 |
+| 2M | source10 | 10 | 20,000 | 0.988 | 0.988 | 29.5 | 51.7 |
+| 2M | source10 | 50 | shipped | 0.572 | 0.963 | 35.8 | 44.9 |
+| 2M | source10 | 50 | 8,000 | 0.835 | 0.989 | 48.1 | 60.4 |
+| 2M | source10 | 50 | 20,000 | 0.958 | 0.992 | 68.9 | 93.1 |
+| 2M | vis10 | 50 | shipped | 0.544 | 0.964 | 41.3 | 47.5 |
+| 2M | vis10 | 50 | 20,000 | 0.959 | 0.992 | 69.4 | 91.1 |
+| 1M, 2M | none | 10, 50 | 8,000 or 20,000 | unchanged | unchanged | ±1 ms | ±4 ms |
+
+Why: a filtered search's index walk orders the whole index, so under a 10% filter it comes back short
+and is rejected. The first pooled attempt then asks for 250 eligible chunks while visiting at most 2,000
+tuples, which is about 200 eligible chunks at 10%. Because those chunks already cover 50 pages, the
+attempt is accepted (mean attempts 2.0 to 2.05 at 1M and 2M in table B: the rejected walk plus one accepted pool attempt). But at 10% selectivity
+and about 7 chunks per page, the 50th-best eligible page sits roughly 3,500 chunks deep, past the
+visit budget. Recall@10 survives because the top ten pages
+lie inside the visited set. `ef_search` sizes only the first candidate list, so raising it barely moves
+recall@50 at 1M and 2M. The EXPLAIN below shows that pooled attempt: 2,242 index tuples visited, 250
+candidates kept.
+
+### E. Harder geometry (1M, rank 32, noise ×2)
+
+The conclusion holds. Unfiltered recall@10 is 0.988. 10%-filtered recall@10 is 0.894 (source) and
+0.905 (visibility), and recall@50 is 0.588 and 0.581. `ef_search` 1000 gives 0.963 and 0.964 at k=10
+and 0.739 and 0.725 at k=50.
+
+## Statistics states and EXPLAIN
+
+The pgvector plan-flip lesson says to EXPLAIN at target size and across statistics states, and the
+bench does. Each corpus is measured in three states, and the bench writes EXPLAIN (ANALYZE, BUFFERS,
+SETTINGS) of the index walk, the first pooled attempt and a ×4 escalation to `explain/` for every
+state, filter, k and `random_page_cost` (1.1 and 4).
+
+- **fresh:** right after the load and index build. Autovacuum is off, nothing is ANALYZEd,
+ `pages.reltuples` is 0 from the empty-table init, and `content_chunks` has no column statistics.
+- **analyze:** after a plain `ANALYZE`.
+- **vacuum:** after `VACUUM ANALYZE` plus `refreshProjectionStatistics`; the main grid runs here.
+- **projection:** only the narrow `ANALYZE pages(text_projection_revision, knowledge_revision)` that
+ import and sync run. Measured at 250k on the 4-vCPU machine.
+
+Shipped settings:
+
+| chunks | state | filter | k | recall@k | p50 ms | p95 ms | incomplete | walk served |
+|---|---|---|---|---|---|---|---|---|
+| 250k | fresh | none | 50 | 0.999 | 6,083 | 6,182 | 0% | 44% |
+| 250k | fresh | source50 | 50 | 0.988 | 1,691 | 3,372 | 0% | 42% |
+| 250k | projection | none | 50 | 0.429 | 8,078 | 8,105 | 57% | 43% |
+| 250k | projection | vis50 | 50 | 0.321 | 8,079 | 8,112 | 67% | 33% |
+| 250k | analyze | source10 | 50 | 0.802 | 29.5 | 262.8 | 0% | 0% |
+| 1M | fresh | source10 | 10 | 1.000 | 3,393 | 3,413 | 0% | 0% |
+| 1M | fresh | source50 | 50 | 0.937 | 10,003 | 10,004 | 54% | 0% |
+| 1M | fresh | vis50 | 50 | 0.957 | 6,365 | 8,018 | 44% | 28% |
+| 1M | analyze | source10 | 50 | 0.608 | 30.1 | 35.4 | 0% | 0% |
+| 2M | fresh | none | 50 | 0.988 | 29.0 | 33.7 | 0% | 100% |
+| 2M | fresh | source10 | 10 | 1.000 | 4,921 | 4,999 | 0% | 0% |
+| 2M | fresh | source50 | 10 | 0.000 | 10,002 | 10,003 | 100% | 0% |
+| 2M | fresh | source50 | 50 | 0.000 | 10,002 | 10,003 | 100% | 0% |
+| 2M | fresh | vis50 | 50 | 0.396 | 8,016 | 8,020 | 60% | 40% |
+| 2M | analyze | source10 | 50 | 0.538 | 36.4 | 48.4 | 0% | 0% |
+| 2M | analyze | vis50 | 50 | 0.989 | 33.6 | 108.6 | 0% | 40% |
+
+Without statistics the pooled statement sorts every eligible chunk by distance instead of walking the
+index. A selective filter makes that exact and slow (3 to 5 s at 10%). A broad one runs past the 8 s
+budget: searches end at about 10 s with zero vector rows and the arm reports incomplete. After ANALYZE
+the plans return to HNSW and table A applies. No plan in any state used JIT, and
+`random_page_cost` 1.1 against 4 changed a plan in only 3 of 504 EXPLAINs (250k m=32 builds, ×4
+escalation, unfiltered).
+
+EXPLAIN ANALYZE timings at random_page_cost 1.1, k=50 ("no: sort" = `Sort Key: (cc.embedding <=> $q)`
+over the filtered join instead of the HNSW index):
+
+| chunks | state | filter | index walk ms (HNSW?) | pool ms (HNSW?) | pool ×4 ms (HNSW?) |
+|---|---|---|---|---|---|
+| 250k | fresh | none | 19 (yes) | 3,065 (no: sort) | 3,127 (no: sort) |
+| 250k | vacuum | none | 10 (yes) | 5 (yes) | 24 (yes) |
+| 250k | vacuum | source10 | 7 (yes) | 10 (yes) | 237 (no: sort) |
+| 1M | fresh | none | 17 (yes) | > 8,000 (no: sort) | > 8,000 (no: sort) |
+| 1M | fresh | vis50 | 10 (yes) | 6,405 (no: sort) | 6,434 (no: sort) |
+| 1M | vacuum | source10 | 8 (yes) | 14 (yes) | 52 (yes) |
+| 2M | fresh | none | 61 (yes) | > 8,000 (no: sort) | > 8,000 (no: sort) |
+| 2M | fresh | source10 | > 8,000 (yes, then a pages-first nested loop) | 2,944 (no: sort) | 2,960 (no: sort) |
+| 2M | fresh | vis50 | 11 (yes) | > 8,000 (no: sort) | > 8,000 (no: sort) |
+| 2M | vacuum | none | 16 (yes) | 7 (yes) | 38 (yes) |
+| 2M | vacuum | source10 | 8 (yes) | 17 (yes) | 77 (yes) |
+| 2M | vacuum | vis50 | 12 (yes) | 10 (yes) | 58 (yes) |
+
+2M, fresh, 10% source filter, first pooled attempt. The planner estimates one page row, nested-loops
+28,698 pages into their chunks and sorts 204,136 rows (vector literal shortened to `$q`, source-boost
+CASE omitted):
+
+```
+Sort (actual time=2915.766..2915.770 rows=10 loops=1)
+ CTE hnsw_candidates
+ -> Limit (actual time=2915.361..2915.382 rows=100 loops=1)
+ -> Sort (cost=10965.47..10965.47 rows=1 width=358) (actual time=2915.361..2915.375 rows=100 loops=1)
+ Sort Key: ((cc.embedding <=> $q))
+ Sort Method: top-N heapsort Memory: 310kB
+ -> Nested Loop (cost=99.92..10965.46 rows=1 width=358) (actual time=0.082..2838.124 rows=204136 loops=1)
+ -> Nested Loop (cost=0.29..3.54 rows=1 width=204) (actual time=0.024..29.678 rows=28698 loops=1)
+ -> Seq Scan on sources s (rows=4)
+ -> Index Scan using pages_dedup_idx on pages p (cost=0.29..2.52 rows=1 width=204) (actual ... rows=7174 loops=4)
+ Index Cond: ((source_id = s.id) AND (source_id = ANY ('{bench-a}'::text[])))
+ -> Bitmap Heap Scan on content_chunks cc (actual time=0.003..0.007 rows=7 loops=28698)
+ Recheck Cond: (p.id = page_id)
+ -> Bitmap Index Scan on idx_chunks_page (rows=7 loops=28698)
+Settings: jit = 'off'
+```
+
+2M, VACUUM ANALYZEd, same filter, k=50, first pooled attempt. The HNSW iterative scan visits 2,242
+tuples, keeps 250 candidates and is accepted:
+
+```
+Sort (cost=7894.89..7895.02 rows=50 width=357) (actual time=16.885..16.890 rows=50 loops=1)
+ CTE hnsw_candidates
+ -> Limit (cost=3999.07..7865.66 rows=250 width=1309) (actual time=1.314..15.782 rows=250 loops=1)
+ -> Nested Loop (actual time=1.314..15.747 rows=250 loops=1)
+ -> Nested Loop (actual time=1.280..12.093 rows=250 loops=1)
+ -> Index Scan using idx_chunks_embedding on content_chunks cc (cost=3998.63..2641530.52 rows=2000063 width=1155) (actual time=1.247..9.120 rows=2242 loops=1)
+ Order By: (embedding <=> $q::vector)
+ Filter: ((embedding IS NOT NULL) AND (modality = 'text'::text) AND (model = 'bench:latent'::text))
+ -> Memoize (actual time=0.001..0.001 rows=0 loops=2242)
+ -> Index Scan using pages_pkey on pages p (actual time=0.003..0.003 rows=0 loops=658)
+ Index Cond: (id = cc.page_id)
+ Filter: ((deleted_at IS NULL) AND (source_id = ANY ('{bench-a}'::text[])) AND ...)
+```
+
+2M, VACUUM ANALYZEd, unfiltered k=50 index walk: `ann` is an HNSW scan of 500 rows in 5.7 ms, then joined by key; 15.6 ms in total.
+
+## E5.4.2 results: index build options (measurement only)
+
+Shipped search settings, VACUUM ANALYZEd, 100 queries. Builds use `CREATE INDEX CONCURRENTLY ... WITH (m, ef_construction)`, with maintenance_work_mem 4 GB, 12 GB or 20 GB by size and 8 parallel workers, unless the row says otherwise. Index size depends only on the type, because pgvector stores one element per page at 1,024 dimensions. Recall moves by up to ±0.02 between builds with the same options (each build is a new graph), so differences smaller than that are noise.
+
+| chunks | index | build s | size GiB | none @10 | none @50 | source10 @10 | source10 @50 | source10 @10 in k=50 | none k=50 p50 ms |
+|---|---|---|---|---|---|---|---|---|---|
+| 250k | vector:16:64 (default) | 24.1 | 1.91 | 0.974 | 0.995 | 0.886 | 0.798 | 0.934 | 49 |
+| 250k | vector:16:128 | 31.6 | 1.91 | 0.996 | 0.998 | 0.948 | 0.866 | 0.970 | 51.7 |
+| 250k | vector:16:200 | 37.2 | 1.91 | 0.981 | 1.000 | 0.934 | 0.868 | 0.966 | 51.9 |
+| 250k | vector:24:64 | 27.6 | 1.91 | 0.983 | 0.987 | 0.873 | 0.835 | 0.939 | 52.2 |
+| 250k | vector:24:128 | 33.6 | 1.91 | 0.980 | 0.980 | 0.916 | 0.853 | 0.948 | 53.1 |
+| 250k | vector:24:200 | 42.9 | 1.91 | 1.000 | 0.999 | 0.965 | 0.912 | 0.991 | 53.5 |
+| 250k | vector:32:64 | 30.2 | 1.91 | 0.986 | 0.987 | 0.893 | 0.880 | 0.957 | 55.1 |
+| 250k | vector:32:128 | 42 | 1.91 | 0.998 | 1.000 | 0.946 | 0.926 | 0.985 | 54.2 |
+| 250k | vector:32:200 | 49.3 | 1.91 | 1.000 | 1.000 | 0.969 | 0.929 | 0.991 | 54.5 |
+| 250k | vector:16:64:mwm=256MB:par=2 | 103.3 | 1.91 | 0.995 | 0.996 | 0.934 | 0.838 | 0.967 | 51.1 |
+| 250k | halfvec:16:64 | 17.9 | 0.64 | 0.974 | 0.997 | 0.901 | 0.781 | 0.943 | 45.5 |
+| 250k | halfvec:16:128 | 22.2 | 0.64 | 0.957 | 0.999 | 0.900 | 0.812 | 0.940 | 48.8 |
+| 250k | halfvec:16:200 | 28 | 0.64 | 0.960 | 1.000 | 0.918 | 0.856 | 0.965 | 48.6 |
+| 250k | halfvec:24:64 | 20.8 | 0.64 | 0.988 | 0.997 | 0.894 | 0.854 | 0.966 | 50.3 |
+| 250k | halfvec:24:128 | 25.9 | 0.64 | 0.999 | 0.999 | 0.945 | 0.891 | 0.983 | 50.2 |
+| 250k | halfvec:24:200 | 34.3 | 0.64 | 1.000 | 1.000 | 0.953 | 0.895 | 0.987 | 50.8 |
+| 250k | halfvec:32:64 | 23.9 | 0.64 | 0.983 | 0.988 | 0.886 | 0.845 | 0.945 | 51.8 |
+| 250k | halfvec:32:128 | 33.9 | 0.64 | 0.980 | 0.990 | 0.934 | 0.881 | 0.968 | 51.9 |
+| 250k | halfvec:32:200 | 40.6 | 0.64 | 1.000 | 1.000 | 0.967 | 0.922 | 0.994 | 52.3 |
+| 1M | vector:16:64 (default) | 103.4 | 7.63 | 0.963 | 0.992 | 0.912 | 0.614 | 0.939 | 15 |
+| 1M | vector:16:128 | 129.6 | 7.63 | 0.997 | 0.997 | 0.942 | 0.678 | 0.960 | 16.1 |
+| 1M | vector:16:200 | 142.9 | 7.63 | 0.967 | 0.998 | 0.928 | 0.717 | 0.945 | 16.9 |
+| 1M | vector:24:64 | 112.5 | 7.63 | 0.944 | 0.981 | 0.873 | 0.592 | 0.903 | 18.6 |
+| 1M | vector:32:64 | 125.3 | 7.63 | 0.983 | 0.994 | 0.889 | 0.601 | 0.922 | 17.6 |
+| 1M | vector:32:200 | 201.1 | 7.63 | 0.998 | 0.999 | 0.948 | 0.750 | 0.976 | 17 |
+| 1M | halfvec:16:64 | 71.8 | 2.54 | 0.984 | 0.992 | 0.920 | 0.592 | 0.938 | 14.4 |
+| 1M | halfvec:32:200 | 168.8 | 2.54 | 0.985 | 0.998 | 0.942 | 0.730 | 0.970 | 15.5 |
+| 2M | vector:16:64 (default) | 235.3 | 15.26 | 0.965 | 0.977 | 0.950 | 0.558 | 0.954 | 16.7 |
+| 2M | vector:16:128 | 284.2 | 15.26 | 0.981 | 0.996 | 0.965 | 0.590 | 0.977 | 26.4 |
+| 2M | halfvec:16:64 | 160.7 | 5.09 | 0.953 | 0.977 | 0.946 | 0.558 | 0.947 | 19.5 |
+
+What the table shows:
+- **`ef_construction` 128 or 200** raises unfiltered recall@10 to 0.98 to 1.0 in 9 of 10 builds (the
+ exception is 1M m16/efc200 at 0.967), for 25 to 95% more build time. It lifts 10%-filtered recall@50 by 0.03 to 0.14 but leaves it at 0.59 to
+ 0.93, and it does not move the max_scan_tuples ceiling.
+- **`m` 24 or 32 at `ef_construction` 64** shows no consistent gain. At 1M its filtered recall@10 is
+ lower (0.873 and 0.889, against 0.912).
+- **`halfvec`** matches `vector` recall within noise, builds about 1.4x faster (1.35x at 250k, 1.44x at
+ 1M, 1.46x at 2M), and is a third of the size. At 1.28M chunks that is about 3.3 GiB of index instead of about 9.8 GiB, which
+ decides whether the index stays in memory on a smaller host. Adopting it needs a column migration:
+ `ALTER TABLE ... TYPE halfvec(1024)` took 273 s at 2M.
+- **Production-like build memory**: maintenance_work_mem 256 MB with 2 workers gave the same graph
+ quality, but the build took 4.3x longer (103 s against 24 s at 250k) after pgvector spilled.
+
+## Limitations
+
+- **Real-vector coverage is one corpus.** The 1M real corpus is English Wikipedia: 207,185 articles, 4.8
+ chunks each, about 920 characters per chunk, LID median 20.7 [14.1, 35.9], query top-1 cosine 0.70.
+ Queries are the first sentence of random chunks, embedded as voyage-4 queries. A personal brain's mail,
+ notes and transcripts may be more or less clustered. The truth was checked against gbrain's own
+ `exactSql` for 15 queries: the top-10 and top-50 sets matched every time, and the order differed once
+ below rank 50 (float near-ties).
+- **The synthetic geometry is generated, not voyage-4 output.** Its local intrinsic dimension (median 15
+ to 17) is a little below the real corpus (20.7). It reproduced the random-scope failure and the fix,
+ but it cannot show the topic-coherent case. That case needs scopes that line up with clusters.
+- **Truth and recall are page-level after max-pooling.** That matches what search returns. 100 queries
+ give a standard error of about ±0.01 to 0.02 on recall@10.
+- **Latency is server-local and single-client, with the index cached** (15 GiB index, 64 GB RAM).
+ Production adds network round trips (about 7 per attempt), and a host that can't cache the index pays
+ disk reads.
+- **One build per cell.** HNSW graph variance between builds is about ±0.02, and up to 0.03 at 2M. The
+ fix comparisons share one build per corpus, so their differences don't carry that variance.
+- **Some rows ran on a 4-vCPU Capy machine** with a 128 MB shared_buffers container: the pre-fix
+ `projection` row and the 250k max_scan_tuples rows. Their plan shapes and recall are comparable; their
+ latencies are not.
+
+## Reproduce
+
+```bash
+# VM (Ubicloud standard-16, 320 GB): bootstrap Docker, Bun 1.4.2 and a tuned pgvector/pg16 on 127.0.0.1:5434
+UBI_OWNER=<thread> scripts/ubicloud/ubi-runner.sh up -s standard-16 -S 320
+scripts/ubicloud/ubi-runner.sh sync <vm> . && scripts/ubicloud/ubi-runner.sh ssh <vm> 'cd work/gbrain && bash scripts/bench/hnsw-scale-vm-setup.sh'
+export DATABASE_URL=postgresql://postgres:[email protected]:5434/postgres
+B=scripts/bench/hnsw-iterative-scan.ts
+
+# main grid + stats states + EXPLAIN + E5.4.2 builds (250k shown; 1M used --build-mwm 12GB, 2M 20GB)
+bun $B --corpus latent --chunks 250000 --queries 100 --workers 14 --explain --build-mwm 4GB --build-parallel 8 \
+ --builds vector:16:128,vector:16:200,vector:24:64,vector:24:128,vector:24:200,vector:32:64,vector:32:128,vector:32:200,vector:16:64:mwm=256MB:par=2,halfvec:16:64,halfvec:16:128,halfvec:16:200,halfvec:24:64,halfvec:24:128,halfvec:24:200,halfvec:32:64,halfvec:32:128,halfvec:32:200
+bun $B --corpus latent --chunks 1000000 --queries 100 --workers 14 --explain --build-mwm 12GB --build-parallel 8 \
+ --builds vector:16:128,vector:16:200,vector:24:64,vector:32:64,vector:32:200,halfvec:16:64,halfvec:32:200
+bun $B --corpus latent --chunks 2000000 --queries 100 --workers 14 --explain --build-mwm 20GB --build-parallel 8 --builds vector:16:128,halfvec:16:64
+
+# ef_search 800/1000 and strict_order (2M used --queries 50)
+bun $B --corpus latent --chunks <n> --queries 100 --workers 14 --states '' --verify 0 --ef shipped,400,800,1000 --modes relaxed_order,strict_order
+# max_scan_tuples pin
+bun $B --corpus latent --chunks <n> --queries 100 --workers 14 --states '' --verify 0 --filters none,source10,vis10 --ef shipped --max-scan-tuples shipped,8000,20000
+# harder geometry
+bun $B --corpus latent --chunks 1000000 --queries 100 --workers 14 --states '' --seed 6133 --latent-rank 32 --latent-noise 0.3 --ef shipped,400,1000 --filters none,source10,vis10
+# fixes, same database: load with the fixed tree (--keep), then rerun a master checkout and the
+# escalate-when-short variant against it with --db (each run's --out needs the load's truth.json)
+bun $B --corpus latent --chunks 1000000 --queries 100 --workers 14 --states projection --explain --keep --build-mwm 12GB --build-parallel 8 --ef shipped,400 --out out/fixed-1000000
+bun $B --corpus latent --chunks 1000000 --queries 100 --db <db from out/fixed-1000000/results.json> --ef shipped --verify 0 --out out/master-1000000
+# real vectors: prepare 1M Wikipedia chunks, embed them with voyage-4 (capped by --max-usd, ledger.json beside the corpus)
+python3 scripts/bench/hnsw-real-corpus-prep.py corpus --chunks 1000000
+VOYAGE_API_KEY=... bun $B --corpus dir --corpus-dir corpus --chunks 1000000 --queries 100 --workers 14 --states '' --explain --keep \
+ --build-mwm 12GB --build-parallel 8 --ef shipped,400,1000 --max-scan-tuples shipped,20000 --max-usd 28 --out out/real-master
+bun $B --corpus dir --corpus-dir corpus --chunks 1000000 --queries 100 --db <db> --ef shipped --max-scan-tuples shipped,50000,100000 --verify 0 --out out/real-fixed
+# pages-only (import/sync) statistics state
+bun $B --corpus latent --chunks 250000 --queries 30 --states projection --verify 0 --filters none,source10,source50,vis50 --ef shipped --explain --no-grid
+```
+
+**Wall time.** Two standard-16 VMs ran 04:20 to 06:22 PT (VM A, 250k then 1M) and 04:20 to 06:05 PT
+(VM B, 2M) on October 9, 2026, about 60 vCPU-hours in total, and both were destroyed after the run.
+
+| run | load + truth | default build | full run |
+|---|---|---|---|
+| 250k main | 38 s | 24 s | 34 min (18 builds included) |
+| 1M main | 153 s | 103 s | 62 min (30 min of it in the fresh-state pass) |
+| 2M main | 223 s | 235 s | 70 min (36 min in the fresh-state pass) |
+| sweeps (250k / 1M / 2M) | | | 6 / 8 / 11 min |
+| max_scan_tuples (1M / 2M) | | | 5 / 9 min |
+| fix comparison, synthetic (fixed / master / escalate) | 1M: 4 min | 1M: 2 min | 1M: 9 / 1 / 2 min; 2M: 17 / 1 / 2 min |
+| real 1M (prep, voyage-4 embedding, load, grid) | prep 27 s, embedding 38 min | 2 min | 46 min master grid; fixed 3 min, escalate 5 min |
+
+The fix runs used two more standard-16 VMs on October 9: about 07:05 to 07:45 PT for the synthetic
+comparison, and about 06:55 to 08:00 PT for the real corpus. Both were destroyed after the runs. The real
+corpus (chunks, vectors, queries and ledger) is kept outside the repository on the builder machine, so a rerun pays nothing for embeddings.
+
+## Changelog
+
+- 2026-10-09: fix 1 (pooled attempts scan 20,000 tuples) and fix 2 (import, sync, reindex and embed
+ drains refresh the content_chunks and search-filter page statistics) ship with the same-database
+ comparisons above. The real-vector confirmation used 1M voyage-4 Wikipedia chunks ($13.07), and found
+ that topic-coherent selective scopes remain a gap. `--corpus dir`, `--max-scan-tuples`, the `projection`
+ stats state and `scripts/bench/hnsw-real-corpus-prep.py` were added to the bench.
+
+- 2026-10-09: first scale measurement (E5.4.1, E5.4.2) at 250k, 1M and 2M synthetic-latent chunks.
+ `scripts/bench/hnsw-iterative-scan.ts` gains `--corpus latent` (`scripts/bench/hnsw-latent-corpus.ts`),
+ the ef_search, max_scan_tuples, filter, statistics-state and build grids, and EXPLAIN capture; the VM
+ bootstrap is `scripts/bench/hnsw-scale-vm-setup.sh`.
diff --git a/llms-full.txt b/llms-full.txt
index 0e43f0be6b..861a9aae9c 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5229,6 +5229,40 @@ the object is absent. Highly selective queries may correctly choose an exact
plan. The [retrieval guide](architecture/RETRIEVAL.md#named-thing-retrieval-per-page-pool--title--alias--evidence)
describes bounded candidate recovery and incomplete-result metadata.
+On Postgres the same refresh also analyzes the page columns every search
+filter reads (`deleted_at`, `source_id`, `type`, `slug`) and
+`content_chunks(model, modality, page_id)`, and an embed drain that embedded
+anything analyzes those chunk columns once at its end (each ANALYZE bounded by
+a 30 s statement and 2 s lock timeout). Without those statistics the vector
+candidate statement sorts every eligible chunk instead of walking the HNSW
+index, and at 1M chunks and above that sort runs past the 8 s vector budget,
+so hybrid search falls back to keyword-only results until autovacuum
+analyzes the tables. If a refresh is skipped (a lock, or a role that does not
+own the tables), run `ANALYZE content_chunks(model, modality, page_id)` and
+`ANALYZE pages` as the table owner.
+
+### Vector index sizing
+
+The chunk HNSW index stores each vector beside its graph links, so at 1,024
+dimensions it takes about 7.6 GiB per million chunks as `vector` (about
+9.8 GiB for a 1.28M-chunk brain) and a third of that as `halfvec`. The
+deferred ANN build (`gbrain migrate embeddings`, `gbrain reindex --vectors`)
+runs `CREATE INDEX CONCURRENTLY` with the server's `maintenance_work_mem`.
+When the graph does not fit, pgvector logs `hnsw graph no longer fits into
+maintenance_work_mem` and the build slows several-fold: 4.3x at 250k chunks
+with 256 MB. Before a large build, raise it on the brain host to the index
+size plus about 10% (Supabase: `supabase postgres-config update --config
+maintenance_work_mem=12GB --project-ref <ref> --experimental`, which reloads
+without a restart; self-hosted: `ALTER SYSTEM SET maintenance_work_mem =
+'12GB'` and `SELECT pg_reload_conf()`), and give it
+`max_parallel_maintenance_workers` of about half the cores: a 1M-chunk build
+took 103 s on 16 vCPU with 12 GB and 8 workers. Measured, not shipped:
+`halfvec` gives the same recall with an index a third the size, and
+`ef_construction` 128 adds about 0.02 to 0.03 unfiltered recall@10 for about
+25% more build time. Both need a migration or a rebuild, so the defaults stay
+(m 16, ef_construction 64, `vector`). Measurements and method:
+[`docs/eval/hnsw-scale-bench.md`](eval/hnsw-scale-bench.md).
+
### Opt-in RLS source-scope binding (`GBRAIN_RLS_SCOPE_BINDING`)
Defense-in-depth layer for Postgres deployments that want the database itself
diff --git a/scripts/bench/hnsw-iterative-scan.ts b/scripts/bench/hnsw-iterative-scan.ts
index b7d11fbd7d..78a59dd467 100644
--- a/scripts/bench/hnsw-iterative-scan.ts
+++ b/scripts/bench/hnsw-iterative-scan.ts
@@ -1,58 +1,141 @@
#!/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.
+ * HNSW vector-search bench (#6132 iterative scan; E5.4 scale and build
+ * options). 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.
+ * needs CREATEDB and CREATE EXTENSION vector, and superuser for the latent
+ * corpus's visibility flips), seeds it, builds the HNSW index and measures
+ * every query through PostgresEngine.searchVector: the index walk, the
+ * pooled statement, its escalations, the exact fallback and the
+ * `onVectorPoolMeta` signal that hybrid search turns into
+ * `vector_candidates_incomplete`. Recall@k is of pages, against an exact
+ * max-pooled ranking under the same filter. Drops the database unless --keep.
*
- * 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.
+ * Corpora:
+ * --corpus repo (default): one page per document of this repository's
+ * docs/, skills/, src/ and test/ text (chunks of up to 800 characters, at
+ * most 60 per page), embedded for real (`--embed voyage`: voyage-4 at 1024
+ * dims; `--embed openai`: text-embedding-3-small at 1536; `synthetic`: a
+ * 16-dim latent tiled across the dimensions, no network), cached under
+ * `--cache` (default ~/.capy/work/w6/bench-cache). Queries are the first
+ * sentence of random chunks; truth is the engine's exact statement.
+ * --corpus latent: `--chunks` synthetic-latent chunks (see
+ * hnsw-latent-corpus.ts: topic/page/chunk structure, low-rank local
+ * variation, about 1,500 characters of text per chunk), loaded by
+ * `--workers` parallel binary COPY streams while the exact per-page truth
+ * is computed in float64 in the same pass. `--verify N` checks N queries
+ * per filter against the engine's own exact statement. No network.
+ * Shape knobs: --seed, --latent-rank, --latent-noise, --latent-query-noise.
+ *
+ * Measurement grid (each cell: recall@k, p50/p95/p99 ms, short results,
+ * `vector_candidates_incomplete`, which statement served, exact fallbacks):
+ * --filters none,source10,source50,vis50,vis10 (repo default: source10,source50).
+ * sourceN: sourceIds covering N% of pages; visN: excludePrivate
+ * with (100-N)% of pages `visibility: private` (latent only).
+ * --k 10,50
+ * --modes strict_order,relaxed_order (latent default: relaxed_order)
+ * --ef shipped,40,100,200,400 (repo default: shipped). `shipped` is the
+ * engine's own sizing (hnswEfSearchFor of the attempt's window); a
+ * number pins hnsw.ef_search for every attempt of the search,
+ * set inside the engine's transaction after its own settings.
+ * --max-scan-tuples shipped,20000: the same pin for hnsw.max_scan_tuples (main
+ * grid only; `shipped` keeps the pool's 2,000 × 4^escalation).
+ * --states fresh,analyze (latent default): before the main grid, EXPLAIN
+ * and a shipped-only pass in the stats state right after the
+ * index build (autovacuum off, never ANALYZEd) and after a plain
+ * ANALYZE (`projection` instead runs only the narrow
+ * ANALYZE pages(...) that import and sync end with). The main
+ * grid always runs after VACUUM ANALYZE plus
+ * refreshProjectionStatistics.
+ * --explain EXPLAIN (ANALYZE, BUFFERS, SETTINGS) of the index walk and the
+ * pooled statement per state, filter, k and random_page_cost
+ * (server value and 4), written under --out.
+ * --builds vector:16:128,halfvec:16:64[:mwm=1GB][:par=2] (E5.4.2): after
+ * the main grid, rebuild idx_chunks_embedding with each option
+ * (CREATE INDEX CONCURRENTLY, as the deferred ANN build does; a
+ * halfvec spec converts the column first) and record build
+ * seconds, index bytes and a grid over --build-filters
+ * (none,source10) and --build-ef (shipped,40).
+ * --build-mwm / --build-parallel: maintenance_work_mem and
+ * max_parallel_maintenance_workers for builds (default 1GB, 0).
+ *
+ * Output: a markdown table on stdout (or --json), and --out DIR (default
+ * ~/.capy/work/hnsw-bench/<corpus>-<chunks>) gets results.json (rewritten
+ * after every cell), truth.json and explain/*.txt. `--db NAME` reuses a
+ * database a previous `--keep` latent run loaded (with its --out truth.json);
+ * `--no-grid` skips the main grid, for adding --builds to a kept database.
*/
import { randomBytes, createHash } from 'node:crypto';
-import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
-import { homedir } from 'node:os';
+import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, readSync, statSync, truncateSync, writeFileSync, writeSync } from 'node:fs';
+import { cpus, homedir, totalmem } 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 { VectorPoolAttempt } from '../../src/core/search/vector-pool.ts';
import type { HnswIterativeScanMode } from '../../src/core/search/hnsw-iterative-scan.ts';
-import type { SearchOpts } from '../../src/core/types.ts';
+import type { SearchOpts, VectorPoolMeta } from '../../src/core/types.ts';
+import {
+ buildBasis, buildQueries, Generator, GROUPS, hashPage, Rng, LATENT_DEFAULTS, loadLatentCorpus, pageSlug, planPages, SOURCE_IDS, topicCount, TRUTH_K,
+ type Group, type LatentParams,
+} from './hnsw-latent-corpus.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;
+ return i > 0 && process.argv[i + 1] !== undefined ? process.argv[i + 1]! : fallback;
}
-const EMBED = flag('embed', 'voyage') as 'voyage' | 'openai' | 'synthetic';
+const list = (name: string, fallback: string) => flag(name, fallback).split(',').map(s => s.trim()).filter(Boolean);
+const CORPUS = flag('corpus', 'repo') as 'repo' | 'latent' | 'dir';
+/** latent and dir corpora are bulk-loaded with their truth computed in the same pass. */
+const LATENT = CORPUS === 'latent' || CORPUS === 'dir';
+const CORPUS_DIR = flag('corpus-dir', '');
+const MAX_USD = Number(flag('max-usd', '28'));
+const EMBED = (CORPUS === 'latent' ? 'synthetic' : flag('embed', 'voyage')) as 'voyage' | 'openai' | 'synthetic';
+if (CORPUS === 'dir' && (!CORPUS_DIR || EMBED !== 'voyage')) throw new Error('--corpus dir needs --corpus-dir DIR (voyage-4 embeddings)');
const DIMS = Number(flag('dims', EMBED === 'openai' ? '1536' : '1024'));
const CHUNKS = Number(flag('chunks', '30000'));
const QUERIES = Number(flag('queries', '100'));
+const SEED = Number(flag('seed', '6132'));
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 EXPLAIN = process.argv.includes('--explain');
+const NO_GRID = process.argv.includes('--no-grid');
+const MODES = list('modes', LATENT ? 'relaxed_order' : 'strict_order,relaxed_order') as HnswIterativeScanMode[];
+const MSTS = list('max-scan-tuples', 'shipped').map(v => (v === 'shipped' ? 'shipped' : Number(v))) as Array<'shipped' | number>;
+const EFS = list('ef', LATENT ? 'shipped,40,100,200,400' : 'shipped').map(v => (v === 'shipped' ? 'shipped' : Number(v))) as Array<'shipped' | number>;
+const FILTERS = list('filters', LATENT ? 'none,source10,source50,vis50,vis10' : 'source10,source50') as Group[];
+const KS = list('k', '10,50').map(Number);
+const STATES = list('states', LATENT ? 'fresh,analyze' : '');
+const BUILDS = list('builds', '');
+const BUILD_FILTERS = list('build-filters', 'none,source10') as Group[];
+const BUILD_EFS = list('build-ef', 'shipped,40').map(v => (v === 'shipped' ? 'shipped' : Number(v))) as Array<'shipped' | number>;
+const BUILD_MWM = flag('build-mwm', '1GB');
+const BUILD_PARALLEL = Number(flag('build-parallel', '0'));
+const WORKERS = Number(flag('workers', String(Math.max(1, cpus().length - 2))));
+const VERIFY = Number(flag('verify', LATENT ? '3' : '0'));
+const REUSE_DB = flag('db', '');
+const OUT = flag('out', join(homedir(), `.capy/work/hnsw-bench/${CORPUS}-${CHUNKS}`));
+const LATENT_PARAMS: LatentParams = {
+ ...LATENT_DEFAULTS, chunks: CHUNKS, dims: DIMS, seed: SEED,
+ rank: Number(flag('latent-rank', String(LATENT_DEFAULTS.rank))),
+ noise: Number(flag('latent-noise', String(LATENT_DEFAULTS.noise))),
+ queryNoise: Number(flag('latent-query-noise', String(LATENT_DEFAULTS.queryNoise))),
+};
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}`);
+if (!LATENT && FILTERS.some(f => f.startsWith('vis'))) throw new Error('vis filters need --corpus latent or dir');
+const wallStart = performance.now();
+const log = (m: string) => console.error(`[bench ${new Date().toISOString().slice(11, 19)} +${Math.round((performance.now() - wallStart) / 1000)}s] ${m}`);
+mkdirSync(join(OUT, 'explain'), { recursive: true });
interface Doc { slug: string; source: string; chunks: string[] }
@@ -99,11 +182,11 @@ async function embedBatch(texts: string[], kind: 'document' | 'query'): Promise<
return ((await res.json()) as { data: Array<{ embedding: number[] }> }).data.map(d => d.embedding);
}
-const LATENT = 16;
+const TILED_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);
+ const latent = Array.from({ length: TILED_LATENT }, (_, i) => seed[i]! / 255 - 0.5);
+ return Array.from({ length: DIMS }, (_, d) => latent[d % TILED_LATENT]! + ((seed[(d * 7) % 32]! / 255) - 0.5) * 0.05);
}
async function embedAll(texts: string[], kind: 'document' | 'query'): Promise<number[][]> {
@@ -128,34 +211,118 @@ async function embedAll(texts: string[], kind: 'document' | 'query'): Promise<nu
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}`);
+// ---------------------------------------------------------------------------
+// Engine seam: pin hnsw.ef_search and trace which attempts each search ran
+// ---------------------------------------------------------------------------
+
+type Run = (tx: { unsafe: (sql: string, params?: unknown[]) => Promise<Record<string, unknown>[]> }, sql: string, bound: unknown[]) => Promise<Record<string, unknown>[]>;
+type RunAttempt = (stmt: unknown, attempt: VectorPoolAttempt, iterative: boolean, opts: SearchOpts | undefined, run: Run) => Promise<Record<string, unknown>[]>;
+const seam = PostgresEngine.prototype as unknown as { runVectorAttempt: RunAttempt };
+const runVectorAttempt = seam.runVectorAttempt;
+let efOverride: number | undefined;
+let mstOverride: number | undefined;
+let trace: Array<{ walk: boolean; exact: boolean; innerLimit: number }> = [];
+seam.runVectorAttempt = function (this: PostgresEngine, stmt, attempt, iterative, opts, run) {
+ trace.push({ walk: !!attempt.indexWalk, exact: attempt.exact, innerLimit: attempt.innerLimit });
+ return runVectorAttempt.call(this, stmt, attempt, iterative, opts, async (tx, sql, bound) => {
+ // The same round trip either way, so pinned and shipped cells pay identical overhead.
+ await tx.unsafe(`SELECT set_config('hnsw.ef_search', COALESCE($1, current_setting('hnsw.ef_search')), true), set_config('hnsw.max_scan_tuples', COALESCE($2, current_setting('hnsw.max_scan_tuples')), true)`,
+ [efOverride === undefined ? null : String(efOverride), mstOverride === undefined ? null : String(mstOverride)]);
+ return run(tx, sql, bound);
+ });
+};
+
+// ---------------------------------------------------------------------------
+// Setup
+// ---------------------------------------------------------------------------
+
+const column = { name: 'embedding', type: 'vector' as 'vector' | 'halfvec', dimensions: DIMS, embeddingModel: `bench:${CORPUS === 'latent' ? 'latent' : EMBED}` };
+const dbName = REUSE_DB || `gbrain_bench_hnsw_${LATENT ? `${CORPUS}_${CHUNKS}` : 'iter'}_${randomBytes(6).toString('hex')}`;
+const admin = postgres(adminUrl, { max: 1, prepare: false, onnotice: () => {} });
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`);
+interface Cell {
+ state: string; build: string; filter: Group; k: number; mode: string; ef: string; maxScanTuples: string; queries: number;
+ recall: number; recall10: number; recallP10: number; p50: number; p95: number; p99: number;
+ short: number; incomplete: number; walk: number; pool: number; exactFallback: number; attempts: number;
+}
+interface Explain { state: string; build: string; filter: Group; k: number; attempt: 'walk' | 'pool' | 'pool-x4'; rpc: string; ms: number | null; annIndex: boolean; seqScanChunks: boolean; sort: boolean; jit: boolean; file: string; note?: string }
+interface BuildRow { spec: string; type: string; m: number; efConstruction: number; mwm: string; parallel: number; seconds: number; bytes: number; notices: string[] }
+const results = {
+ corpus: CORPUS, embed: EMBED, dims: DIMS, chunks: CHUNKS, queries: QUERIES, seed: SEED, db: dbName,
+ latent: CORPUS === 'latent' ? LATENT_PARAMS : undefined,
+ env: {} as Record<string, unknown>, corpusStats: {} as Record<string, unknown>, stats: [] as Array<Record<string, unknown>>,
+ verify: [] as Array<Record<string, unknown>>, builds: [] as BuildRow[], explain: [] as Explain[], cells: [] as Cell[], wallSeconds: 0,
+ phases: {} as Record<string, number>,
+};
+const save = () => { results.wallSeconds = Math.round((performance.now() - wallStart) / 1000); writeFileSync(join(OUT, 'results.json'), JSON.stringify(results, (_k, v) => (typeof v === 'bigint' ? Number(v) : v), 2)); };
+const phase = async <T>(name: string, fn: () => Promise<T>): Promise<T> => {
+ const t0 = performance.now();
+ try { return await fn(); } finally { results.phases[name] = Math.round((performance.now() - t0) / 100) / 10; log(`${name}: ${results.phases[name]}s`); save(); }
+};
+
+/** truth[group][q] = exact top TRUTH_K page ids, best first. */
+let truth: Record<string, number[][]> = {};
+let queryVectors: Float32Array[] = [];
+let visState: Group | null = null;
+
+const filterOpts = (g: Group): SearchOpts =>
+ g === 'source10' ? { sourceIds: ['bench-a'] } : g === 'source50' ? { sourceIds: ['bench-a', 'bench-b'] } : g === 'vis50' || g === 'vis10' ? { excludePrivate: true } : {};
+
+async function exactPages(q: Float32Array, g: Group): Promise<number[]> {
+ const exact = buildVectorSearchStatement({ dialect: 'postgres', embedding: q, limit: TRUTH_K, offset: 0, opts: { ...filterOpts(g), embeddingColumn: column } });
+ const rows = await engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL statement_timeout = '600s'`);
+ const bound = [...exact.params];
+ bound[exact.innerLimitIdx] = null;
+ return tx.executeRaw<{ page_id: number | null }>(exact.exactSql, bound);
+ });
+ return rows.filter(r => r.page_id != null).slice(0, TRUTH_K).map(r => Number(r.page_id));
+}
+
+/** Latent only: make (100-N)% of pages private for visN; frontmatter carries each page's draw. Triggers off so no revision moves. */
+async function setVisibility(g: Group, analyze: boolean): Promise<void> {
+ const threshold = g === 'vis10' ? 0.1 : 0.5;
+ if (visState === g) return;
+ await engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL session_replication_role = replica`);
+ await tx.executeRaw(`UPDATE pages SET frontmatter = CASE WHEN (frontmatter->>'bench_vis')::float8 >= $1
+ THEN (frontmatter - 'visibility') || '{"visibility":"private"}'::jsonb ELSE frontmatter - 'visibility' END
+ WHERE slug LIKE 'bench/%'`, [threshold]);
+ });
+ if (analyze) await engine.executeRaw('VACUUM ANALYZE pages');
+ visState = g;
+ log(`visibility: ${g} (${Math.round((1 - threshold) * 100)}% private)`);
+}
+
+async function statsSnapshot(state: string): Promise<void> {
+ const rows = await engine.executeRaw<Record<string, unknown>>(`
+ SELECT c.relname, c.reltuples::bigint AS reltuples, c.relpages, c.relallvisible,
+ pg_size_pretty(pg_relation_size(c.oid)) AS heap, pg_size_pretty(pg_total_relation_size(c.oid)) AS total,
+ (SELECT pg_size_pretty(pg_relation_size(c.reltoastrelid)) WHERE c.reltoastrelid <> 0) AS toast,
+ (SELECT count(*) FROM pg_stats s WHERE s.tablename = c.relname)::int AS stat_columns,
+ s.last_analyze, s.last_vacuum
+ FROM pg_class c LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid
+ WHERE c.relname IN ('content_chunks', 'pages', 'sources')`);
+ results.stats.push({ state, tables: rows });
+ log(`stats ${state}: ${rows.map(r => `${r.relname} reltuples=${r.reltuples} stat_columns=${r.stat_columns}`).join('; ')}`);
+}
+
+async function seedRepo(): Promise<void> {
+ const docs = corpus();
+ const chunkTexts = docs.flatMap(d => d.chunks);
+ log(`corpus: ${docs.length} pages, ${chunkTexts.length} chunks; ${EMBED} @ ${DIMS} dims`);
+ results.corpusStats = { pages: docs.length, chunks: chunkTexts.length };
+ 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);
+ });
+ queryVectors = (await embedAll(queryTexts, 'query')).map(v => Float32Array.from(v));
let v = 0;
for (let i = 0; i < docs.length; i += 200) {
const slice = docs.slice(i, i + 200);
@@ -170,59 +337,493 @@ try {
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))));
+}
+
+async function seedLatent(): Promise<void> {
+ const params = LATENT_PARAMS;
+ const plan = planPages(CHUNKS, SEED);
+ const basis = buildBasis(params);
+ const q = buildQueries(params, plan, basis, QUERIES);
+ queryVectors = q.vectors;
+ results.corpusStats = { pages: plan.count, chunks: CHUNKS, meanChunksPerPage: Number((CHUNKS / plan.count).toFixed(2)), topics: topicCount(CHUNKS) };
+ log(`latent corpus: ${plan.count} pages, ${CHUNKS} chunks, ${topicCount(CHUNKS)} topics, rank ${params.rank} @ ${DIMS} dims`);
+ for (const t of ['content_chunks', 'pages', 'sources']) await engine.executeRaw(`ALTER TABLE ${t} SET (autovacuum_enabled = off, toast.autovacuum_enabled = off)`);
+ const sql = postgres(url.toString(), { max: 1, prepare: false, onnotice: () => {} });
+ try {
+ const copy = await sql.unsafe(`COPY pages (id, slug, source_id, type, title, compiled_truth, frontmatter, knowledge_revision, text_projection_revision, chunker_version) FROM STDIN`).writable();
+ const finished = new Promise<void>((res, rej) => { copy.on('finish', res); copy.on('error', rej); });
+ let buf = '';
+ for (let p = 0; p < plan.count; p++) {
+ const vis = plan.vis[p]!;
+ const fm = JSON.stringify({ bench_vis: Number(vis.toFixed(6)), topic: plan.topic[p], ...(vis >= 0.5 ? { visibility: 'private' } : {}) });
+ buf += `${p + 1}\t${pageSlug(p)}\t${SOURCE_IDS[plan.source[p]!]}\tnote\tLatent page ${p}\tSynthetic page ${p} on topic ${plan.topic[p]}.\t${fm}\t00000000-0000-4000-8000-000000000001\t00000000-0000-4000-8000-000000000001\t4\n`;
+ if (buf.length > 1 << 20) { if (!copy.write(buf)) await new Promise(r => copy.once('drain', r)); buf = ''; }
+ }
+ copy.write(buf);
+ copy.end();
+ await finished;
+ await sql.unsafe(`SELECT setval(pg_get_serial_sequence('pages', 'id'), ${plan.count})`);
+ } finally { await sql.end(); }
+ visState = 'vis50';
+ log(`pages loaded; streaming chunks with ${WORKERS} workers`);
+ const loaded = await loadLatentCorpus({ params, plan, basis, queries: q.vectors, url: url.toString(), model: column.embeddingModel, workers: WORKERS, log });
+ truth = Object.fromEntries(GROUPS.map((g, gi) => [g, loaded.pages.map(per => per[gi]!.map(p => p + 1))]));
+ const sorted = [...loaded.lid].sort((a, b) => a - b);
+ const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / xs.length;
+ results.corpusStats = {
+ ...results.corpusStats,
+ lidMedian: Number(sorted[Math.floor(sorted.length / 2)]!.toFixed(1)), lidP10: Number(sorted[Math.floor(sorted.length * 0.1)]!.toFixed(1)), lidP90: Number(sorted[Math.floor(sorted.length * 0.9)]!.toFixed(1)),
+ queryTop1CosMean: Number(mean(loaded.top1Sim).toFixed(3)),
+ ...geometrySample(params, plan, basis, q),
+ };
+ writeFileSync(join(OUT, 'truth.json'), JSON.stringify({ truth, corpusStats: results.corpusStats }));
+ log(`corpus geometry: ${JSON.stringify(results.corpusStats)}`);
+}
+
+// ---------------------------------------------------------------------------
+// --corpus dir: a prepared real-text corpus (scripts/bench/hnsw-real-corpus-prep.py)
+// ---------------------------------------------------------------------------
+
+interface Ledger { model: string; pricePerMTok: number; documentTokens: number; queryTokens: number; requests: number; usd: number; maxUsd: number; updatedAt: string }
+const VOYAGE_4_PRICE_PER_MTOK = 0.06;
+
+function readLedger(): Ledger {
+ const file = join(CORPUS_DIR, 'ledger.json');
+ return existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) as Ledger
+ : { model: 'voyage:voyage-4', pricePerMTok: VOYAGE_4_PRICE_PER_MTOK, documentTokens: 0, queryTokens: 0, requests: 0, usd: 0, maxUsd: MAX_USD, updatedAt: '' };
+}
+function writeLedger(l: Ledger): void {
+ l.usd = Number((((l.documentTokens + l.queryTokens) / 1e6) * l.pricePerMTok).toFixed(4));
+ l.maxUsd = MAX_USD;
+ l.updatedAt = new Date().toISOString();
+ writeFileSync(join(CORPUS_DIR, 'ledger.json'), JSON.stringify(l, null, 2));
+}
+
+/** One voyage-4 call: unit-normalized vectors and the API-reported token count. Retries 429 and 5xx with backoff. */
+async function voyage(texts: string[], kind: 'document' | 'query'): Promise<{ vectors: Float32Array[]; tokens: number }> {
+ for (let attempt = 0; ; attempt++) {
+ 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 }),
+ }).catch((e: Error) => ({ ok: false, status: 0, text: async () => e.message }) as Response);
+ if (res.ok) {
+ const body = await res.json() as { data: Array<{ embedding: number[] }>; usage: { total_tokens: number } };
+ const vectors = body.data.map(d => {
+ const v = Float32Array.from(d.embedding);
+ let n = 0;
+ for (const x of v) n += x * x;
+ const inv = 1 / Math.sqrt(n);
+ for (let i = 0; i < v.length; i++) v[i]! *= inv;
+ return v;
+ });
+ return { vectors, tokens: body.usage.total_tokens };
+ }
+ const retry = res.status === 0 || res.status === 429 || res.status >= 500;
+ if (!retry || attempt >= 8) throw new Error(`voyage ${res.status}: ${(await res.text()).slice(0, 200)}`);
+ await Bun.sleep(Math.min(60_000, 1000 * 2 ** attempt) * (0.7 + Math.random() * 0.6));
+ }
+}
+
+/** Embeds chunks [have, n) into vectors.f32 in order, CONCURRENCY batches at a time; resumable and capped by --max-usd. */
+async function embedCorpus(texts: Buffer, offsets: Float64Array, n: number): Promise<void> {
+ const file = join(CORPUS_DIR, 'vectors.f32');
+ const width = DIMS * 4;
+ let have = existsSync(file) ? Math.floor(statSync(file).size / width) : 0;
+ if (existsSync(file) && statSync(file).size !== have * width) truncateSync(file, have * width);
+ if (have >= n) return;
+ const ledger = readLedger();
+ const fd = openSync(file, 'a');
+ const text = (i: number) => texts.toString('utf8', offsets[i]!, offsets[i + 1]! - 1);
+ const t0 = performance.now(), start = have;
+ try {
+ while (have < n) {
+ if (ledger.usd >= MAX_USD) throw new Error(`embedding stopped at the $${MAX_USD} cap (${have}/${n} chunks, ledger.json)`);
+ const batches: string[][] = [];
+ let i = have;
+ for (let b = 0; b < 8 && i < n; b++) {
+ const batch: string[] = [];
+ let chars = 0;
+ while (i < n && batch.length < 128 && chars < 90_000) { const t = text(i++); batch.push(t); chars += t.length; }
+ batches.push(batch);
+ }
+ const results = await Promise.all(batches.map(b => voyage(b, 'document')));
+ for (const r of results) {
+ writeSync(fd, Buffer.concat(r.vectors.map(v => Buffer.from(v.buffer, v.byteOffset, v.byteLength))));
+ ledger.documentTokens += r.tokens; ledger.requests++;
+ }
+ have = i;
+ writeLedger(ledger);
+ if ((have - start) % 20_000 < 1024) log(`embedded ${have}/${n} chunks, $${ledger.usd}, ${Math.round((have - start) / ((performance.now() - t0) / 60_000))} chunks/min`);
+ }
+ } finally { closeSync(fd); writeLedger(ledger); }
+}
+
+/** Cached query vectors (queries.f32), or null when there are fewer than n. */
+function readQueryCache(n: number): Float32Array[] | null {
+ const file = join(CORPUS_DIR, 'queries.f32');
+ if (!existsSync(file)) return null;
+ const flat = new Float32Array(readFileSync(file).buffer.slice(0));
+ if (flat.length / DIMS < n) return null;
+ return Array.from({ length: n }, (_, i) => flat.slice(i * DIMS, (i + 1) * DIMS));
+}
+
+/**
+ * Pages, offsets, embeddings, queries and topic-correlated sources: k-means
+ * (40 clusters, cosine) over page mean vectors; whole clusters, in a seeded
+ * order, fill bench-a to 10% of chunks and bench-b to 50%. Visibility stays a
+ * per-page random draw, as in the latent corpus.
+ */
+async function seedDir(): Promise<void> {
+ const lines = readFileSync(join(CORPUS_DIR, 'pages.tsv'), 'utf8').trim().split('\n').map(l => l.split('\t'));
+ const counts: number[] = [], slugs: string[] = [];
+ let total = 0;
+ for (const [, slug, count] of lines) { if (total >= CHUNKS) break; const c = Math.min(Number(count), CHUNKS - total); counts.push(c); slugs.push(slug!); total += c; }
+ const texts = readFileSync(join(CORPUS_DIR, 'chunks.txt'));
+ const offsets = new Float64Array(new SharedArrayBuffer((total + 1) * 8));
+ for (let i = 0, pos = 0; i <= total; i++) { offsets[i] = pos; if (i < total) pos = texts.indexOf(10, pos) + 1; }
+ log(`dir corpus: ${counts.length} pages, ${total} chunks; embedding with voyage-4 @ ${DIMS} (cap $${MAX_USD})`);
+ await embedCorpus(texts, offsets, total);
+ let queries = readQueryCache(QUERIES);
+ if (!queries) {
+ const rng = (() => { let s = SEED; return () => (s = (s * 1103515245 + 12345) % 2 ** 31) / 2 ** 31; })();
+ const qtexts = Array.from({ length: QUERIES }, () => {
+ const i = Math.floor(rng() * total);
+ const t = texts.toString('utf8', offsets[i]!, offsets[i + 1]! - 1);
+ const first = t.split(/(?<=[.!?])\s/)[0] ?? t;
+ return (first.length >= 30 ? first : t).slice(0, 300);
+ });
+ const ledger = readLedger();
+ const out: Float32Array[] = [];
+ for (let i = 0; i < qtexts.length; i += 128) { const r = await voyage(qtexts.slice(i, i + 128), 'query'); out.push(...r.vectors); ledger.queryTokens += r.tokens; ledger.requests++; }
+ writeLedger(ledger);
+ writeFileSync(join(CORPUS_DIR, 'queries.f32'), Buffer.concat(out.map(v => Buffer.from(v.buffer, v.byteOffset, v.byteLength))));
+ queries = out;
+ }
+ queryVectors = queries;
+ const plan = { count: counts.length, chunkStart: new Int32Array(new SharedArrayBuffer(counts.length * 4)), chunkCount: new Int32Array(new SharedArrayBuffer(counts.length * 4)),
+ topic: new Int32Array(new SharedArrayBuffer(counts.length * 4)), source: new Uint8Array(new SharedArrayBuffer(counts.length)), vis: new Float32Array(new SharedArrayBuffer(counts.length * 4)) };
+ // Page mean vectors, read in one sequential pass.
+ const means = new Float32Array(counts.length * DIMS);
+ const fd = openSync(join(CORPUS_DIR, 'vectors.f32'), 'r');
+ for (let p = 0, chunk = 0; p < counts.length; chunk += counts[p]!, p++) {
+ plan.chunkStart[p] = chunk; plan.chunkCount[p] = counts[p]!;
+ const buf = Buffer.allocUnsafe(counts[p]! * DIMS * 4);
+ readSync(fd, buf, 0, buf.length, chunk * DIMS * 4);
+ const v = new Float32Array(buf.buffer, buf.byteOffset, counts[p]! * DIMS);
+ const m = means.subarray(p * DIMS, (p + 1) * DIMS);
+ for (let i = 0; i < v.length; i++) m[i % DIMS]! += v[i]!;
+ let norm = 0;
+ for (let d = 0; d < DIMS; d++) norm += m[d]! * m[d]!;
+ const inv = 1 / Math.sqrt(norm);
+ for (let d = 0; d < DIMS; d++) m[d]! *= inv;
+ plan.vis[p] = new Rng(hashPage(SEED, p)).next();
+ }
+ closeSync(fd);
+ const K = 40;
+ const rng = new Rng(SEED);
+ const sample = Array.from({ length: Math.min(20_000, counts.length) }, () => Math.floor(rng.next() * counts.length));
+ const cent = new Float32Array(K * DIMS);
+ for (let k = 0; k < K; k++) cent.set(means.subarray(sample[k]! * DIMS, (sample[k]! + 1) * DIMS), k * DIMS);
+ const nearest = (p: number) => {
+ let best = -Infinity, arg = 0;
+ for (let k = 0; k < K; k++) { let dot = 0; for (let d = 0; d < DIMS; d++) dot += means[p * DIMS + d]! * cent[k * DIMS + d]!; if (dot > best) { best = dot; arg = k; } }
+ return arg;
+ };
+ for (let iter = 0; iter < 12; iter++) {
+ const sum = new Float64Array(K * DIMS);
+ for (const p of sample) { const k = nearest(p); for (let d = 0; d < DIMS; d++) sum[k * DIMS + d]! += means[p * DIMS + d]!; }
+ for (let k = 0; k < K; k++) {
+ let norm = 0;
+ for (let d = 0; d < DIMS; d++) norm += sum[k * DIMS + d]! ** 2;
+ if (norm === 0) continue;
+ const inv = 1 / Math.sqrt(norm);
+ for (let d = 0; d < DIMS; d++) cent[k * DIMS + d] = sum[k * DIMS + d]! * inv;
+ }
+ }
+ const clusterChunks = new Float64Array(K);
+ for (let p = 0; p < counts.length; p++) { plan.topic[p] = nearest(p); clusterChunks[plan.topic[p]!]! += counts[p]!; }
+ const order = Array.from({ length: K }, (_, k) => k).sort((a, b) => hashPage(SEED, a) - hashPage(SEED, b));
+ const sourceOf = new Uint8Array(K);
+ let filled = 0;
+ for (const k of order) { sourceOf[k] = filled < 0.1 * total ? 0 : filled < 0.5 * total ? 1 : 2; filled += clusterChunks[k]!; }
+ for (let p = 0; p < counts.length; p++) plan.source[p] = sourceOf[plan.topic[p]!]!;
+ const share = (s: number) => Number((Array.from(plan.source).reduce((acc, src, p) => acc + (src <= s ? counts[p]! : 0), 0) / total).toFixed(3));
+ results.corpusStats = { pages: counts.length, chunks: total, meanChunksPerPage: Number((total / counts.length).toFixed(2)), topics: K, source10Share: share(0), source50Share: share(1) };
+ const sql = postgres(url.toString(), { max: 1, prepare: false, onnotice: () => {} });
+ try {
+ const copy = await sql.unsafe(`COPY pages (id, slug, source_id, type, title, compiled_truth, frontmatter, knowledge_revision, text_projection_revision, chunker_version) FROM STDIN`).writable();
+ const finished = new Promise<void>((res, rej) => { copy.on('finish', res); copy.on('error', rej); });
+ let buf = '';
+ for (let p = 0; p < counts.length; p++) {
+ const vis = plan.vis[p]!;
+ const fm = JSON.stringify({ bench_vis: Number(vis.toFixed(6)), topic: plan.topic[p], ...(vis >= 0.5 ? { visibility: 'private' } : {}) });
+ buf += `${p + 1}\tbench/${slugs[p]}\t${SOURCE_IDS[plan.source[p]!]}\tnote\tPage ${p}\tReal-text page ${p}.\t${fm}\t00000000-0000-4000-8000-000000000001\t00000000-0000-4000-8000-000000000001\t4\n`;
+ if (buf.length > 1 << 20) { if (!copy.write(buf)) await new Promise(r => copy.once('drain', r)); buf = ''; }
+ }
+ copy.write(buf);
+ copy.end();
+ await finished;
+ await sql.unsafe(`SELECT setval(pg_get_serial_sequence('pages', 'id'), ${counts.length})`);
+ } finally { await sql.end(); }
+ visState = 'vis50';
+ for (const t of ['content_chunks', 'pages', 'sources']) await engine.executeRaw(`ALTER TABLE ${t} SET (autovacuum_enabled = off, toast.autovacuum_enabled = off)`);
+ const params = { ...LATENT_PARAMS, chunks: total };
+ const loaded = await loadLatentCorpus({ params, plan, basis: null, queries, url: url.toString(), model: column.embeddingModel, workers: WORKERS, log, file: { dir: CORPUS_DIR, offsets: offsets.buffer as SharedArrayBuffer } });
+ truth = Object.fromEntries(GROUPS.map((g, gi) => [g, loaded.pages.map(per => per[gi]!.map(p => p + 1))]));
+ const sorted = [...loaded.lid].sort((a, b) => a - b);
+ results.corpusStats = {
+ ...results.corpusStats,
+ lidMedian: Number(sorted[Math.floor(sorted.length / 2)]!.toFixed(1)), lidP10: Number(sorted[Math.floor(sorted.length * 0.1)]!.toFixed(1)), lidP90: Number(sorted[Math.floor(sorted.length * 0.9)]!.toFixed(1)),
+ queryTop1CosMean: Number((loaded.top1Sim.reduce((a, b) => a + b, 0) / loaded.top1Sim.length).toFixed(3)),
+ ledger: readLedger(),
+ };
+ writeFileSync(join(OUT, 'truth.json'), JSON.stringify({ truth, corpusStats: results.corpusStats }));
+ log(`dir corpus geometry: ${JSON.stringify(results.corpusStats)}`);
+}
+
+/** Cosine statistics of the generated vectors: random pairs, same-topic pairs, same-page pairs, query vs its source chunk. */
+function geometrySample(params: LatentParams, plan: ReturnType<typeof planPages>, basis: SharedArrayBuffer, q: ReturnType<typeof buildQueries>) {
+ const gen = new Generator(params, basis);
+ const dot = (a: Float32Array, b: Float32Array) => { let s = 0; for (let i = 0; i < a.length; i++) s += a[i]! * b[i]!; return s; };
+ const firstTwo = (p: number) => { const out: Float32Array[] = []; gen.page(p, Math.min(2, plan.chunkCount[p]!), (_c, v) => out.push(Float32Array.from(v))); return out; };
+ const sample = Array.from({ length: Math.min(400, plan.count) }, (_, i) => Math.floor((i * 2654435761) % plan.count));
+ const vecs = sample.map(firstTwo);
+ let rand = 0, nRand = 0, same = 0, nSame = 0, topic = 0, nTopic = 0;
+ for (let i = 0; i < vecs.length; i++) {
+ if (vecs[i]!.length === 2) { same += dot(vecs[i]![0]!, vecs[i]![1]!); nSame++; }
+ for (let j = i + 1; j < Math.min(vecs.length, i + 20); j++) {
+ const s = dot(vecs[i]![0]!, vecs[j]![0]!);
+ if (plan.topic[sample[i]!] === plan.topic[sample[j]!]) { topic += s; nTopic++; } else { rand += s; nRand++; }
+ }
+ }
+ const byTopic = new Map<number, number[]>();
+ for (let p = 0; p < plan.count && byTopic.size < 400; p++) { const t = plan.topic[p]!; const arr = byTopic.get(t) ?? []; if (arr.length < 2) arr.push(p); byTopic.set(t, arr); }
+ for (const pages of byTopic.values()) if (pages.length === 2) { topic += dot(firstTwo(pages[0]!)[0]!, firstTwo(pages[1]!)[0]!); nTopic++; }
+ let qs = 0;
+ q.vectors.forEach((qv, i) => { gen.page(q.sourcePage[i]!, q.sourceChunk[i]! + 1, (c, v) => { if (c === q.sourceChunk[i]) qs += dot(qv, v); }); });
+ const f = (x: number) => Number(x.toFixed(3));
+ return { cosRandomPair: f(rand / nRand), cosSameTopic: f(topic / Math.max(1, nTopic)), cosSamePage: f(same / Math.max(1, nSame)), cosQuerySourceChunk: f(qs / q.vectors.length) };
+}
+
+async function buildIndex(spec: string, label = spec): Promise<BuildRow> {
+ const [type, m, efc, ...rest] = spec.split(':');
+ const opt = Object.fromEntries(rest.map(kv => kv.split('=') as [string, string]));
+ const row: BuildRow = { spec: label, type: type!, m: Number(m), efConstruction: Number(efc), mwm: opt.mwm ?? BUILD_MWM, parallel: Number(opt.par ?? BUILD_PARALLEL), seconds: 0, bytes: 0, notices: [] };
+ if (type !== column.type) {
+ if (type !== 'halfvec' || column.type !== 'vector') throw new Error(`cannot convert ${column.type} to ${type}`);
+ await engine.executeRaw('DROP INDEX IF EXISTS idx_chunks_embedding');
+ await phase(`convert to halfvec(${DIMS})`, async () => {
+ await engine.executeRaw(`ALTER TABLE content_chunks ALTER COLUMN embedding TYPE halfvec(${DIMS}) USING embedding::halfvec(${DIMS})`);
+ await engine.executeRaw('VACUUM ANALYZE content_chunks');
+ });
+ column.type = 'halfvec';
+ }
+ const sql = postgres(url.toString(), { max: 1, prepare: false, onnotice: n => row.notices.push(String(n.message)) });
+ try {
+ await sql.unsafe('DROP INDEX IF EXISTS idx_chunks_embedding');
+ await sql.unsafe(`SET maintenance_work_mem = '${row.mwm}'`);
+ await sql.unsafe(`SET max_parallel_maintenance_workers = ${row.parallel}`);
+ await sql.unsafe('SET statement_timeout = 0');
+ const t0 = performance.now();
+ await sql.unsafe(`CREATE INDEX CONCURRENTLY idx_chunks_embedding ON content_chunks USING hnsw (embedding ${type}_cosine_ops) WITH (m = ${row.m}, ef_construction = ${row.efConstruction})`);
+ row.seconds = Math.round((performance.now() - t0) / 100) / 10;
+ row.bytes = Number((await sql.unsafe(`SELECT pg_relation_size('idx_chunks_embedding') AS b`))[0]!.b);
+ } finally { await sql.end(); }
+ results.builds.push(row);
+ log(`build ${label}: ${row.seconds}s, ${(row.bytes / 2 ** 30).toFixed(2)} GiB${row.notices.length ? `; notices: ${row.notices.join(' | ')}` : ''}`);
+ save();
+ return row;
+}
+
+// ---------------------------------------------------------------------------
+// Measurement
+// ---------------------------------------------------------------------------
+
+async function explain(state: string, build: string, filters: Group[]): Promise<void> {
+ const [rpcRow] = await engine.executeRaw<{ v: string }>(`SELECT current_setting('random_page_cost') AS v`);
+ const rpcs = [...new Set([rpcRow!.v, '4'])];
+ const q = queryVectors[0]!;
+ for (const g of filters) {
+ if (g.startsWith('vis')) await setVisibility(g, state === 'vacuum');
+ for (const k of KS) {
+ const opts: SearchOpts = { ...filterOpts(g), limit: k, embeddingColumn: column, hnswIterativeScan: 'relaxed_order' };
+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding: q, limit: k, offset: 0, opts });
+ for (const attempt of [...(stmt.indexWalkSql ? ['walk'] : []), 'pool', 'pool-x4'] as Array<'walk' | 'pool' | 'pool-x4'>) {
+ for (const rpc of rpcs) {
+ const file = `explain/${state}-${build}-${g}-k${k}-${attempt}-rpc${rpc}.txt`;
+ const run = (analyze: boolean): Run => async (tx, sql, bound) => {
+ await tx.unsafe(`SELECT set_config('random_page_cost', $1, true)`, [rpc]);
+ return tx.unsafe(`EXPLAIN (${analyze ? 'ANALYZE, BUFFERS, ' : ''}SETTINGS, FORMAT TEXT) ${sql}`, bound);
+ };
+ const innerLimit = attempt === 'pool-x4' ? stmt.innerLimit * 4 : stmt.innerLimit;
+ const go = (analyze: boolean) => runVectorAttempt.call(engine, stmt, { innerLimit, maxScanTuples: attempt === 'pool-x4' ? 8_000 : 2_000, remainingMs: 8_000, exact: false, indexWalk: attempt === 'walk' }, true, opts, run(analyze));
+ let text: string, note: string | undefined;
+ try { text = (await go(true)).map(r => String(r['QUERY PLAN'])).join('\n'); }
+ catch (e) { note = `EXPLAIN ANALYZE failed (${(e as Error).message}); plain EXPLAIN shown`; text = (await go(false)).map(r => String(r['QUERY PLAN'])).join('\n'); }
+ writeFileSync(join(OUT, file), `${note ? `-- ${note}\n` : ''}${text}\n`);
+ const ms = /Execution Time: ([\d.]+) ms/.exec(text);
+ const row: Explain = {
+ state, build, filter: g, k, attempt, rpc, ms: ms ? Number(ms[1]) : null,
+ annIndex: /Index Scan using idx_chunks_embedding/.test(text), seqScanChunks: /Seq Scan on content_chunks/.test(text),
+ sort: /\n\s*->\s+(Incremental )?Sort\b/.test(text) && /Sort Key: \(?\(?cc\.embedding <=>/.test(text), jit: /JIT:/.test(text), file, ...(note ? { note } : {}),
+ };
+ results.explain.push(row);
+ log(`explain ${state} ${g} k=${k} ${attempt} rpc=${rpc}: ${row.ms ?? '-'} ms ann=${row.annIndex} seq=${row.seqScanChunks} sort=${row.sort} jit=${row.jit}${note ? ' (timeout)' : ''}`);
+ }
}
- 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;
+ }
+ }
+ save();
+}
+
+async function grid(state: string, build: string, filters: Group[], efs: Array<'shipped' | number>, nq: number): Promise<Cell[]> {
+ const cells: Cell[] = [];
+ const variants = MODES.flatMap(mode => efs.flatMap(ef => (efs === EFS ? MSTS : ['shipped' as const]).map(mst => ({ mode, ef, mst }))));
+ for (const g of filters) {
+ if (g.startsWith('vis')) await setVisibility(g, state === 'vacuum');
+ if (!truth[g]) {
+ truth[g] = [];
+ for (const q of queryVectors) truth[g]!.push(await exactPages(q, g));
+ }
+ for (const k of KS) {
+ const search = async (i: number, mode: HnswIterativeScanMode, ef: 'shipped' | number, mst: 'shipped' | number = 'shipped') => {
+ efOverride = ef === 'shipped' ? undefined : ef;
+ mstOverride = mst === 'shipped' ? undefined : mst;
+ trace = [];
+ let meta: VectorPoolMeta | undefined;
+ const start = performance.now();
+ const hits = await engine.searchVector(queryVectors[i]!, { ...filterOpts(g), limit: k, embeddingColumn: column, hnswIterativeScan: mode, onVectorPoolMeta: m => { meta = m; } });
+ const ms = performance.now() - start;
+ efOverride = undefined;
+ mstOverride = undefined;
+ return { hits, ms, meta: meta as VectorPoolMeta | undefined, trace };
+ };
+ for (let i = 0; i < Math.min(5, nq); i++) for (const v of variants) await search(i, v.mode, v.ef, v.mst);
+ const acc = variants.map(() => ({ ms: [] as number[], recall: [] as number[], recall10: [] as number[], short: 0, incomplete: 0, walk: 0, pool: 0, exactFallback: 0, attempts: 0 }));
+ for (let i = 0; i < nq; i++) {
+ const t = new Set(truth[g]![i]!.slice(0, k));
+ const t10 = new Set(truth[g]![i]!.slice(0, 10));
+ const order = variants.map((_, j) => (j + i) % variants.length);
+ for (const j of order) {
+ const r = await search(i, variants[j]!.mode, variants[j]!.ef, variants[j]!.mst);
+ const a = acc[j]!;
+ a.ms.push(r.ms);
+ a.recall.push(t.size === 0 ? 1 : r.hits.slice(0, k).filter(h => t.has(h.page_id)).length / t.size);
+ a.recall10.push(t10.size === 0 ? 1 : r.hits.slice(0, 10).filter(h => t10.has(h.page_id)).length / t10.size);
+ if (r.hits.length < Math.min(k, t.size)) a.short++;
+ if (r.meta?.underfilled) a.incomplete++;
+ const last = r.trace[r.trace.length - 1];
+ if (r.trace.length === 1 && last?.walk) a.walk++; else if (last && !last.exact) a.pool++;
+ if (r.trace.some(x => x.exact)) a.exactFallback++;
+ a.attempts += r.trace.length;
}
}
- for (const mode of MODES) {
- const a = acc.get(mode)!;
+ variants.forEach((v, j) => {
+ const a = acc[j]!;
a.ms.sort((x, y) => x - y);
+ const sortedRecall = [...a.recall].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)));
- }
+ const cell: Cell = {
+ state, build, filter: g, k, mode: v.mode, ef: String(v.ef), maxScanTuples: String(v.mst), queries: nq,
+ recall: Number((a.recall.reduce((x, y) => x + y, 0) / nq).toFixed(4)), recall10: Number((a.recall10.reduce((x, y) => x + y, 0) / nq).toFixed(4)), recallP10: Number(sortedRecall[Math.floor(nq * 0.1)]!.toFixed(3)),
+ p50: pct(0.5), p95: pct(0.95), p99: pct(0.99), short: a.short / nq, incomplete: a.incomplete / nq,
+ walk: a.walk / nq, pool: a.pool / nq, exactFallback: a.exactFallback / nq, attempts: Number((a.attempts / nq).toFixed(2)),
+ };
+ cells.push(cell); results.cells.push(cell);
+ log(`${state} ${build} ${g} k=${k} ${v.mode} ef=${v.ef} mst=${v.mst}: recall ${cell.recall} p50 ${cell.p50} p95 ${cell.p95} short ${cell.short} incomplete ${cell.incomplete} walk ${cell.walk} exact ${cell.exactFallback}`);
+ });
+ save();
+ }
+ }
+ return cells;
+}
+
+async function verifyTruth(filters: Group[]): Promise<void> {
+ for (const g of filters) {
+ if (g.startsWith('vis')) await setVisibility(g, true);
+ for (let i = 0; i < Math.min(VERIFY, queryVectors.length); i++) {
+ const t0 = performance.now();
+ const exact = await exactPages(queryVectors[i]!, g);
+ const mine = truth[g]![i]!;
+ const overlap = (k: number) => exact.slice(0, k).filter(p => mine.slice(0, k).includes(p)).length / Math.min(k, exact.length);
+ const row = { filter: g, query: i, overlap10: overlap(10), overlap50: overlap(50), identicalOrder: exact.join() === mine.join(), exactMs: Math.round(performance.now() - t0) };
+ results.verify.push(row);
+ log(`verify ${g} q${i}: ${JSON.stringify(row)}`);
}
}
+ save();
+}
+
+// ---------------------------------------------------------------------------
+// Run
+// ---------------------------------------------------------------------------
+
+try {
+ if (!REUSE_DB) await admin.unsafe(`CREATE DATABASE ${dbName}`);
+ await engine.connect({ database_url: url.toString(), poolSize: 2 });
+ const env = (await engine.executeRaw<Record<string, unknown>>(`SELECT version() AS pg, (SELECT extversion FROM pg_extension WHERE extname = 'vector') AS pgvector,
+ current_setting('shared_buffers') AS shared_buffers, current_setting('effective_cache_size') AS effective_cache_size, current_setting('work_mem') AS work_mem,
+ current_setting('random_page_cost') AS random_page_cost, current_setting('effective_io_concurrency') AS effective_io_concurrency,
+ current_setting('max_parallel_workers_per_gather') AS max_parallel_workers_per_gather, current_setting('jit') AS jit`))[0]!;
+ results.env = { ...env, cpus: cpus().length, memGiB: Math.round(totalmem() / 2 ** 30), workers: WORKERS };
+ if (REUSE_DB) {
+ const saved = JSON.parse(readFileSync(join(OUT, 'truth.json'), 'utf8')) as { truth: Record<string, number[][]>; corpusStats: Record<string, unknown> };
+ truth = saved.truth; results.corpusStats = saved.corpusStats;
+ queryVectors = CORPUS === 'dir' ? readQueryCache(QUERIES)! : buildQueries(LATENT_PARAMS, planPages(CHUNKS, SEED), buildBasis(LATENT_PARAMS), QUERIES).vectors;
+ const [fm] = await engine.executeRaw<{ n: number }>(`SELECT count(*) FILTER (WHERE frontmatter->>'visibility' = 'private')::int AS n FROM pages`);
+ visState = fm!.n > Number(results.corpusStats.pages) * 0.7 ? 'vis10' : 'vis50';
+ const [t] = await engine.executeRaw<{ t: string }>(`SELECT format_type(atttypid, atttypmod) AS t FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding'`);
+ if (t!.t.startsWith('halfvec')) column.type = 'halfvec';
+ log(`reusing ${dbName} (${visState}, ${t!.t})`);
+ } else {
+ await phase('schema', async () => {
+ 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`);
+ });
+ await phase('seed', () => (CORPUS === 'latent' ? seedLatent() : CORPUS === 'dir' ? seedDir() : seedRepo()));
+ if (LATENT) {
+ await buildIndex(`vector:16:64`, 'vector:16:64 (default)');
+ } else {
+ 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)');
+ });
+ }
+ const preFilters = FILTERS.filter(g => g !== 'vis10');
+ for (const state of STATES) {
+ if (state === 'analyze') await engine.executeRaw('ANALYZE');
+ if (state === 'projection') await refreshProjectionStatistics(engine);
+ await statsSnapshot(state);
+ if (EXPLAIN) await phase(`explain ${state}`, () => explain(state, 'default', preFilters.filter(g => g === 'none' || g === 'source10' || g === 'vis50')));
+ await phase(`grid ${state}`, () => grid(state, 'default', preFilters, ['shipped'], Math.min(50, QUERIES)));
+ }
+ await engine.executeRaw('VACUUM ANALYZE content_chunks');
+ await engine.executeRaw('ANALYZE pages');
+ await engine.executeRaw('ANALYZE sources');
+ await refreshProjectionStatistics(engine);
+ log('seeded and indexed');
+ }
+ await statsSnapshot('vacuum');
+ if (VERIFY > 0 && LATENT) await phase('verify truth', () => verifyTruth(FILTERS));
+ if (EXPLAIN) await phase('explain vacuum', () => explain('vacuum', 'default', FILTERS.filter(g => g === 'none' || g === 'source10' || g.startsWith('vis'))));
+ const ordered = [...FILTERS.filter(g => !g.startsWith('vis')), ...FILTERS.filter(g => g === 'vis50'), ...FILTERS.filter(g => g === 'vis10')];
+ if (!NO_GRID) await phase('grid vacuum', () => grid('vacuum', 'default', ordered, EFS, QUERIES));
+ for (const spec of BUILDS) {
+ const row = await phase(`build ${spec}`, () => buildIndex(spec));
+ if (EXPLAIN) await phase(`explain ${spec}`, () => explain('vacuum', spec.replaceAll(':', '-'), BUILD_FILTERS));
+ await phase(`grid ${spec}`, () => grid('vacuum', row.spec, BUILD_FILTERS, BUILD_EFS, QUERIES));
+ }
} finally {
+ seam.runVectorAttempt = runVectorAttempt;
await engine.disconnect();
- if (!KEEP) await admin.unsafe(`DROP DATABASE IF EXISTS ${dbName} WITH (FORCE)`);
+ if (!KEEP && !REUSE_DB) await admin.unsafe(`DROP DATABASE IF EXISTS ${dbName} WITH (FORCE)`);
await admin.end();
+ save();
}
-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}`);
+const header = `| state | build | filter | k | mode | ef_search | recall@k | recall@10 | p10 recall | p50 ms | p95 ms | short | incomplete | walk | exact fallback |\n|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|`;
+const table = results.cells.map(r => `| ${r.state} | ${r.build} | ${r.filter} | ${r.k} | ${r.mode} | ${r.ef} | ${r.recall} | ${r.recall10} | ${r.recallP10} | ${r.p50} | ${r.p95} | ${r.short} | ${r.incomplete} | ${r.walk} | ${r.exactFallback} |`).join('\n');
+console.log(JSON_OUT ? JSON.stringify(results, (_k, v) => (typeof v === 'bigint' ? Number(v) : v), 2) : `${CORPUS} ${EMBED} @ ${DIMS} dims, ${JSON.stringify(results.corpusStats)}, ${QUERIES} queries, ${results.wallSeconds}s\n${header}\n${table}`);
diff --git a/scripts/bench/hnsw-latent-corpus.ts b/scripts/bench/hnsw-latent-corpus.ts
new file mode 100644
index 0000000000..c79ab80efa
--- /dev/null
+++ b/scripts/bench/hnsw-latent-corpus.ts
@@ -0,0 +1,435 @@
+/**
+ * Synthetic-latent corpus for scripts/bench/hnsw-iterative-scan.ts
+ * (`--corpus latent`): brain-shaped pages and chunks with real-width unit
+ * vectors and no network or model calls. Opt-in bench code, never run in CI.
+ *
+ * Geometry. Every chunk vector is
+ * a0·μ + a1·C[super] + a2·G[topic] + B[topic]·(u_page + u_chunk) + n
+ * normalized to unit length: μ is a shared mean direction (embeddings are
+ * anisotropic), C and G are random unit super-topic and topic directions,
+ * B[topic] is a random rank-`rank` basis in which a topic's pages and chunks
+ * vary (local variation is low-rank, as in text embeddings), and n is
+ * isotropic noise across all dimensions. A query picks a random chunk and
+ * moves it inside its topic subspace and with fresh noise (a query is close
+ * to, not equal to, its source chunk). Topics grow as 4·sqrt(pages), so a
+ * bigger brain is both broader and denser. Pages hold 1 to 60 chunks
+ * (exponential, mean about 7.5) and fall into three sources (10% / 40% /
+ * 50%) and a visibility draw independent of their topic.
+ *
+ * Determinism. Every page draws from its own seeded stream, so any page can
+ * be regenerated alone (the main thread rebuilds query source chunks that
+ * way) and the corpus at a given --chunks and --seed is identical across
+ * runs, machines and worker counts.
+ *
+ * Load + truth. `loadLatentCorpus` splits the pages over Bun workers. Each
+ * worker regenerates its pages, streams its chunks into `content_chunks`
+ * with binary COPY (exact float4 values, no text parse) and, in the same
+ * pass, scores every chunk against every query in float64 to keep the exact
+ * per-page max-pooled top 100 for each filter group, plus each query's 20
+ * nearest chunks for the local intrinsic dimension estimate.
+ */
+import { createHash } from 'node:crypto';
+import { closeSync, openSync, readSync } from 'node:fs';
+import { join } from 'node:path';
+import { isMainThread, parentPort, Worker, workerData } from 'node:worker_threads';
+import postgres from '#postgres';
+
+export interface LatentParams {
+ chunks: number;
+ dims: number;
+ seed: number;
+ rank: number;
+ /** Variance shares before normalization. */
+ mean: number; superTopic: number; topic: number; page: number; chunk: number; noise: number;
+ queryShift: number; queryNoise: number;
+}
+
+export const LATENT_DEFAULTS: Omit<LatentParams, 'chunks' | 'dims' | 'seed'> = {
+ rank: 16, mean: 0.25, superTopic: 0.2, topic: 0.25, page: 0.35, chunk: 0.25, noise: 0.15, queryShift: 0.25, queryNoise: 0.3,
+};
+
+export const SUPER_TOPICS = 64;
+export const MAX_CHUNKS_PER_PAGE = 60;
+export const TRUTH_K = 100;
+export const LID_K = 20;
+/** Filter groups the truth is kept for; each is a page predicate. */
+export const GROUPS = ['none', 'source10', 'source50', 'vis50', 'vis10'] as const;
+export type Group = (typeof GROUPS)[number];
+
+export interface PagePlan { count: number; chunkStart: Int32Array; chunkCount: Int32Array; topic: Int32Array; source: Uint8Array; vis: Float32Array }
+
+export function hash32(...parts: number[]): number {
+ let h = 0x811c9dc5;
+ for (const p of parts) { h = Math.imul(h ^ (p >>> 0), 0x01000193); h ^= h >>> 15; h = Math.imul(h, 0x2c1b3c6d); h ^= h >>> 12; }
+ return h >>> 0;
+}
+
+/** mulberry32 with a cached Box-Muller pair. */
+export class Rng {
+ private s: number;
+ private spare: number | null = null;
+ constructor(seed: number) { this.s = seed >>> 0; }
+ next(): number {
+ let t = (this.s = (this.s + 0x6d2b79f5) >>> 0);
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ }
+ gauss(): number {
+ if (this.spare !== null) { const v = this.spare; this.spare = null; return v; }
+ let u = 0;
+ while (u === 0) u = this.next();
+ const r = Math.sqrt(-2 * Math.log(u)), a = 2 * Math.PI * this.next();
+ this.spare = r * Math.sin(a);
+ return r * Math.cos(a);
+ }
+}
+
+export function topicCount(chunks: number): number {
+ return Math.max(SUPER_TOPICS, Math.round(4 * Math.sqrt(chunks / 7.5)));
+}
+
+/** Per-page attributes, drawn first from the page's own stream (pageStream replays them). */
+function pageHeader(seed: number, p: number, topics: number) {
+ const rng = new Rng(hash32(seed, p, 0x9a6e));
+ const chunkCount = Math.min(MAX_CHUNKS_PER_PAGE, 1 + Math.floor(-Math.log(1 - rng.next()) * 6.5));
+ const topic = Math.floor(rng.next() * topics);
+ const s = rng.next();
+ const source = s < 0.1 ? 0 : s < 0.5 ? 1 : 2;
+ const vis = rng.next();
+ return { rng, chunkCount, topic, source, vis };
+}
+
+export function planPages(chunks: number, seed: number): PagePlan {
+ const topics = topicCount(chunks);
+ const starts: number[] = [], counts: number[] = [], topicOf: number[] = [], sources: number[] = [], vis: number[] = [];
+ let total = 0;
+ for (let p = 0; total < chunks; p++) {
+ const h = pageHeader(seed, p, topics);
+ const n = Math.min(h.chunkCount, chunks - total);
+ starts.push(total); counts.push(n); topicOf.push(h.topic); sources.push(h.source); vis.push(h.vis);
+ total += n;
+ }
+ return { count: starts.length, chunkStart: Int32Array.from(starts), chunkCount: Int32Array.from(counts), topic: Int32Array.from(topicOf), source: Uint8Array.from(sources), vis: Float32Array.from(vis) };
+}
+
+export function inGroup(group: Group, source: number, vis: number): boolean {
+ switch (group) {
+ case 'none': return true;
+ case 'source10': return source === 0;
+ case 'source50': return source <= 1;
+ case 'vis50': return vis < 0.5;
+ case 'vis10': return vis < 0.1;
+ }
+}
+
+/** Shared basis: μ, SUPER_TOPICS super directions, `topics` topic directions, then `topics × rank` subspace vectors. */
+export function buildBasis(params: LatentParams): SharedArrayBuffer {
+ const { dims, rank, seed } = params;
+ const topics = topicCount(params.chunks);
+ const rows = 1 + SUPER_TOPICS + topics + topics * rank;
+ const buf = new SharedArrayBuffer(rows * dims * 4);
+ const out = new Float32Array(buf);
+ for (let r = 0; r < rows; r++) {
+ const rng = new Rng(hash32(seed, r, 0xba515));
+ const row = out.subarray(r * dims, (r + 1) * dims);
+ let norm = 0;
+ for (let d = 0; d < dims; d++) { const g = rng.gauss(); row[d] = g; norm += g * g; }
+ const isSubspace = r >= 1 + SUPER_TOPICS + topics;
+ const scale = isSubspace ? 1 / Math.sqrt(dims) : 1 / Math.sqrt(norm);
+ for (let d = 0; d < dims; d++) row[d]! *= scale;
+ }
+ return buf;
+}
+
+export class Generator {
+ readonly topics: number;
+ private readonly basis: Float32Array;
+ private readonly acc: Float64Array;
+ private readonly coef: Float64Array;
+ constructor(readonly params: LatentParams, basisBuf: SharedArrayBuffer) {
+ this.topics = topicCount(params.chunks);
+ this.basis = new Float32Array(basisBuf);
+ this.acc = new Float64Array(params.dims);
+ this.coef = new Float64Array(params.rank);
+ }
+ private row(r: number): Float32Array { const D = this.params.dims; return this.basis.subarray(r * D, (r + 1) * D); }
+
+ /** Writes one unit vector into `out` from subspace coefficients `coef` and noise variance `noiseVar`. */
+ private compose(topic: number, coef: Float64Array, noiseVar: number, rng: Rng, out: Float32Array): void {
+ const { dims: D, rank, mean, superTopic, topic: topicVar } = this.params;
+ const acc = this.acc;
+ const mu = this.row(0), sup = this.row(1 + (topic % SUPER_TOPICS)), top = this.row(1 + SUPER_TOPICS + topic);
+ const a0 = Math.sqrt(mean), a1 = Math.sqrt(superTopic), a2 = Math.sqrt(topicVar), sn = Math.sqrt(noiseVar / D);
+ for (let d = 0; d < D; d++) acc[d] = a0 * mu[d]! + a1 * sup[d]! + a2 * top[d]! + sn * rng.gauss();
+ const base = 1 + SUPER_TOPICS + this.topics + topic * rank;
+ for (let j = 0; j < rank; j++) {
+ const c = coef[j]!;
+ const b = this.row(base + j);
+ for (let d = 0; d < D; d++) acc[d]! += c * b[d]!;
+ }
+ let norm = 0;
+ for (let d = 0; d < D; d++) norm += acc[d]! * acc[d]!;
+ const inv = 1 / Math.sqrt(norm);
+ for (let d = 0; d < D; d++) out[d] = acc[d]! * inv;
+ }
+
+ /** Replays page `p`, calling `each(chunkIndex, vector, uPage + uChunk)` for its first `count` chunks. */
+ page(p: number, count: number, each: (c: number, vec: Float32Array, coef: Float64Array) => void): void {
+ const { rank, page: pageVar, chunk: chunkVar, noise, seed } = this.params;
+ const h = pageHeader(seed, p, this.topics);
+ const sp = Math.sqrt(pageVar / rank), sc = Math.sqrt(chunkVar / rank);
+ const uPage = new Float64Array(rank);
+ for (let j = 0; j < rank; j++) uPage[j] = sp * h.rng.gauss();
+ const vec = new Float32Array(this.params.dims);
+ for (let c = 0; c < count; c++) {
+ for (let j = 0; j < rank; j++) this.coef[j] = uPage[j]! + sc * h.rng.gauss();
+ this.compose(h.topic, this.coef, noise, h.rng, vec);
+ each(c, vec, this.coef);
+ }
+ }
+
+ query(topic: number, sourceCoef: Float64Array, rng: Rng, out: Float32Array): void {
+ const { rank, queryShift, queryNoise } = this.params;
+ const sq = Math.sqrt(queryShift / rank);
+ const coef = new Float64Array(rank);
+ for (let j = 0; j < rank; j++) coef[j] = sourceCoef[j]! + sq * rng.gauss();
+ this.compose(topic, coef, queryNoise, rng, out);
+ }
+}
+
+export interface LatentQueries { vectors: Float32Array[]; sourcePage: number[]; sourceChunk: number[] }
+
+export function buildQueries(params: LatentParams, plan: PagePlan, basis: SharedArrayBuffer, n: number): LatentQueries {
+ const gen = new Generator(params, basis);
+ const rng = new Rng(hash32(params.seed, 0x51e7));
+ const out: LatentQueries = { vectors: [], sourcePage: [], sourceChunk: [] };
+ for (let i = 0; i < n; i++) {
+ const chunk = Math.floor(rng.next() * params.chunks);
+ let lo = 0, hi = plan.count - 1;
+ while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (plan.chunkStart[mid]! <= chunk) lo = mid; else hi = mid - 1; }
+ const c = chunk - plan.chunkStart[lo]!;
+ let coef: Float64Array | undefined;
+ gen.page(lo, c + 1, (ci, _vec, k) => { if (ci === c) coef = Float64Array.from(k); });
+ const q = new Float32Array(params.dims);
+ gen.query(plan.topic[lo]!, coef!, rng, q);
+ out.vectors.push(q); out.sourcePage.push(lo); out.sourceChunk.push(c);
+ }
+ return out;
+}
+
+const VOCAB = (() => {
+ const syl = ['ka', 'lo', 'mi', 'ten', 'ar', 'vis', 'no', 're', 'shu', 'pa', 'der', 'qui', 'lan', 'mo', 'zet', 'ri', 'bo', 'ex', 'ul', 'fen'];
+ const words: string[] = [];
+ const rng = new Rng(0x70c4b);
+ for (let i = 0; i < 6000; i++) {
+ let w = '';
+ const n = 1 + Math.floor(rng.next() * 3);
+ for (let j = 0; j < n; j++) w += syl[Math.floor(rng.next() * syl.length)];
+ words.push(w);
+ }
+ return words;
+})();
+
+/** About 600 to 2,400 characters (mean about 1,500): roughly a 430-token chunk. Half the words come from the topic's slice of the vocabulary. */
+export function chunkText(seed: number, p: number, c: number, topic: number): string {
+ const rng = new Rng(hash32(seed, p, c, 0x7e47));
+ const target = 600 + Math.floor(rng.next() * 1800);
+ const parts: string[] = [];
+ let len = 0;
+ while (len < target) {
+ const w = rng.next() < 0.5 ? VOCAB[(topic * 37 + Math.floor(rng.next() * 60)) % VOCAB.length]! : VOCAB[Math.floor(rng.next() * VOCAB.length)]!;
+ parts.push(w); len += w.length + 1;
+ if (rng.next() < 0.07) { parts[parts.length - 1] += '.'; }
+ }
+ return parts.join(' ');
+}
+
+export const pageSlug = (p: number) => `bench/latent/p${p}`;
+export const hashPage = (seed: number, p: number) => hash32(seed, p, 0x51b);
+export const SOURCE_IDS = ['bench-a', 'bench-b', 'bench-c'] as const;
+
+// ---------------------------------------------------------------------------
+// Binary COPY of content_chunks
+// ---------------------------------------------------------------------------
+
+const COPY_HEADER = Buffer.concat([Buffer.from('PGCOPY\n\xff\r\n\0', 'latin1'), Buffer.alloc(8)]);
+
+class CopyBuffer {
+ private buf: Buffer;
+ private pos = 0;
+ constructor(size: number) { this.buf = Buffer.allocUnsafe(size); }
+ private ensure(n: number) {
+ if (this.pos + n <= this.buf.length) return;
+ const next = Buffer.allocUnsafe(Math.max(this.buf.length * 2, this.pos + n));
+ this.buf.copy(next, 0, 0, this.pos);
+ this.buf = next;
+ }
+ int16(v: number) { this.ensure(2); this.buf.writeInt16BE(v, this.pos); this.pos += 2; }
+ int32(v: number) { this.ensure(4); this.buf.writeInt32BE(v, this.pos); this.pos += 4; }
+ text(s: string) { const b = Buffer.from(s, 'utf8'); this.int32(b.length); this.ensure(b.length); b.copy(this.buf, this.pos); this.pos += b.length; }
+ vector(v: Float32Array) {
+ this.int32(4 + 4 * v.length); this.int16(v.length); this.int16(0);
+ this.ensure(4 * v.length);
+ for (let d = 0; d < v.length; d++) { this.buf.writeFloatBE(v[d]!, this.pos); this.pos += 4; }
+ }
+ raw(b: Buffer) { this.ensure(b.length); b.copy(this.buf, this.pos); this.pos += b.length; }
+ get size() { return this.pos; }
+ take(): Buffer { const out = Buffer.from(this.buf.subarray(0, this.pos)); this.pos = 0; return out; }
+}
+
+// ---------------------------------------------------------------------------
+// Worker: load a page range and score it against every query
+// ---------------------------------------------------------------------------
+
+/** A prepared real-text corpus (hnsw-real-corpus-prep.py): chunks.txt, its line offsets, and unit vectors.f32 in chunk order. */
+export interface FileCorpus { dir: string; offsets: SharedArrayBuffer }
+
+interface WorkerInput {
+ params: LatentParams; basis: SharedArrayBuffer | null; queries: SharedArrayBuffer; nQueries: number;
+ plan: { chunkStart: Int32Array; chunkCount: Int32Array; topic: Int32Array; source: Uint8Array; vis: Float32Array };
+ pageFrom: number; pageTo: number; url: string; model: string; file?: FileCorpus;
+}
+
+/** Replays page `p` of a file corpus: its chunk texts and vectors, read in one block each. */
+function filePage(file: { offsets: Float64Array; text: number; vectors: number }, dims: number, start: number, count: number, each: (c: number, vec: Float32Array, text: string) => void): void {
+ const from = file.offsets[start]!, to = file.offsets[start + count]!;
+ const bytes = Buffer.allocUnsafe(to - from);
+ readSync(file.text, bytes, 0, bytes.length, from);
+ const texts = bytes.toString('utf8').split('\n');
+ const vbuf = Buffer.allocUnsafe(count * dims * 4);
+ readSync(file.vectors, vbuf, 0, vbuf.length, start * dims * 4);
+ const all = new Float32Array(vbuf.buffer, vbuf.byteOffset, count * dims);
+ for (let c = 0; c < count; c++) each(c, all.subarray(c * dims, (c + 1) * dims), texts[c]!);
+}
+
+/** Per query and group: up to TRUTH_K [pageIndex, similarity] pairs, best first; chunk-level top LID_K distances per query. */
+export interface ShardTruth { pages: Array<Array<Array<[number, number]>>>; chunkSims: number[][] }
+
+class TopK {
+ ids: number[] = []; sims: number[] = [];
+ constructor(private readonly k: number) {}
+ get floor(): number { return this.sims.length < this.k ? -Infinity : this.sims[this.sims.length - 1]!; }
+ push(id: number, sim: number) {
+ if (sim <= this.floor) return;
+ let i = this.sims.length;
+ while (i > 0 && this.sims[i - 1]! < sim) i--;
+ this.ids.splice(i, 0, id); this.sims.splice(i, 0, sim);
+ if (this.sims.length > this.k) { this.ids.pop(); this.sims.pop(); }
+ }
+}
+
+async function runWorker(input: WorkerInput): Promise<ShardTruth> {
+ const { params, nQueries, plan, pageFrom, pageTo } = input;
+ const D = params.dims;
+ const gen = input.basis ? new Generator(params, input.basis) : null;
+ const file = input.file ? { offsets: new Float64Array(input.file.offsets), text: openSync(join(input.file.dir, 'chunks.txt'), 'r'), vectors: openSync(join(input.file.dir, 'vectors.f32'), 'r') } : null;
+ const Q = new Float32Array(input.queries);
+ const groupTops = Array.from({ length: nQueries }, () => GROUPS.map(() => new TopK(TRUTH_K)));
+ const chunkTops = Array.from({ length: nQueries }, () => new TopK(LID_K));
+ const best = new Float64Array(nQueries);
+ const sql = postgres(input.url, { max: 1, prepare: false, onnotice: () => {} });
+ const copy = await sql.unsafe(`COPY content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding) FROM STDIN (FORMAT binary)`).writable();
+ const finished = new Promise<void>((res, rej) => { copy.on('finish', res); copy.on('error', rej); });
+ const out = new CopyBuffer(16 << 20);
+ out.raw(COPY_HEADER);
+ const flush = async () => { if (!copy.write(out.take())) await new Promise(r => copy.once('drain', r)); };
+ for (let p = pageFrom; p < pageTo; p++) {
+ best.fill(-Infinity);
+ const topic = plan.topic[p]!;
+ const each = (c: number, vec: Float32Array, text: string) => {
+ out.int16(7);
+ out.int32(4); out.int32(p + 1);
+ out.int32(4); out.int32(c);
+ out.text(text); out.text('compiled_truth'); out.text(input.model);
+ out.text(createHash('md5').update(text).digest('hex'));
+ out.vector(vec);
+ for (let q = 0; q < nQueries; q++) {
+ let dot = 0;
+ const off = q * D;
+ for (let d = 0; d < D; d++) dot += vec[d]! * Q[off + d]!;
+ if (dot > best[q]!) best[q] = dot;
+ chunkTops[q]!.push(0, dot);
+ }
+ };
+ if (file) filePage(file, D, plan.chunkStart[p]!, plan.chunkCount[p]!, each);
+ else gen!.page(p, plan.chunkCount[p]!, (c, vec) => each(c, vec, chunkText(params.seed, p, c, topic)));
+ for (let q = 0; q < nQueries; q++) {
+ const tops = groupTops[q]!;
+ for (let g = 0; g < GROUPS.length; g++) if (inGroup(GROUPS[g]!, plan.source[p]!, plan.vis[p]!)) tops[g]!.push(p, best[q]!);
+ }
+ if (out.size > 8 << 20) await flush();
+ }
+ out.int16(-1);
+ await flush();
+ copy.end();
+ await finished;
+ await sql.end();
+ if (file) { closeSync(file.text); closeSync(file.vectors); }
+ return {
+ pages: groupTops.map(tops => tops.map(t => t.ids.map((id, i) => [id, t.sims[i]!] as [number, number]))),
+ chunkSims: chunkTops.map(t => t.sims),
+ };
+}
+
+if (!isMainThread && (workerData as { latentCorpus?: boolean } | null)?.latentCorpus) {
+ runWorker(workerData as WorkerInput).then(r => parentPort!.postMessage({ ok: r }), (e: Error) => parentPort!.postMessage({ error: e.stack ?? e.message }));
+}
+
+/**
+ * Streams the corpus into content_chunks (pages must already exist with
+ * id = pageIndex + 1) across `workers` workers and returns the merged truth:
+ * `pages[q][g]` = the exact top TRUTH_K page indexes for query q under
+ * GROUPS[g], best first, and `lid[q]` the MLE local intrinsic dimension at
+ * query q over its LID_K nearest chunks.
+ */
+export async function loadLatentCorpus(input: {
+ params: LatentParams; plan: PagePlan; basis: SharedArrayBuffer | null; queries: Float32Array[]; url: string; model: string; workers: number;
+ log: (m: string) => void; file?: FileCorpus;
+}): Promise<{ pages: number[][][]; lid: number[]; top1Sim: number[] }> {
+ const { params, plan, queries } = input;
+ const qbuf = new SharedArrayBuffer(queries.length * params.dims * 4);
+ const qflat = new Float32Array(qbuf);
+ queries.forEach((q, i) => qflat.set(q, i * params.dims));
+ const shards: Array<[number, number]> = [];
+ const per = params.chunks / input.workers;
+ let from = 0;
+ for (let w = 1; w <= input.workers; w++) {
+ let to = from;
+ while (to < plan.count && (w === input.workers || plan.chunkStart[to]! < per * w)) to++;
+ if (to > from) shards.push([from, to]);
+ from = to;
+ }
+ let done = 0;
+ const results = await Promise.all(shards.map(([pageFrom, pageTo]) => new Promise<ShardTruth>((resolve, reject) => {
+ const worker = new Worker(new URL(import.meta.url), {
+ workerData: {
+ latentCorpus: true, params, basis: input.basis, queries: qbuf, nQueries: queries.length,
+ plan: { chunkStart: plan.chunkStart, chunkCount: plan.chunkCount, topic: plan.topic, source: plan.source, vis: plan.vis }, pageFrom, pageTo, url: input.url, model: input.model,
+ ...(input.file ? { file: input.file } : {}),
+ } satisfies WorkerInput & { latentCorpus: true },
+ });
+ worker.on('message', (m: { ok?: ShardTruth; error?: string }) => {
+ void worker.terminate();
+ if (m.error) return reject(new Error(m.error));
+ input.log(`loaded shard ${++done}/${shards.length} (pages ${pageFrom}..${pageTo - 1})`);
+ resolve(m.ok!);
+ });
+ worker.on('error', reject);
+ })));
+ const pages = queries.map((_, q) => GROUPS.map((_, g) => {
+ const merged = results.flatMap(r => r.pages[q]![g]!);
+ merged.sort((a, b) => b[1] - a[1] || a[0] - b[0]);
+ return merged.slice(0, TRUTH_K).map(([p]) => p);
+ }));
+ const lid: number[] = [], top1Sim: number[] = [];
+ queries.forEach((_, q) => {
+ const sims = results.flatMap(r => r.chunkSims[q]!).sort((a, b) => b - a).slice(0, LID_K);
+ const dist = sims.map(s => Math.sqrt(Math.max(1e-12, 2 - 2 * s)));
+ const dk = dist[dist.length - 1]!;
+ const mean = dist.slice(0, -1).reduce((acc, d) => acc + Math.log(d / dk), 0) / (dist.length - 1);
+ lid.push(-1 / mean);
+ top1Sim.push(sims[0]!);
+ });
+ return { pages, lid, top1Sim };
+}
diff --git a/scripts/bench/hnsw-real-corpus-prep.py b/scripts/bench/hnsw-real-corpus-prep.py
new file mode 100644
index 0000000000..b3b9418c31
--- /dev/null
+++ b/scripts/bench/hnsw-real-corpus-prep.py
@@ -0,0 +1,86 @@
+#!/usr/bin/env python3
+"""Real-text corpus for scripts/bench/hnsw-iterative-scan.ts (`--corpus dir`).
+
+Downloads English Wikipedia shards (wikimedia/wikipedia, 20231101.en, parquet)
+and writes brain-shaped pages and chunks into OUT_DIR. Each article becomes one
+page; its text is cut on paragraph and sentence boundaries into chunks of up to
+CHUNK_CHARS characters, at most 60 per page, until CHUNKS chunks exist.
+
+ pip install pyarrow
+ python3 scripts/bench/hnsw-real-corpus-prep.py OUT_DIR [--chunks 1000000] [--chunk-chars 1200]
+
+Writes:
+ pages.tsv page index, slug, chunk count (title kept out: the bench needs none)
+ chunks.txt one chunk per line, in page order (newlines and tabs replaced by spaces)
+No embeddings are made here: the bench embeds chunks.txt with voyage-4 and caches
+the vectors beside it (vectors.f32), recording tokens and dollars in ledger.json.
+"""
+import argparse
+import os
+import re
+import urllib.request
+
+import pyarrow.parquet as pq
+
+BASE = 'https://huggingface.co/datasets/wikimedia/wikipedia/resolve/main/20231101.en/train-{:05d}-of-00041.parquet'
+SENTENCE = re.compile(r'(?<=[.!?])\s+')
+
+
+def chunks_of(text, limit):
+ out, cur = [], ''
+ for para in (p.strip() for p in text.split('\n')):
+ if not para:
+ continue
+ pieces = [para] if len(para) <= limit else SENTENCE.split(para)
+ for piece in pieces:
+ while len(piece) > limit:
+ if cur:
+ out.append(cur)
+ cur = ''
+ out.append(piece[:limit])
+ piece = piece[limit:]
+ if cur and len(cur) + 1 + len(piece) > limit:
+ out.append(cur)
+ cur = ''
+ cur = f'{cur} {piece}' if cur else piece
+ if cur:
+ out.append(cur)
+ return out
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument('out')
+ ap.add_argument('--chunks', type=int, default=1_000_000)
+ ap.add_argument('--chunk-chars', type=int, default=1200)
+ ap.add_argument('--min-chars', type=int, default=300)
+ args = ap.parse_args()
+ os.makedirs(args.out, exist_ok=True)
+ total = pages = 0
+ with open(os.path.join(args.out, 'pages.tsv'), 'w') as pf, open(os.path.join(args.out, 'chunks.txt'), 'w') as cf:
+ for shard in range(41):
+ path = os.path.join(args.out, f'shard-{shard:05d}.parquet')
+ if not os.path.exists(path):
+ urllib.request.urlretrieve(BASE.format(shard), path + '.part')
+ os.rename(path + '.part', path)
+ table = pq.read_table(path, columns=['id', 'text'])
+ for wid, text in zip(table.column('id').to_pylist(), table.column('text').to_pylist()):
+ if len(text) < args.min_chars:
+ continue
+ parts = [re.sub(r'[\t\r\n]+', ' ', c) for c in chunks_of(text, args.chunk_chars)][:60]
+ parts = parts[: args.chunks - total]
+ if not parts:
+ break
+ pf.write(f'{pages}\twiki/{wid}\t{len(parts)}\n')
+ cf.write('\n'.join(parts) + '\n')
+ pages += 1
+ total += len(parts)
+ if total >= args.chunks:
+ break
+ print(f'shard {shard}: {pages} pages, {total} chunks', flush=True)
+ if total >= args.chunks:
+ break
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/bench/hnsw-scale-vm-setup.sh b/scripts/bench/hnsw-scale-vm-setup.sh
new file mode 100644
index 0000000000..2c26bf283b
--- /dev/null
+++ b/scripts/bench/hnsw-scale-vm-setup.sh
@@ -0,0 +1,72 @@
+#!/usr/bin/env bash
+# scripts/bench/hnsw-scale-vm-setup.sh — bootstrap one Ubicloud VM for the
+# E5.4 HNSW scale bench (scripts/bench/hnsw-iterative-scan.ts --corpus latent).
+# Runs as user `ubi` (passwordless sudo) on a stock Ubuntu 24.04 image, inside
+# the synced checkout (~/work/gbrain). Installs Docker, bun and frozen
+# dependencies, and starts one pgvector/pgvector:pg16 server on
+# 127.0.0.1:5434 sized to the VM: shared_buffers 25% and effective_cache_size
+# 75% of RAM, SSD planner costs (random_page_cost 1.1, effective_io_concurrency
+# 200), a /dev/shm large enough for parallel HNSW builds, and the data
+# directory on the VM disk.
+#
+# scripts/ubicloud/ubi-runner.sh ssh "$name" 'cd work/gbrain && bash scripts/bench/hnsw-scale-vm-setup.sh'
+# DATABASE_URL=postgresql://postgres:[email protected]:5434/postgres bun scripts/bench/hnsw-iterative-scan.ts --corpus latent ...
+set -euo pipefail
+
+BUN_VERSION="${BUN_VERSION:-1.4.2}"
+PG_IMAGE="${PG_IMAGE:-pgvector/pgvector:pg16}"
+t0=$(date +%s)
+step() { echo "[hnsw-scale-setup +$(( $(date +%s) - t0 ))s] $*"; }
+
+echo force-unsafe-io | sudo tee /etc/dpkg/dpkg.cfg.d/99-gbrain-bench >/dev/null
+sudo rm -f /var/lib/man-db/auto-update
+apt_get() { sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_SUSPEND=1 apt-get -qq -o Acquire::Languages=none "$@" >/dev/null; }
+
+step "apt"
+apt_get update
+apt_get install -y --no-install-recommends docker.io git ca-certificates python3 procps postgresql-client jq unzip curl
+sudo systemctl start docker
+
+step "postgres image"
+sudo docker pull -q "$PG_IMAGE" >/dev/null &
+pull=$!
+
+step "bun ${BUN_VERSION}"
+if ! command -v bun >/dev/null || [ "$(bun --version)" != "$BUN_VERSION" ]; then
+ arch=x64
+ [ "$(uname -m)" = aarch64 ] && arch=aarch64
+ tmp=$(mktemp -d)
+ curl -fsSL --retry 5 --retry-all-errors --retry-delay 1 -o "$tmp/bun.zip" "https://github.com/oven-sh/bun/releases/download/bun-v${BUN_VERSION}/bun-linux-${arch}.zip"
+ python3 -m zipfile -e "$tmp/bun.zip" "$tmp"
+ mkdir -p "$HOME/.bun/bin"
+ install -m 755 "$tmp/bun-linux-${arch}/bun" "$HOME/.bun/bin/bun"
+ rm -rf "$tmp"
+fi
+export PATH="$HOME/.bun/bin:$PATH"
+grep -q '.bun/bin' "$HOME/.profile" || echo 'export PATH="$HOME/.bun/bin:$PATH"' >> "$HOME/.profile"
+bun --version
+
+step "dependencies"
+bun install --frozen-lockfile >/dev/null
+wait "$pull"
+
+mem_mb=$(( $(awk '/MemTotal/ {print $2}' /proc/meminfo) / 1024 ))
+shared=$(( mem_mb / 4 ))
+cache=$(( mem_mb * 3 / 4 ))
+shm=$(( mem_mb / 2 ))
+step "postgres: ${mem_mb} MB RAM, shared_buffers ${shared}MB, effective_cache_size ${cache}MB, shm ${shm}MB"
+sudo mkdir -p /var/lib/hnsw-bench-pg
+sudo docker rm -f hnsw-bench-pg >/dev/null 2>&1 || true
+sudo docker run -d --name hnsw-bench-pg --shm-size="${shm}m" -p 127.0.0.1:5434:5432 \
+ -e POSTGRES_PASSWORD=postgres -v /var/lib/hnsw-bench-pg:/var/lib/postgresql/data "$PG_IMAGE" \
+ -c shared_buffers="${shared}MB" -c effective_cache_size="${cache}MB" \
+ -c random_page_cost=1.1 -c effective_io_concurrency=200 \
+ -c max_worker_processes=32 -c max_parallel_workers=16 -c max_parallel_maintenance_workers=8 \
+ -c max_wal_size=32GB -c checkpoint_timeout=30min -c synchronous_commit=off \
+ -c max_connections=200 >/dev/null
+for _ in $(seq 1 60); do
+ PGPASSWORD=postgres psql -h 127.0.0.1 -p 5434 -U postgres -tAc 'select 1' >/dev/null 2>&1 && break
+ sleep 1
+done
+PGPASSWORD=postgres psql -h 127.0.0.1 -p 5434 -U postgres -tAc "select version(), (select default_version from pg_available_extensions where name = 'vector')"
+step "ready (nproc $(nproc), disk $(df -h /var/lib/hnsw-bench-pg | awk 'NR==2 {print $4}') free)"
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index b38dcc7f60..f152c52f50 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -5,6 +5,7 @@ import { embedTakesForStaleDrain, type EmbedTakesResult } from '../core/embed-ta
import { parseFactEmbedArgs } from './embed-facts-delegate.ts';
import { readProjectionSnapshot, installPageProjection, installPageEmbeddings, PageProjectionConflictError, retryProjectionConflict } from '../core/page-state/projections.ts';
import { projectionConflictLine } from '../core/agent-output.ts';
+import { withChunkStatisticsRefresh } from '../core/search/projection-statistics.ts';
import { PageRevisionConflictError } from '../core/page-state/types.ts';
import type { BrainEngine } from '../core/engine.ts';
import { currentEmbeddingSignature } from '../core/embedding.ts';
@@ -715,7 +716,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
let drainError: { err: unknown } | undefined;
const drain = (async () => {
try {
- await embedAll(engine, !!opts.stale, !!opts.dryRun, result, opts.onProgress, opts.sourceId, {
+ await withChunkStatisticsRefresh(engine, () => !opts.dryRun && result.embedded > 0 && !isAborted(drainSignal), () => embedAll(engine, !!opts.stale, !!opts.dryRun, result, opts.onProgress, opts.sourceId, {
batchSize: opts.batchSize,
priority: opts.priority,
catchUp: opts.catchUp,
@@ -724,7 +725,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
quiet: opts.quiet,
includeNullSignature: opts.includeNullSignature,
assertOwned: opts.assertOwned,
- }, drainSignal);
+ }, drainSignal));
if (opts.stale && !isAborted(drainSignal)) await embedTakesForStaleDrain(engine, {
dryRun: !!opts.dryRun, signal: drainSignal, sourceId: opts.sourceId, assertOwned: opts.assertOwned, quiet: opts.quiet,
takes: opts.takes, onProgress: (_done, _total, embedded) => { takesEmbedded = embedded; },
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 12d33f36c2..d1c572aee7 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -350,6 +350,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// Budgeted delivery PR 1. `since` equals the branch's VERSION; the integrator sets it to the merge-slot stamp by hand (release:restamp does not rewrite this table).
{ since: '0.60.124.0', text: 'A token budget passed under `auto` evidence delivery (`token_budget` on query, search and assemble_evidence, `budget_tokens` on recall with `return_unit: "auto"`) is now a hard cap on the delivered titles and evidence: the best hit comes first, and conversations or notes that do not fit are listed in `delivery.dropped_reasons` instead of being appended as extra chunks. A budget below 32 tokens is refused with `invalid_params`. Calls without a budget, and a bare query `token_budget` (legacy chunk budgeting), are unchanged. `gbrain config set search.auto_packing off` restores the uncapped behavior.' },
{ since: '0.60.126.0', text: '`context_pack` cards now list the newest pages that mention each entity and are dated after the entity\'s own page (up to 8 per card, 2,000 characters per card and 6,000 per pack, each with its date, slug, title and preview), so a later mail or note that corrects the page reaches the agent on its first call. A remote caller never sees a private page or another source there, and the section packs last under `budget_tokens`. `gbrain config set mentions.newer_on_cards false` turns it off.' },
+ // E5.4 HNSW scale wave (GBRA-60); `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.130.0', text: 'Vector search under a source or visibility scope now scans up to 20,000 index entries before it settles (it stopped at 2,000), so a scope covering a tenth of a large brain returns its true nearest pages instead of the first few hundred it reached: on 1M chunks with real embeddings and a random 10% scope, recall@50 rose from 0.77 to 0.97, for about 15 to 35 ms more per scoped search on 1M to 2M chunks. Unscoped search returns the same results.' },
+ { since: '0.60.130.0', text: 'On Postgres, import, sync, reindex and every embed drain that embedded something now finish with a bounded ANALYZE (30 s statement, 2 s lock timeout) of `content_chunks(model, modality, page_id)` and the page columns search filters read. Without those statistics, vector search on a freshly loaded brain of 1M chunks or more sorted every candidate, hit its 8 s budget and fell back to keyword-only results (`vector_candidates_incomplete`) until autovacuum ran.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 3287a55d6e..e795a20a93 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -64,7 +64,7 @@ import { sanitizeForJsonb, sanitizeText, buildLinkRows, buildTimelineRows } from
import { SCHEMA_SQL } from './schema-embedded.generated.ts';
import { verifySchema } from './schema-verify.ts';
import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, supportsHnswIterativeScan } from './vector-index.ts';
-import { searchIndexWalk, searchVectorPool, readVectorPool, remainingVectorBudget, type VectorPoolAttempt } from './search/vector-pool.ts';
+import { searchIndexWalk, searchVectorPool, readVectorPool, remainingVectorBudget, type VectorPoolAttempt, POOL_MAX_SCAN_TUPLES } from './search/vector-pool.ts';
import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, SET_STATEMENT_TIMEOUT_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeShareLoader, type PageSourceStats, type VectorSearchStatement } from './search/vector-statement.ts';
import { withVectorSettings } from './search/vector-settings.ts';
import {
@@ -1356,7 +1356,7 @@ export class PostgresEngine implements BrainEngine {
const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());
const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scopeShare: await this.vectorScopeShare(opts) });
const iterative = await this.vectorIterativeScanSupported();
- const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: 2_000, remainingMs: 8_000, exact: false, indexWalk: !!stmt.indexWalkSql };
+ const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: stmt.indexWalkSql ? 2_000 : POOL_MAX_SCAN_TUPLES, remainingMs: 8_000, exact: false, indexWalk: !!stmt.indexWalkSql };
const [row] = await this.runVectorAttempt(stmt, attempt, iterative, opts, (tx, sql, bound) => tx.unsafe(`EXPLAIN (FORMAT JSON) ${sql}`, bound));
const plan = row?.['QUERY PLAN'];
return (Array.isArray(plan) ? plan[0] : plan) as Record<string, unknown>;
diff --git a/src/core/search/projection-statistics.ts b/src/core/search/projection-statistics.ts
index 899761980a..4bcb769067 100644
--- a/src/core/search/projection-statistics.ts
+++ b/src/core/search/projection-statistics.ts
@@ -39,6 +39,74 @@ export async function verifyProjectionStatistics(engine: Pick<BrainEngine, 'exec
}
}
+/**
+ * The content_chunks columns vector search's candidate statement is estimated
+ * from: its generation and modality filters (cc.model, cc.modality) and its
+ * page join (cc.page_id). Without them Postgres prices each equality at 0.5%,
+ * expects a handful of eligible chunks, and sorts every candidate instead of
+ * walking the HNSW index: at 1M to 2M chunks that runs past the 8 s vector
+ * budget (docs/eval/hnsw-scale-bench.md, "Statistics states and EXPLAIN").
+ */
+export const CHUNK_STATISTICS_SQL = 'ANALYZE content_chunks(model, modality, page_id)';
+
+/**
+ * The Postgres page refresh: the projection columns plus the page columns
+ * every search filter reads (`p.deleted_at IS NULL`, source, type and slug
+ * scopes). Without `deleted_at` statistics Postgres prices `IS NULL` at 0.5%
+ * and drives the vector candidate statement from a few pages into their
+ * chunks and a sort, even with content_chunks analyzed. Wide columns
+ * (frontmatter, compiled_truth) stay out, so the sample stays cheap.
+ */
+export const SEARCH_PAGE_STATISTICS_SQL = 'ANALYZE pages(text_projection_revision, knowledge_revision, deleted_at, source_id, type, slug)';
+
+const CHUNK_STATISTICS_WARNING = `[search] Chunk planner statistics could not be refreshed (a lock or the 30 s bound). Vector search may skip its index until autovacuum analyzes content_chunks; run ${CHUNK_STATISTICS_SQL} as the table owner to fix it now.`;
+
+/**
+ * The chunk ANALYZE inside a caller's bounded Postgres transaction, behind a
+ * savepoint: a concurrent index build holding the table's lock (2 s lock
+ * timeout) costs this step alone, never the caller's page statistics. A role
+ * that does not own the table gets Postgres's skip warning, not an error.
+ */
+async function analyzeChunkColumns(tx: BrainEngine): Promise<boolean> {
+ await tx.executeRaw('SAVEPOINT chunk_statistics');
+ try {
+ await tx.executeRaw(CHUNK_STATISTICS_SQL);
+ await tx.executeRaw('RELEASE SAVEPOINT chunk_statistics');
+ return true;
+ } catch {
+ await tx.executeRaw('ROLLBACK TO SAVEPOINT chunk_statistics');
+ console.warn(CHUNK_STATISTICS_WARNING);
+ return false;
+ }
+}
+
+/**
+ * Postgres only (PGLite's planner-stats deltas own its chunk statistics): one
+ * bounded narrow ANALYZE of content_chunks after an embed drain, which moves
+ * content_chunks.model on every row it embeds. Import, sync and reindex get
+ * the same step inside refreshProjectionStatistics.
+ */
+export async function refreshChunkStatistics(engine: BrainEngine): Promise<boolean> {
+ if (engine.kind !== 'postgres') return false;
+ try {
+ return await engine.transaction(async tx => {
+ await tx.executeRaw("SET LOCAL statement_timeout = '30s'");
+ await tx.executeRaw("SET LOCAL lock_timeout = '2s'");
+ return analyzeChunkColumns(tx);
+ });
+ } catch {
+ console.warn(CHUNK_STATISTICS_WARNING);
+ return false;
+ }
+}
+
+/** Runs an embed drain, then refreshes the chunk statistics once when `changed()` says it embedded something (a drain moves content_chunks.model on every row it embeds). */
+export async function withChunkStatisticsRefresh<T>(engine: BrainEngine, changed: () => boolean, drain: () => Promise<T>): Promise<T> {
+ const out = await drain();
+ if (changed()) await refreshChunkStatistics(engine);
+ return out;
+}
+
export async function refreshProjectionStatistics(engine: BrainEngine): Promise<boolean> {
try {
const [role] = await engine.executeRaw<{ can_analyze: boolean }>(
@@ -60,10 +128,11 @@ export async function refreshProjectionStatistics(engine: BrainEngine): Promise<
// PGLite has no autovacuum, so nothing else ever collects planner statistics there. Without them the
// planner sees empty tables and runs search's graph joins as pages-by-pages nested loops (about 50 s
// per search on a freshly imported 4,000-page brain; 6 ms after ANALYZE). Postgres keeps the narrow
- // refresh and leaves the rest to autovacuum.
+ // refresh (the search filter columns of pages, then content_chunks behind a savepoint) and leaves the rest to autovacuum.
// F4b: the full ANALYZE covers every hot table, so it publishes their planner-stats watermarks too.
const publishWatermarks = full ? await beginFullAnalyze(tx) : async () => {};
- await tx.executeRaw(full ? 'ANALYZE' : 'ANALYZE pages(text_projection_revision, knowledge_revision)');
+ await tx.executeRaw(full ? 'ANALYZE' : engine.kind === 'postgres' ? SEARCH_PAGE_STATISTICS_SQL : 'ANALYZE pages(text_projection_revision, knowledge_revision)');
+ if (!full && engine.kind === 'postgres') await analyzeChunkColumns(tx);
await publishWatermarks();
await verifyProjectionStatistics(tx);
});
diff --git a/src/core/search/vector-pool.ts b/src/core/search/vector-pool.ts
index 86a929e7c9..e7f8375f77 100644
--- a/src/core/search/vector-pool.ts
+++ b/src/core/search/vector-pool.ts
@@ -39,6 +39,21 @@ export async function searchIndexWalk(
}
}
+/**
+ * `hnsw.max_scan_tuples` for every pooled attempt: pgvector's own default.
+ * A filtered pooled attempt asks for `innerLimit` eligible chunks and is
+ * accepted once they cover `limit` pages, so its scan budget decides how far
+ * it can reach. At 2,000 tuples a 10% source or visibility filter found about
+ * 200 eligible chunks: enough pages to be accepted, too shallow to hold the
+ * true neighbours. At 20,000 the window fills down to about 1% selectivity
+ * at limit 50: 10%-filter recall@50 rose from 0.52-0.63 to 0.96-0.99 on 1M and
+ * 2M synthetic chunks and from 0.77 to 0.97 on 1M voyage-4 chunks under a
+ * random filter, for 16 to 36 ms more p50 (docs/eval/hnsw-scale-bench.md).
+ * An unfiltered scan stops at its LIMIT long before either budget, so only
+ * filtered searches pay for the deeper visit.
+ */
+export const POOL_MAX_SCAN_TUPLES = 20_000;
+
export function remainingVectorBudget(deadline: number): number {
const remaining = Math.floor(deadline - performance.now());
if (remaining <= 0) throw Object.assign(new Error('Vector candidate deadline exhausted'), { code: '57014' });
@@ -66,7 +81,7 @@ export async function searchVectorPool(
try {
for (;;) {
if (remaining() === 0) { reason = 'deadline'; break; }
- batch = await run({ innerLimit, maxScanTuples: Math.min(2_000 * 4 ** escalations, 20_000), remainingMs: remaining(), exact: false });
+ batch = await run({ innerLimit, maxScanTuples: POOL_MAX_SCAN_TUPLES, remainingMs: remaining(), exact: false });
if (batch.rows.length >= limit) return batch.rows;
if (batch.candidatePool < innerLimit) {
if (!indexed) return batch.rows;
@@ -79,7 +94,7 @@ export async function searchVectorPool(
}
if (engine === 'postgres' && indexed && remaining() > 0) {
exactFallback = true;
- batch = await run({ innerLimit, maxScanTuples: 20_000, remainingMs: remaining(), exact: true });
+ batch = await run({ innerLimit, maxScanTuples: POOL_MAX_SCAN_TUPLES, remainingMs: remaining(), exact: true });
if (batch.rows.length >= limit || batch.exhausted) return batch.rows;
reason = remaining() === 0 ? 'deadline' : 'candidate_budget';
}
diff --git a/test/e2e/vector-chunk-statistics-postgres.test.ts b/test/e2e/vector-chunk-statistics-postgres.test.ts
new file mode 100644
index 0000000000..8466150691
--- /dev/null
+++ b/test/e2e/vector-chunk-statistics-postgres.test.ts
@@ -0,0 +1,115 @@
+/**
+ * E5.4 plan proof: content_chunks planner statistics keep vector search on
+ * its HNSW index. Without statistics on content_chunks, Postgres prices the
+ * candidate statement's `cc.model = $m` and `cc.modality = 'text'` at 0.5%
+ * each, expects a handful of eligible chunks and sorts every candidate by
+ * distance instead of walking idx_chunks_embedding. At 1M to 2M chunks that
+ * sort ran past the 8 s vector budget (docs/eval/hnsw-scale-bench.md).
+ * Import, sync and reindex end with refreshProjectionStatistics, which used
+ * to ANALYZE only pages(text_projection_revision, knowledge_revision). Both
+ * halves of the fix are needed on this fixture: content_chunks(model,
+ * modality, page_id) alone still sorts, because `p.deleted_at IS NULL` is
+ * priced at 0.5% without pages statistics, and pages(deleted_at) alone still
+ * sorts on the chunk filters. This proves the refresh now leaves the pooled
+ * statement on the index.
+ *
+ * 1. precondition: with autovacuum off and nothing analyzed, the pooled
+ * statement does NOT use the index (an undersized fixture fails here);
+ * 2. after refreshProjectionStatistics alone, it does.
+ *
+ * Runs in a dedicated 64-dim database with default planner costs, created on
+ * the E2E server and dropped in afterAll.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import postgres from '#postgres';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import { refreshProjectionStatistics } from '../../src/core/search/projection-statistics.ts';
+import { buildVectorSearchStatement } from '../../src/core/search/vector-statement.ts';
+import { POOL_MAX_SCAN_TUPLES } from '../../src/core/search/vector-pool.ts';
+import { hasDatabase } from './helpers.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+
+const DIM = 64;
+const MODEL = 'openai:text-embedding-3-small';
+// 3,000 pages x 4 chunks, the size the #5824 plan proof measured as clear of
+// the ANALYZEd flip point (about 2,000 chunks) on PostgreSQL 16 + pgvector 0.8.
+const PAGES = 3_000;
+const column = { name: 'embedding', type: 'vector' as const, dimensions: DIM, embeddingModel: MODEL };
+const query = new Float32Array(DIM).map((_, i) => Math.sin(i * 1.7) * 0.5);
+
+const adminUrl = process.env.GBRAIN_PGBOUNCER_DIRECT_URL ?? process.env.DATABASE_URL ?? '';
+const dbName = `gbrain_test_chunk_stats_${randomUUID().replaceAll('-', '')}`;
+let admin: ReturnType<typeof postgres> | undefined;
+let engine: PostgresEngine;
+
+const usesIndex = (plan: unknown) => JSON.stringify(plan).includes('"Index Name":"idx_chunks_embedding"');
+const scans = (plan: unknown) => JSON.stringify(plan).match(/"Node Type":"[^"]+"/g)?.join(' > ') ?? '';
+type Run = (tx: { unsafe: (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]> }, sql: string, bound: unknown[]) => Promise<Record<string, unknown>[]>;
+/** EXPLAIN of the first pooled attempt searchVector runs after a rejected index walk: same statement, transaction and scan settings. */
+async function pooledPlan(): Promise<unknown> {
+ const opts = { limit: 50, embeddingColumn: column };
+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding: query, limit: 50, offset: 0, opts });
+ const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: POOL_MAX_SCAN_TUPLES, remainingMs: 8_000, exact: false };
+ const run = (engine as unknown as { runVectorAttempt: (s: unknown, a: unknown, i: boolean, o: unknown, r: Run) => Promise<Record<string, unknown>[]> }).runVectorAttempt;
+ const [row] = await run.call(engine, stmt, attempt, true, opts, (tx, sql, bound) => tx.unsafe(`EXPLAIN (FORMAT JSON) ${sql}`, bound));
+ return row?.['QUERY PLAN'];
+}
+
+(hasDatabase() ? describe : describe.skip)('content_chunks planner statistics keep the HNSW plan (Postgres)', () => {
+ beforeAll(async () => {
+ assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);
+ admin = postgres(adminUrl, { max: 1, prepare: false });
+ await admin.unsafe(`CREATE DATABASE ${dbName}`);
+ for (const [name, value] of [['random_page_cost', '4'], ['seq_page_cost', '1'], ['cpu_tuple_cost', '0.01'], ['cpu_index_tuple_cost', '0.005'],
+ ['cpu_operator_cost', '0.0025'], ['effective_cache_size', "'4GB'"], ['max_parallel_workers_per_gather', '2'], ['jit', 'off']]) {
+ await admin.unsafe(`ALTER DATABASE ${dbName} SET ${name} = ${value}`);
+ }
+ const url = new URL(adminUrl);
+ url.pathname = `/${dbName}`;
+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIM, env: {} });
+ engine = new PostgresEngine();
+ await engine.connect({ database_url: url.toString(), poolSize: 2 });
+ await engine.initSchema();
+ for (const table of ['content_chunks', 'pages', 'sources']) await engine.executeRaw(`ALTER TABLE ${table} SET (autovacuum_enabled = off, toast.autovacuum_enabled = off)`);
+ await engine.executeRaw('DROP INDEX IF EXISTS idx_chunks_embedding');
+ await engine.executeRaw(`ALTER TABLE content_chunks ALTER COLUMN embedding TYPE vector(${DIM})`);
+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)
+ SELECT 'notes/stats-' || i, 'default', 'note', 'Stats ' || i, 'fixture', '00000000-0000-4000-8000-000000000001'::uuid,
+ '00000000-0000-4000-8000-000000000001'::uuid, 4
+ FROM generate_series(1, ${PAGES}) i`);
+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding)
+ SELECT p.id, c, 'chunk ' || p.id || '/' || c, 'compiled_truth', '${MODEL}', md5('chunk ' || p.id || '/' || c),
+ (SELECT array_agg(sin((p.id * 4 + c) * 0.37 + d * 1.13)::real ORDER BY d)::vector FROM generate_series(1, ${DIM}) d)
+ FROM pages p CROSS JOIN generate_series(0, 3) c`);
+ await engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL max_parallel_maintenance_workers = 0');
+ await tx.executeRaw('CREATE INDEX idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops)');
+ });
+ }, 180_000);
+
+ afterAll(async () => {
+ await engine?.disconnect();
+ resetGateway();
+ if (admin) {
+ await admin.unsafe(`DROP DATABASE IF EXISTS ${dbName} WITH (FORCE)`);
+ await admin.end();
+ }
+ }, 60_000);
+
+ test('stats-less content_chunks sorts every candidate; the import/sync refresh restores the index plan', async () => {
+ const [before] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pg_stats WHERE tablename = 'content_chunks'`);
+ expect(before!.n).toBe(0);
+ const stale = await pooledPlan();
+ expect(usesIndex(stale), `precondition: the stats-less pooled plan already uses the index (${scans(stale)}); grow PAGES`).toBe(false);
+
+ expect(await refreshProjectionStatistics(engine)).toBe(true);
+ const after = await engine.executeRaw<{ column: string }>(
+ `SELECT tablename || '.' || attname AS column FROM pg_stats WHERE (tablename = 'content_chunks' AND attname IN ('model', 'modality', 'page_id'))
+ OR (tablename = 'pages' AND attname = 'deleted_at') ORDER BY 1`);
+ expect(after.map(r => r.column)).toEqual(['content_chunks.modality', 'content_chunks.model', 'content_chunks.page_id', 'pages.deleted_at']);
+ const fresh = await pooledPlan();
+ expect(usesIndex(fresh), scans(fresh)).toBe(true);
+ }, 60_000);
+});
diff --git a/test/e2e/vector-plan-real-column-postgres.test.ts b/test/e2e/vector-plan-real-column-postgres.test.ts
index bf1075d94a..23a1defa5b 100644
--- a/test/e2e/vector-plan-real-column-postgres.test.ts
+++ b/test/e2e/vector-plan-real-column-postgres.test.ts
@@ -347,14 +347,13 @@ function axis(d: number): Float32Array {
}, 60_000);
test('a short raw window holding stale rows escalates on the fresh count instead of stopping short', async () => {
- // 3,000 chunks along the e_3 arc; every 30th is type 'rare' (100 rows),
- // the nearest 90 rare rows stale. hnsw.max_scan_tuples (2,000 on the
- // first attempt) cuts the filtered walk short. How far the walk reaches
- // varies with the randomized HNSW graph (a run reached 20 current rows
- // when only the nearest 60 were stale), so the only current rows are the
- // farthest 10: a short window holds fewer than 10 of them on any graph.
- await seedCluster('short-window', 3_000, [3, 4], 0.0002, i => ({
- type: i % 30 === 0 ? 'rare' : 'note', hash: i % 30 === 0 && i / 30 < 90 ? 'stale' : 'current',
+ // 30,000 chunks along the e_3 arc; every 300th is type 'rare' (100 rows),
+ // the nearest 90 rare rows stale. hnsw.max_scan_tuples (POOL_MAX_SCAN_TUPLES,
+ // 20,000 per pooled attempt) cuts the filtered walk short. How far the walk
+ // reaches varies with the randomized HNSW graph, so the only current rows
+ // are the farthest 10: a short window holds fewer than 10 of them on any graph.
+ await seedCluster('short-window', 30_000, [3, 4], 0.00002, i => ({
+ type: i % 300 === 0 ? 'rare' : 'note', hash: i % 300 === 0 && i / 300 < 90 ? 'stale' : 'current',
}));
await engine.executeRaw('SET enable_seqscan = off');
await engine.executeRaw('SET enable_sort = off');
@@ -368,7 +367,7 @@ function axis(d: number): Float32Array {
expect(first.candidatePool).toBeGreaterThan(first.eligiblePool!);
expect(attempts.length).toBeGreaterThan(1);
expect(hits).toHaveLength(10);
- expect(hits.every(hit => Number(hit.slug.split('-').at(-1)) / 30 >= 90)).toBe(true);
+ expect(hits.every(hit => Number(hit.slug.split('-').at(-1)) / 300 >= 90)).toBe(true);
} finally {
await engine.executeRaw('RESET enable_seqscan');
await engine.executeRaw('RESET enable_sort');
diff --git a/test/embed-chunk-statistics.test.ts b/test/embed-chunk-statistics.test.ts
new file mode 100644
index 0000000000..18f3cdeda2
--- /dev/null
+++ b/test/embed-chunk-statistics.test.ts
@@ -0,0 +1,60 @@
+/**
+ * E5.4: an embed drain that embedded something refreshes the content_chunks
+ * planner statistics once (Postgres), so vector search keeps its HNSW plan
+ * instead of sorting every candidate on a stats-less table. A dry run and a
+ * drain with nothing to embed issue no ANALYZE.
+ */
+import { afterAll, afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { runEmbedCore } from '../src/commands/embed.ts';
+import { CHUNK_STATISTICS_SQL } from '../src/core/search/projection-statistics.ts';
+import { mockEmbedProjectionEngine as mockEngine } from './helpers/embed-projection-mock.ts';
+
+const DIMS = 1536;
+
+beforeEach(() => {
+ resetGateway();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({
+ embeddings: values.map(() => Array.from({ length: DIMS }, (_, j) => (j === 0 ? 1 : 0))),
+ usage: { tokens: values.length },
+ })) as never);
+});
+
+afterEach(() => __setEmbedTransportForTests(null));
+afterAll(() => resetGateway());
+
+function staleEngine(pages: number) {
+ const stale = Array.from({ length: pages }, (_, i) => ({
+ slug: `notes/stats-${i}`, chunk_index: 0, chunk_text: `Synthetic text for notes/stats-${i}.`, chunk_source: 'compiled_truth' as const,
+ model: null, token_count: 4, source_id: 'default', page_id: i + 1,
+ }));
+ let served = false;
+ const engine = mockEngine({
+ kind: 'postgres',
+ countStaleChunks: async () => (served ? 0 : pages),
+ listStaleChunks: async () => { if (served || pages === 0) return []; served = true; return stale; },
+ getChunks: async (slug: string) => [{ chunk_index: 0, chunk_text: `Synthetic text for ${slug}.`, chunk_source: 'compiled_truth', embedded_at: null, token_count: 4 }],
+ upsertChunks: async () => {},
+ });
+ const analyzed = () => ((engine as unknown as { _calls: Array<{ method: string; args: unknown[] }> })._calls)
+ .filter(c => c.method === 'executeRaw' && String(c.args[0]).startsWith('ANALYZE')).map(c => String(c.args[0]));
+ return { engine, analyzed };
+}
+
+describe('embed drain chunk statistics', () => {
+ test('a drain that embedded chunks runs one bounded ANALYZE of content_chunks', async () => {
+ const { engine, analyzed } = staleEngine(5);
+ const result = await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(result.embedded).toBe(5);
+ expect(analyzed()).toEqual([CHUNK_STATISTICS_SQL]);
+ });
+
+ test('a dry run and an empty drain issue no ANALYZE', async () => {
+ for (const [pages, dryRun] of [[5, true], [0, false]] as const) {
+ const { engine, analyzed } = staleEngine(pages);
+ await runEmbedCore(engine, { stale: true, quiet: true, dryRun });
+ expect(analyzed()).toEqual([]);
+ }
+ });
+});
diff --git a/test/search/vector-pool.test.ts b/test/search/vector-pool.test.ts
index 79d418893c..1b47738e4b 100644
--- a/test/search/vector-pool.test.ts
+++ b/test/search/vector-pool.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'bun:test';
-import { readVectorPool, searchVectorPool, type VectorPoolAttempt } from '../../src/core/search/vector-pool.ts';
+import { POOL_MAX_SCAN_TUPLES, readVectorPool, searchVectorPool, type VectorPoolAttempt } from '../../src/core/search/vector-pool.ts';
import { supportsHnswIterativeScan } from '../../src/core/vector-index.ts';
import type { SearchOpts } from '../../src/core/types.ts';
@@ -117,6 +117,23 @@ describe('bounded vector candidate safety', () => {
expect(events).toEqual([]);
});
+ test('a 10% filter fills its first pooled window instead of accepting a short one (E5.4)', async () => {
+ // A fake HNSW scan under a 10% filter: it visits at most maxScanTuples
+ // tuples, so it finds a tenth of that many eligible chunks, and four of
+ // them share a page. At 2,000 tuples the window comes back at 200 of 250
+ // chunks, which already covers 50 pages, so the pool used to accept it.
+ const attempts: VectorPoolAttempt[] = [];
+ const rows = await searchVectorPool(50, 250, true, true, 'postgres', async attempt => {
+ attempts.push(attempt);
+ const eligible = Math.min(attempt.innerLimit, Math.floor(attempt.maxScanTuples * 0.1));
+ return { rows: Array.from({ length: Math.min(50, Math.floor(eligible / 4)) }, (_, page_id) => ({ page_id })), candidatePool: eligible };
+ }, async () => true, () => {});
+ expect(rows).toHaveLength(50);
+ expect(attempts).toHaveLength(1);
+ expect(attempts[0]!.maxScanTuples).toBe(POOL_MAX_SCAN_TUPLES);
+ expect(attempts[0]!.maxScanTuples * 0.1).toBeGreaterThanOrEqual(attempts[0]!.innerLimit);
+ });
+
test('#5824: eligible_pool is read next to the raw candidate_pool', () => {
expect(readVectorPool([{ page_id: 3, candidate_pool: 100, eligible_pool: 12 }])).toEqual({
rows: [{ page_id: 3, candidate_pool: 100, eligible_pool: 12 }], candidatePool: 100, eligiblePool: 12 });