AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(engine,vector): #371 scalar8 kNN scored updated docs from stale codes AND a stale codebook
xerj-org30d0763150e4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 73c40662d..6cfb89a69 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,47 +22,100 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0quiet when the same request already reaches the vector through `semantic`or `knn` (including the ES 8.x top-level `knn` block).- **A `quantization: "scalar8"` (`int8_hnsw`) vector field scored updated- documents from stale quantized codes, silently, forever**+ documents from stale quantized data, silently, forever**([#371](https://github.com/xerj-org/xerj/issues/371)).- The per-field SQ8 code store was populated write-once: the first kNN that- observed a document computed its codes and nothing ever recomputed them — not- an update, not a delete-and-reindex, not a merge. Overwrite a document's- vector and it kept the ranking it had at first sight.-- Reproduced at the HTTP boundary before the fix, on an 8-dimension cosine- field, against a byte-identical full-precision control index: doc `0` starts- as the query vector itself and is rewritten with its exact negation (true- cosine -1). The control drops it as it must. The `scalar8` index returned it- at `_score` **0.99999774** — the same value, to the last bit, as before the- rewrite, with the entire 20-document score list unchanged — while- `GET /{index}/_doc/0` confirmed `_source` had taken the negation. Both- `PUT /{index}/_doc/{id}` and `_bulk` were affected; `_bulk` was untested in- the original report.-- The fix removes the per-document cache rather than adding invalidation to it.- The brute-force scan already holds each candidate's live f32 vector — it just- read it out of `_source` to apply the filter — so it now quantizes and- dequantizes on the spot through a new `Sq8Params::encode_into`, into two- buffers reused across the scan (no per-document allocation). Only the fitted- per-dimension min/scale codebook is kept between queries, behind an `Arc` the- scan clones so it holds no lock while scoring. `scalar8` still scores from- 1-byte-per-dimension codes, so its recall profile is unchanged; what changes- is that the code being scored is always the document's current vector.-- Three defects in the same object went with it: unbounded growth (the map had- no eviction and no upper bound — one entry per document ever queried, for the- life of the process), an exclusive write lock taken on the query path on- *every* kNN over the field, and a codebook that could be fitted from an empty- candidate set — a single query with a wrong-length vector installed an- all-zero-scale codec that every later score on that field collapsed onto.-- Not closed by this change: `scalar8` still reads the full-precision vector- from `_source` on every query, so it does not reduce resident memory today.- Making it do so means the ordinal-addressed, ingest-time code array described- in #371 — codes written next to the data they describe, as Lucene does it —- which is a separate change. The "~4× smaller vector working set" wording in- `ES_COMPATIBILITY.md` described the cache that has been removed and has been- corrected there rather than left standing.+ There were **two** write-once caches on this path, and either one alone+ reproduces the reported symptom.++ 1. The per-field SQ8 **code store** was populated write-once: the first kNN+ that observed a document computed its codes and nothing ever recomputed+ them — not an update, not a delete-and-reindex, not a merge.+ 2. The per-field **codebook** (`Sq8Params`, the per-dimension min/scale pair)+ was fitted from the first <=1000 candidate vectors the field was ever+ scanned with and then kept for the life of the process. A vector written+ afterwards that falls outside that fitted range is *clamped* into it, and+ when the fitted range is narrow the clamped decode is indistinguishable+ from the vector the document used to hold.++ Both were reproduced at the HTTP boundary before the fix, each against a+ byte-identical full-precision control index that performs the identical+ manipulation:++ * **codes** — 8-dimension cosine field, doc `0` starts as the query vector+ and is rewritten with its exact negation. The control drops it as it must;+ the `scalar8` index returned it at `_score` **0.99999774**, the same value+ to the last bit as before the rewrite, with the entire 20-document score+ list unchanged, while `GET /{index}/_doc/0` confirmed `_source` had taken+ the negation. `PUT /{index}/_doc/{id}` and `_bulk` were both affected;+ `_bulk` was untested in the original report.+ * **codebook** — same shape, but over a corpus whose dimension 0 never leaves+ `+1.0`, so it fits the degenerate range `[1,1]`. Doc `0` negated to `-1.0`+ decodes straight back to `+1.0`: still first at `_score` **1.000000**, the+ whole score list frozen. On the workload the issue names as what makes it a+ blocker — re-embedding a corpus after a model change — a codebook fitted to+ the old embedding space clamped 50 re-embedded documents into a 0.002-wide+ score band, destroying ranking outright.++ The fix removes both caches rather than adding invalidation to them. The+ brute-force scan already holds each candidate's live f32 vector — it just+ read it out of `_source` to apply the filter — so it now fits the codebook+ over exactly the candidates it is about to score and quantizes/dequantizes+ each one on the spot, through a new `Sq8Params::encode_into` and+ `Sq8Params::fit_borrowed`, into two buffers reused across the scan (no+ per-document allocation). **No SQ8 state of any kind now outlives a query**,+ so there is nothing left to go stale. Fitting over exactly the set being+ encoded additionally makes clamping impossible on this path rather than+ merely unlikely: every value passed to `encode_into` is inside `[min,max]` by+ construction. `scalar8` still scores from 1-byte-per-dimension codes, so its+ recall profile is unchanged — measured recall@10 **0.998** against the exact+ float32 index on the `vector-quantization` recipe corpus, byte-identical+ scores to before this change on that (unfiltered, <1000-doc, never-updated)+ shape.++ Three defects in the removed objects went with them: unbounded growth (the+ code map had no eviction and no upper bound — one entry per document ever+ queried, for the life of the process), an exclusive write lock taken on the+ query path on *every* kNN over the field, and a codebook that could be fitted+ from an empty candidate set — a single query with a wrong-length vector+ installed an all-zero-scale codec that every later score on that field+ collapsed onto. That last one is now structurally absent rather than guarded:+ a codebook that does not outlive its query cannot be observed by another.++ **Not closed by this change**, tracked in+ [#392](https://github.com/xerj-org/xerj/issues/392):+ * `scalar8` still reads the full-precision vector from `_source` on every+ query, so it **does not reduce resident memory** — it buys the precision+ profile of int8 and nothing else. Making it a memory win means the+ ordinal-addressed, ingest-time code array described in #371, written next+ to the data it describes as Lucene does it. The "~4x smaller vector working+ set" wording has been corrected wherever it appeared rather than left+ standing: `demo/playbooks/ES_COMPATIBILITY.md`,+ `demo/playbooks/STUB_AUDIT.md`, `demo/playbooks/USER_FEEDBACK_SCORECARD_RC4.md`,+ `docs/recipes/vector-quantization.md`, `docs/recipes/README.md`,+ `docs/examples/vector-quantization/quant_demo.py`,+ `recipes/vector_quantization.py`, `xerj-common/src/config.rs` and+ `xerj-vector/src/quantizer.rs`.+ * because the codebook is now fitted per query, a `scalar8` `_score` depends+ on the candidate set: the same document can score marginally differently+ under two different `filter`s. The difference is bounded by SQ8's own+ quantization step (1/255 of the fitted per-dimension range), inside the+ approximation error `scalar8` already carries, but it is a real difference+ from Elasticsearch, which fixes its codebook per segment at index time.+ * `scalar8` continues to disqualify a field from HNSW-served kNN, so opting+ in still costs ANN.++ Cost: measured, but **not resolved**. `ci-test` profile, 4000 docs x 384+ dims, warm, min/p10/p50 of 60 requests, three builds per side. On the+ scan-bound shape (`k=4000`) the two sides overlap and the ordering flips with+ the statistic — best min-of-60 was 22.66 ms on main vs 24.88 ms here, but+ best p10 was 29.26 ms on main vs 25.09 ms here — on a machine that produced+ p50 outliers up to 159 ms from background load. No direction can be claimed+ for that shape from these numbers. The small-`k` shape (`k=10`,+ `num_candidates=100`) was consistently marginally faster here, 0.15-0.16 ms+ against 0.17-0.18 ms on main, which is the per-query `RwLock` read on the+ codec store going away. In principle this change adds one min/max pass over+ the candidate vectors and removes a lock acquisition; both are small against+ the encode/decode/similarity work the scan already does.## [1.0.0-rc.17] - 2026-08-15diff --git a/demo/playbooks/ES_COMPATIBILITY.md b/demo/playbooks/ES_COMPATIBILITY.mdindex 8a4bdcf90..8e28f360e 100644--- a/demo/playbooks/ES_COMPATIBILITY.md+++ b/demo/playbooks/ES_COMPATIBILITY.md@@ -384,6 +384,6 @@ The sections above predate the **rc-3** release and the **RC4** hardening pass.- **`percolate`** — a real reverse-search doc-scan (each indexed doc stores a query; the supplied `document`/`documents` are matched against it), replacing the former hard-coded `MatchNone`.- **`script_fields`** — real per-hit Painless evaluation with `index.max_script_fields` enforcement (was a silent `null`, fixed `65ce844`). Relatedly, **`scripted_metric`** now runs a real single-shard `init`/`map`/`combine`/`reduce` interpreter, and **`significant_terms`** computes real JLH significance scoring — both previously empty/`null`.- **`has_child` / `has_parent`** — now **fail loud (400)** at parse time instead of returning unfiltered flat hits.-- **HNSW-served kNN** — unfiltered, cosine, full-precision kNN on indexes ≥1,024 docs is now served by a persisted HNSW graph with exact rescoring (measured recall@10 1.00 on the bench query; filtered/nested/SQ8/small-index shapes keep the exact brute-force scan). **`scalar8` (`int8_hnsw`)** has a real serving path — scores are computed from 1-byte-per-dimension codes, not from the f32 vector (recall@10 ≈ 0.99) — but it does **not** reduce resident memory today: the scan reads the full-precision vector from `_source` and quantizes it per query. The earlier "~4× smaller vector working set" claim described a per-document code cache that [#371](https://github.com/xerj-org/xerj/issues/371) removed, because it was write-once and kept scoring updated documents from stale codes; the ingest-time, ordinal-addressed code array that would make a memory claim true is still open. `binary` (1-bit) is still rejected at startup.+- **HNSW-served kNN** — unfiltered, cosine, full-precision kNN on indexes ≥1,024 docs is now served by a persisted HNSW graph with exact rescoring (measured recall@10 1.00 on the bench query; filtered/nested/SQ8/small-index shapes keep the exact brute-force scan). **`scalar8` (`int8_hnsw`)** has a real serving path — scores are computed from 1-byte-per-dimension codes, not from the f32 vector (recall@10 ≈ 0.998, measured) — but it buys **precision, not memory**: the scan reads the full-precision vector from `_source` and quantizes it per query, so nothing gets smaller in RAM. The earlier "~4× smaller vector working set" claim described caches that [#371](https://github.com/xerj-org/xerj/issues/371) removed — both the per-document code map and the per-field codebook were write-once, and between them kept scoring updated documents from stale data. The ingest-time, ordinal-addressed code array that would make a memory claim true is tracked in [#392](https://github.com/xerj-org/xerj/issues/392), which also covers the two consequences of fitting the codebook per query: `scalar8` still disqualifies a field from HNSW-served kNN, and a `scalar8` `_score` varies with the candidate set (bounded by SQ8's own 1/255 quantization step) where Elasticsearch's, fixed per segment at index time, does not. `binary` (1-bit) is still rejected at startup.Still **not** compatible (unchanged, single-node by design): true multi-node sharding/replication, CCR, and full ML. The float-to-integer truncation and scored-`hits.total` defects flagged in §1/§8 are tracked separately — this addendum does not claim them closed. See ROADMAP.md and STUB_AUDIT.md for the full tracked list.diff --git a/demo/playbooks/STUB_AUDIT.md b/demo/playbooks/STUB_AUDIT.mdindex 2add870f5..33df5eaf5 100644--- a/demo/playbooks/STUB_AUDIT.md+++ b/demo/playbooks/STUB_AUDIT.md@@ -110,7 +110,7 @@ These intersect a claim on the site/README/docs. Fixed rows first.| Intelligent automatic field encoding engine (FieldAnalyzer/FieldEncoding) — per-field smart compression + the user-facing /v1/indices/:name/encodings endpoint and dashboard top_encodings stats | missing | `crates/xerj-compress/src/field_codec.rs (analyzer, fully implemented but orphaned); dead driver at /home/claude/ai/xerj/engine/crates/xerj-engine/src/memtable.rs:352 (collect_sample); empty-forever aggregator at memtable.rs:1288; consumer at /home/claude/ai/xerj/engine/crates/xerj-api/src/native.rs:1796` | REAL gap (dead scaffold), not a false positive — but with an important nuance. The FieldAnalyzer/FieldEncoding code in field_codec.rs is genuinely implemented a… || SSO / IdP configuration (OIDC / SAML federated identity) | missing | `crates/xerj-console-api/src/indices.rs:26` | Real gap, correctly identified as dead scaffold. The `.xerj_idp_config` index (IDP_CONFIG) is declared at indices.rs:26, added to the ALL set (line 43), given a… || Xerj Console cluster RAFT-state / topology endpoints (and the `.xerj_cluster_state` system index that backs them) | missing | `crates/xerj-console-api/src/indices.rs:27` | REAL gap, verified in both directions. (1) Dead scaffold confirmed: `CLUSTER_STATE = ".xerj_cluster_state"` (indices.rs:27) has a full per-node Raft schema (rol… |-| dense_vector quantization / memory-efficient vector storage (config default_quantization: none/scalar8/binary, advertised 4-32x memory reduction) | missing | `crates/xerj-vector/src/quantizer.rs` | ✅ scalar8 FIXED (`int8_hnsw` serving path shipped — kNN scores against 1-byte-per-dim codes, ~4× smaller working set, measured recall@10 ≈ 0.99; see ROADMAP "Real scalar8 vector quantization"). `binary` (1-bit) is still rejected at startup and `scalar4`/offload remain future work, so this row is only partially closed. Original finding: REAL gap (dead scaffold with a silently-inert config knob). The quantizer.rs module itself is fully implemented and unit-tested in isolation (NoneQuantizer, Sca… |+| dense_vector quantization / memory-efficient vector storage (config default_quantization: none/scalar8/binary, advertised 4-32x memory reduction) | missing | `crates/xerj-vector/src/quantizer.rs` | ⚠️ scalar8 PARTIAL (`int8_hnsw` serving path shipped — kNN scores against 1-byte-per-dim codes, measured recall@10 ≈ 0.998; see ROADMAP "Real scalar8 vector quantization"). It buys PRECISION, not memory: the scan reads the f32 vector from `_source` and quantizes per query, so there is no smaller working set and the earlier "~4× smaller working set" claim here was wrong — [#392](https://github.com/xerj-org/xerj/issues/392) tracks making it true. `binary` (1-bit) is still rejected at startup and `scalar4`/offload remain future work, so this row is only partially closed. Original finding: REAL gap (dead scaffold with a silently-inert config knob). The quantizer.rs module itself is fully implemented and unit-tested in isolation (NoneQuantizer, Sca… |---## Internal gaps (34) — not on the public landing pagesdiff --git a/demo/playbooks/USER_FEEDBACK_SCORECARD_RC4.md b/demo/playbooks/USER_FEEDBACK_SCORECARD_RC4.mdindex 403ef44d1..7c7968eeb 100644--- a/demo/playbooks/USER_FEEDBACK_SCORECARD_RC4.md+++ b/demo/playbooks/USER_FEEDBACK_SCORECARD_RC4.md@@ -92,7 +92,7 @@ These are the strategic decisions for rc5, stated without spin.- `role_descriptors` accepted then ignored — every API key is effectively superuser.- ~~No `cargo-audit`/`cargo-deny` gate (528 unscanned dep crates) and no `cargo-fuzz` harnesses.~~**CLOSED 2026-08-09 (#207):** CI job `security-audit` runs `cargo audit` on every push and PR, and job `fuzz` builds and runs the libFuzzer harnesses in `engine/fuzz/` (ES DSL, `query_string`, date math, index-name date math, SQL, Painless, and the aggregation script tokenisers). `cargo-deny` is still absent.-- Binary/RaBitQ (BBQ) quantization unimplemented; `bbq_*`/`int4_*` mappings silently keep full f32 (no memory saving) — HNSW RAM wall only 4× mitigated by SQ8, no DiskANN.+- Binary/RaBitQ (BBQ) quantization unimplemented; `bbq_*`/`int4_*` mappings silently keep full f32 (no memory saving) — HNSW RAM wall NOT mitigated by SQ8 either — `scalar8` changes scoring precision, not resident memory (the scan quantizes from `_source` per query); see [#392](https://github.com/xerj-org/xerj/issues/392). No DiskANN.**Marketing numbers to reconcile with measured reality (honesty-posture debt):**`<500MB RSS / 1M docs` (measured 596MB / 200k) · `~30MB Docker image` (~75–100MB) · `2–5× compression` (~1.6×) · `2 files/segment` (~4) · `TLS enabled out of the box` (off by default) · `OpenAPI generated from code` (static hand-maintained, 404 live) · `no deep-pagination cliff` (identical 10k cap) · `cost-based planner` (rule/structure-based) · error links use `xerj.io` vs canonical `xerj.org`.@@ -151,7 +151,7 @@ Ranking = severity × reach (how many pain points / clusters it closes) × inver| Candidate | Sev | Effort | Closes ||---|---|---|---|| **Default (or auto-detect) the neural embedder** instead of lexical feature-hash | MED | M | resource-cost + ai-logs — semantic/RAG/memory quality poor out-of-box |-| **Binary/RaBitQ (BBQ 1-bit) quantization + make `bbq_*` mappings honest** | MED | L | ai-logs quantization PARTIAL (only 4× SQ8 today vs promised 32×) |+| **Binary/RaBitQ (BBQ 1-bit) quantization + make `bbq_*` mappings honest** | MED | L | ai-logs quantization PARTIAL (SQ8 today buys precision, not the promised 32× — or any — memory reduction; [#392](https://github.com/xerj-org/xerj/issues/392)) || **DiskANN / disk-backed vector index** | MED | L | ai-logs HNSW memory-wall GAP (graph is entirely in-RAM) || **Contextual retrieval: surface prev/next sibling chunks + parent metadata on recall** | MED | M | upgrades-datamodel + ai-logs chunking PARTIAL — RAG context quality |diff --git a/docs/examples/vector-quantization/quant_demo.py b/docs/examples/vector-quantization/quant_demo.pyindex 1bdd79d0b..b2dd31e3d 100644--- a/docs/examples/vector-quantization/quant_demo.py+++ b/docs/examples/vector-quantization/quant_demo.py@@ -4,8 +4,14 @@XERJ stores dense vectors at full float32 precision by default. Opting a`dense_vector` field into scalar8 quantization (`index_options.type:int8_hnsw`) makes the kNN *serving* path score against 1-byte-per-dimension-codes instead of 4-byte floats — a ~4x smaller vector working set with-almost no recall loss. `_source` still returns the original vectors.+codes instead of 4-byte floats, with almost no recall loss. `_source` still+returns the original vectors.++NOTE: this changes PRECISION, not memory. XERJ reads the full-precision+vector from `_source` and quantizes it per query, so `scalar8` does not+shrink the resident vector working set today — see issue #392. The footprint+number printed below is the size of the int8 ENCODING, not a saving XERJ+currently realises.This recipe embeds the 40 real KB articles (demo/data/ai_kb.ndjson) into128-dim vectors with a small deterministic feature-hasher (same idea as@@ -15,9 +21,9 @@ shows that:1. kNN returns the same top results from both,2. recall@10 of the quantized index vs the exact index stays >= 0.90,- 3. the quantized field's vector footprint is 4x smaller — MEASURED by- actually encoding every vector as float32 bytes vs int8 bytes and- comparing the real byte totals (not a hardcoded ratio).+ 3. what the int8 encoding costs vs float32 — MEASURED by actually+ encoding every vector both ways and comparing the real byte totals+ (not a hardcoded ratio). See the NOTE above on what this is not.Usage:xerj --insecure --data-dir ./data & # start XERJ@@ -172,9 +178,11 @@ def main():total += len(exact)recall = hits / total if total else 0.0- # ── 5. Measure the real byte footprint of each encoding. ─────────────+ # ── 5. Measure the real byte size of each ENCODING. ──────────────────# Encode every corpus vector both ways and compare the actual byte totals- # — this is a genuine measurement, not a stipulated 4x.+ # — a genuine measurement, not a stipulated 4x. It is a measurement of the+ # encodings, though, NOT of XERJ's resident footprint: the serving path+ # reads the f32 vector from `_source` and quantizes per query (issue #392).f32_total = sum(len(encode_f32(d["v"])) for d in docs)i8_total = sum(len(encode_i8(d["v"])) for d in docs)ratio = f32_total / i8_total if i8_total else 0.0@@ -183,13 +191,14 @@ def main():print(f"recall@10 (scalar8 vs float32 ground truth): {recall:.3f}")print(- f"vector footprint over {len(docs)} vecs: "+ f"encoding size over {len(docs)} vecs: "f"float32 = {f32_total} B ({f32_per} B/vec) → "f"scalar8 = {i8_total} B ({i8_per} B/vec) ({ratio:.2f}x smaller)")if recall < 0.90:raise SystemExit(f"FAIL: recall {recall:.3f} < 0.90")- print("\nOK — 4x smaller vectors, recall preserved. `_source` still holds the originals.")+ print("\nOK — recall preserved through 1-byte-per-dim codes. `_source` still holds")+ print("the originals. scalar8 changes precision, not resident memory (issue #392).")if __name__ == "__main__":diff --git a/docs/recipes/README.md b/docs/recipes/README.mdindex 0f8b9d30e..2784e7de8 100644--- a/docs/recipes/README.md+++ b/docs/recipes/README.md@@ -15,7 +15,7 @@ These are practical "how do I actually do X" recipes, not an API reference (that| [Passage retrieval on long docs](./passage-retrieval.md) | `semantic_text` auto-embeds every overlapping passage; a long doc competes on any one of its sections via best-passage (max-sim) scoring — 98% top-3 vs 32% pooled | [`passage_demo.py`](../examples/passage-retrieval/passage_demo.py) || [Log analytics](./log-analytics.md) | From raw logs to dashboards — error rates, p95 latency, top services via aggregations | [`log_analytics.py`](../examples/log-analytics/log_analytics.py) || [Vector search (kNN)](./vector-search-knn.md) | Nearest-neighbor similarity search over `dense_vector` (HNSW), with filters | [`knn_demo.py`](../examples/vector-search-knn/knn_demo.py) |-| [Vector quantization](./vector-quantization.md) | Opt a `dense_vector` field into scalar8 (`int8_hnsw`) — 4× smaller vectors, recall@10 ≈ 0.99 | [`quant_demo.py`](../examples/vector-quantization/quant_demo.py) |+| [Vector quantization](./vector-quantization.md) | Opt a `dense_vector` field into scalar8 (`int8_hnsw`) — kNN scored from 1-byte-per-dim codes at recall@10 ≈ 0.998 (precision, **not** memory: see [#392](https://github.com/xerj-org/xerj/issues/392)) | [`quant_demo.py`](../examples/vector-quantization/quant_demo.py) || [Hybrid search](./hybrid-search.md) | Keyword + vector in one query — results neither BM25 nor kNN finds alone | [`hybrid_search.py`](../examples/hybrid-search/hybrid_search.py) || [Anomaly detection](./anomaly-detection.md) | Statistical `_ml` detectors that flag spikes in metrics/logs | [`anomaly_detection.py`](../examples/anomaly-detection/anomaly_detection.py) || [Continuous anomaly datafeeds](./continuous-anomaly-datafeeds.md) | A live `_ml` datafeed that re-scores an index on a timer and stores new anomaly records you poll | [`datafeed_demo.py`](../examples/continuous-anomaly-datafeeds/datafeed_demo.py) |diff --git a/docs/recipes/vector-quantization.md b/docs/recipes/vector-quantization.mdindex 02a8a61a9..dfaa5a0f8 100644--- a/docs/recipes/vector-quantization.md+++ b/docs/recipes/vector-quantization.md@@ -1,4 +1,13 @@-# Vector quantization: 4× smaller vectors, same results+# Vector quantization: int8 scoring at recall@10 ≈ 0.998++> **Read this first.** `scalar8` on XERJ today changes **precision, not+> memory**. Scores are computed from 1-byte-per-dimension codes, so the field+> has the recall profile of int8 — but the serving path still reads the+> full-precision vector out of `_source` and quantizes it per query, so+> nothing gets smaller in RAM. The ingest-time code array that would make it+> a memory win is tracked in+> [#392](https://github.com/xerj-org/xerj/issues/392). If you came here for a+> smaller working set, that issue is the one to watch, not this recipe.## The problem@@ -8,23 +17,27 @@ kNN. Scale to tens of millions and the vector working set — not the text,not the postings — becomes the thing that decides how much RAM you rent.The standard fix is **scalar quantization**: store each dimension in one-byte instead of four. That's a 4× reduction. The catch everyone worries-about is recall — does compressing the vectors quietly wreck ranking-quality?+byte instead of four. The catch everyone worries about is recall — does+compressing the vectors quietly wreck ranking quality? That is the question+this recipe answers, and the answer is no.## Why XERJXERJ lets you opt a `dense_vector` field into **scalar8** (int8)quantization per field. When you do, the kNN *serving* path scores against-1-byte-per-dimension codes instead of 4-byte floats — a ~4× smaller vector-working set — while `_source` still returns the **original** vectors for-retrieval. It's off by default (full float32), so you choose precision vs.-memory per field, exactly like Elasticsearch's `int8_hnsw`.+1-byte-per-dimension codes instead of 4-byte floats, while `_source` still+returns the **original** vectors for retrieval. It's off by default (full+float32), so you choose the precision model per field, spelled exactly like+Elasticsearch's `int8_hnsw`.On a real 128-dim corpus the recall cost is negligible: **recall@10 = 0.998**-against the exact float32 index, with the vector footprint cut from 512 to-128 bytes per vector — a **measured 4.00× reduction**. (Both numbers are-computed by the run below, not stipulated.)+against the exact float32 index. That number is computed by the run below,+not stipulated.++What that costs in bytes *as an encoding* is 128 rather than 512 per vector,+and the run measures that too — but see the note at the top: XERJ does not+hold those codes resident today, so treat it as the size of the encoding, not+as a saving you get.## The solution@@ -86,14 +99,18 @@ query: 'how do I stop an agent's context window from overflowing?'0.59731 SOC 2 controls that apply to vector workloadsrecall@10 (scalar8 vs float32 ground truth): 0.998-vector footprint over 40 vecs: float32 = 20480 B (512 B/vec) → scalar8 = 5120 B (128 B/vec) (4.00x smaller)+encoding size over 40 vecs: float32 = 20480 B (512 B/vec) → scalar8 = 5120 B (128 B/vec) (4.00x smaller)-OK — 4x smaller vectors, recall preserved. `_source` still holds the originals.+OK — recall preserved through 1-byte-per-dim codes. `_source` still holds+the originals. scalar8 changes precision, not resident memory (issue #392).```-The footprint line is a real measurement: the run encodes every corpus+The encoding-size line is a real measurement: the run encodes every corpusvector as float32 bytes (`struct`) and as int8 codes and compares the actual-byte totals — 20480 B vs 5120 B, exactly 4.00×.+byte totals — 20480 B vs 5120 B, exactly 4.00×. It is the cost of the two+*encodings*, measured in the client. It is **not** a measurement of XERJ's+resident footprint, and XERJ does not currently realise it as one+([#392](https://github.com/xerj-org/xerj/issues/392)).## Reproduce it yourself@@ -110,7 +127,7 @@ overrides the KB path (default: auto-discovered `demo/data/ai_kb.ndjson`).The embedder and corpus are deterministic, so a customer should see exactly:- `recall@10 (scalar8 vs float32 ground truth): 0.998`-- `vector footprint over 40 vecs: float32 = 20480 B (512 B/vec) → scalar8 = 5120 B (128 B/vec) (4.00x smaller)`+- `encoding size over 40 vecs: float32 = 20480 B (512 B/vec) → scalar8 = 5120 B (128 B/vec) (4.00x smaller)`These numbers are stable run-to-run (verified across repeated runs — novariance); the printed kNN scores are likewise identical each run.@@ -125,3 +142,20 @@ variance); the printed kNN scores are likewise identical each run.is rejected at startup rather than silently storing full precision.- **Cosine is normalised** before quantizing for the tightest code range;`dot_product` and `l2_norm` similarities are supported too.+- **No memory saving yet.** The serving path reads the full-precision vector+ from `_source` and quantizes it per query, so `scalar8` costs the same RAM+ as float32 and a little more CPU. Tracked in+ [#392](https://github.com/xerj-org/xerj/issues/392).+- **`scalar8` disables ANN.** A quantized field is excluded from HNSW-served+ kNN and always takes the exact brute-force scan, so it is slower, not+ faster, than leaving the field full-precision. Also [#392](https://github.com/xerj-org/xerj/issues/392).+- **A `scalar8` `_score` depends on the candidate set.** The codebook is+ fitted per query over the candidates being scored — which is what keeps an+ updated document from being scored on a stale codebook+ ([#371](https://github.com/xerj-org/xerj/issues/371)) — so the same+ document can score marginally differently under two different `filter`s.+ The difference is bounded by SQ8's own quantization step (1/255 of the+ fitted per-dimension range), i.e. inside the approximation error `scalar8`+ already carries. Elasticsearch fixes its codebook per segment at index+ time and does not have this property; [#392](https://github.com/xerj-org/xerj/issues/392)+ is what would bring XERJ in line.diff --git a/engine/crates/xerj-api/tests/sq8_codebook_follows_the_corpus.rs b/engine/crates/xerj-api/tests/sq8_codebook_follows_the_corpus.rsnew file mode 100644index 000000000..130c55833--- /dev/null+++ b/engine/crates/xerj-api/tests/sq8_codebook_follows_the_corpus.rs@@ -0,0 +1,432 @@+//! A `quantization: "scalar8"` field must score the vector the document+//! CURRENTLY holds even when the new vector falls outside the range the+//! codebook was fitted from — issue #371, second half.+//!+//! `sq8_codes_follow_document_updates.rs` pins the per-document half: codes+//! must not be cached write-once per document id. This file pins the CODEBOOK+//! half, which is the same defect one level up. The per-dimension min/scale+//! pair (`Sq8Params`) was fitted from the first ≤1000 candidate vectors the+//! field was ever scanned with and then kept for the life of the process. A+//! vector written afterwards that falls outside that fitted range is clamped+//! into it, and when the fitted range is narrow the clamped decode is+//! indistinguishable from the vector that was there before — so the headline+//! symptom of #371 survives unchanged:+//!+//! * `codebook_tracks_a_vector_written_outside_the_fitted_range` — 20 docs+//! whose first dimension is pinned at +1.0, so dimension 0 fits to the+//! degenerate range [1,1]. Overwrite doc 0 with its exact negation and a+//! stale codebook decodes -1.0 straight back to +1.0: doc 0 still first at+//! `_score` 1.000000, whole score list frozen. Verbatim the issue.+//!+//! * `codebook_tracks_a_whole_corpus_re_embedding` — the workload the issue+//! names as what makes it a blocker. Fit the codebook on model-A vectors,+//! bulk-rewrite every document with model-B vectors, query with a model-B+//! vector. A stale codebook clamps the entire corpus onto a handful of+//! codes: every document collapses onto one identical score and the exact+//! match ranks nowhere.+//!+//! Both carry the full-precision index as a control through every step, so a+//! failure here cannot be a test artifact — the control performs the identical+//! manipulation and is asserted first.+//!+//! Elasticsearch is referenced for wire semantics only. It is AGPL-3.0/+//! SSPL-1.0/Elastic-2.0 licensed and no code from it is reproduced here.++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use tower::ServiceExt;++const SQ8: &str = "sq8";+const EXACT: &str = "exact";++async fn app() -> (axum::Router, tempfile::TempDir) {+ let dir = tempfile::tempdir().expect("tempdir");+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ let state = xerj_api::state::AppState::new(config, engine, metrics);+ (xerj_api::router::build_es_compat_router(state), dir)+}++async fn send(app: &axum::Router, req: Request<Body>) -> (StatusCode, Value) {+ let response = app.clone().oneshot(req).await.expect("response");+ let status = response.status();+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .expect("body");+ let value: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);+ (status, value)+}++async fn json_req(+ app: &axum::Router,+ method: &str,+ path: &str,+ body: Value,+) -> (StatusCode, Value) {+ send(+ app,+ Request::builder()+ .method(method)+ .uri(path)+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .expect("request"),+ )+ .await+}++async fn get(app: &axum::Router, path: &str) -> (StatusCode, Value) {+ send(+ app,+ Request::get(path).body(Body::empty()).expect("request"),+ )+ .await+}++async fn ndjson(app: &axum::Router, path: &str, body: String) -> (StatusCode, Value) {+ send(+ app,+ Request::builder()+ .method("POST")+ .uri(path)+ .header("content-type", "application/x-ndjson")+ .body(Body::from(body))+ .expect("request"),+ )+ .await+}++/// Create the quantized index and its full-precision control, identical apart+/// from the `quantization` option.+async fn create_pair(app: &axum::Router, dim: usize) {+ for (index, field_def) in [+ (+ SQ8,+ json!({ "type": "dense_vector", "dims": dim, "quantization": "scalar8" }),+ ),+ (EXACT, json!({ "type": "dense_vector", "dims": dim })),+ ] {+ let (status, body) = json_req(+ app,+ "PUT",+ &format!("/{index}"),+ json!({ "mappings": { "properties": { "v": field_def } } }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "create {index}: {body}");+ }+}++async fn refresh(app: &axum::Router, index: &str) {+ let (status, body) = json_req(app, "POST", &format!("/{index}/_refresh"), json!({})).await;+ assert!(status.is_success(), "refresh {index}: {status} {body}");+}++/// Write `vectors` into `index` through `_bulk`, then refresh.+async fn bulk_index(app: &axum::Router, index: &str, vectors: &[Vec<f32>]) {+ let mut body = String::new();+ for (i, v) in vectors.iter().enumerate() {+ body.push_str(&json!({ "index": { "_index": index, "_id": i.to_string() } }).to_string());+ body.push('\n');+ body.push_str(&json!({ "v": v }).to_string());+ body.push('\n');+ }+ let (status, response) = ndjson(app, "/_bulk?refresh=true", body).await;+ assert_eq!(status, StatusCode::OK, "bulk {index}: {response}");+ assert_eq!(+ response["errors"],+ json!(false),+ "bulk {index} reported errors: {response}"+ );+ refresh(app, index).await;+}++/// `(id, score)` for the whole corpus, in hit order.+async fn knn(app: &axum::Router, index: &str, query: &[f32], n: usize) -> Vec<(String, f64)> {+ let (status, body) = json_req(+ app,+ "POST",+ &format!("/{index}/_search"),+ json!({+ "knn": {+ "field": "v",+ "query_vector": query,+ "k": n,+ "num_candidates": n * 4+ },+ "size": n,+ "_source": false+ }),+ )+ .await;+ assert!(status.is_success(), "knn on {index}: {status} {body}");+ body["hits"]["hits"]+ .as_array()+ .unwrap_or_else(|| panic!("no hits on {index}: {body}"))+ .iter()+ .map(|h| {+ (+ h["_id"].as_str().expect("_id").to_string(),+ h["_score"].as_f64().expect("_score"),+ )+ })+ .collect()+}++fn score_of(hits: &[(String, f64)], id: &str) -> f64 {+ hits.iter()+ .find(|(hit_id, _)| hit_id == id)+ .unwrap_or_else(|| panic!("{id} missing from {hits:?}"))+ .1+}++fn rank_of(hits: &[(String, f64)], id: &str) -> usize {+ hits.iter()+ .position(|(hit_id, _)| hit_id == id)+ .unwrap_or_else(|| panic!("{id} missing from {hits:?}"))+}++/// Confirm the write landed in `_source`. If this fails nothing below means+/// anything.+async fn assert_source(app: &axum::Router, index: &str, id: &str, want: &[f32]) {+ let (status, body) = get(app, &format!("/{index}/_doc/{id}")).await;+ assert!(status.is_success(), "get {index}/{id}: {status} {body}");+ let stored: Vec<f64> = body["_source"]["v"]+ .as_array()+ .unwrap_or_else(|| panic!("no _source.v on {index}: {body}"))+ .iter()+ .map(|v| v.as_f64().expect("float"))+ .collect();+ let want: Vec<f64> = want.iter().map(|x| *x as f64).collect();+ assert_eq!(stored, want, "{index}/{id}: _source did not take the write");+}++/// How many distinct `_score` values the hit list carries. A codebook that has+/// clamped the whole corpus collapses this to 1.+fn distinct_scores(hits: &[(String, f64)]) -> usize {+ let mut seen: Vec<u64> = hits.iter().map(|(_, s)| s.to_bits()).collect();+ seen.sort_unstable();+ seen.dedup();+ seen.len()+}++// ─────────────────────────────────────────────────────────────────────────────+// 1. Narrow fitted range: the update falls outside the codebook+// ─────────────────────────────────────────────────────────────────────────────++const NARROW_DIM: usize = 8;+const NARROW_DOCS: usize = 20;++/// Every document pins dimension 0 at +1.0 and varies only in dimension 1, so+/// the fitted range for dimension 0 is the degenerate `[1, 1]`. That is what a+/// real corpus of near-identical embeddings looks like to a per-dimension+/// min/max fit, and it is the case a codebook cannot represent a later `-1`+/// in: it clamps back to `+1`.+fn narrow_vector(i: usize) -> Vec<f32> {+ let mut v = vec![0.0f32; NARROW_DIM];+ v[0] = 1.0;+ v[1] = i as f32 * 0.001;+ v+}++fn narrow_negated() -> Vec<f32> {+ narrow_vector(0).iter().map(|x| -x).collect()+}++#[tokio::test]+async fn codebook_tracks_a_vector_written_outside_the_fitted_range() {+ let (app, _dir) = app().await;+ create_pair(&app, NARROW_DIM).await;++ let corpus: Vec<Vec<f32>> = (0..NARROW_DOCS).map(narrow_vector).collect();+ bulk_index(&app, SQ8, &corpus).await;+ bulk_index(&app, EXACT, &corpus).await;++ let query = narrow_vector(0);++ // Step 1 — query once. This is what fits the codebook, over a corpus whose+ // dimension 0 never leaves +1.0.+ let sq8_before = knn(&app, SQ8, &query, NARROW_DOCS).await;+ let exact_before = knn(&app, EXACT, &query, NARROW_DOCS).await;+ for (index, hits) in [(SQ8, &sq8_before), (EXACT, &exact_before)] {+ assert_eq!(+ hits[0].0, "0",+ "{index}: doc 0 IS the query vector, it must rank first: {hits:?}"+ );+ }++ // Step 2/3 — overwrite doc 0 with its exact negation (true cosine -1) and+ // confirm the write landed.+ let negated = narrow_negated();+ for index in [SQ8, EXACT] {+ let (status, body) = json_req(+ &app,+ "PUT",+ &format!("/{index}/_doc/0"),+ json!({ "v": negated }),+ )+ .await;+ assert!(status.is_success(), "update {index}: {status} {body}");+ refresh(&app, index).await;+ assert_source(&app, index, "0", &negated).await;+ }++ // Step 4 — the same query again.+ let sq8_after = knn(&app, SQ8, &query, NARROW_DOCS).await;+ let exact_after = knn(&app, EXACT, &query, NARROW_DOCS).await;++ // Control first: if the full-precision index does not move doc 0 either,+ // the manipulation is wrong and the SQ8 assertion below is meaningless.+ assert_ne!(+ exact_after[0].0, "0",+ "EXACT control did not move doc 0 — the manipulation is wrong: {exact_after:?}"+ );+ assert!(+ score_of(&exact_after, "0") < 0.1,+ "EXACT control: doc 0 is the exact negation of the query, expected \+ _score 0.0, got {}: {exact_after:?}",+ score_of(&exact_after, "0")+ );++ // The assertion the stale codebook fails.+ assert_ne!(+ sq8_after[0].0, "0",+ "SQ8: doc 0 now holds the NEGATION of the query vector and must not be \+ the top hit. The codebook was fitted while dimension 0 never left \+ +1.0, so -1.0 clamps back to +1.0 and the document is scored on a \+ vector it no longer holds (#371): {sq8_after:?}"+ );+ let before_scores: Vec<f64> = sq8_before.iter().map(|(_, s)| *s).collect();+ let after_scores: Vec<f64> = sq8_after.iter().map(|(_, s)| *s).collect();+ assert_ne!(+ before_scores, after_scores,+ "SQ8: the score list is unchanged by a vector rewrite — the ranking is \+ frozen at first observation (#371): {sq8_after:?}"+ );+ let moved = score_of(&sq8_after, "0");+ assert!(+ moved < 0.1,+ "SQ8: doc 0 is the exact negation of the query (true cosine -1, _score \+ 0.0) but scored {moved}: {sq8_after:?}"+ );+}++// ─────────────────────────────────────────────────────────────────────────────+// 2. Whole-corpus re-embedding — the workload #371 calls out as the blocker+// ─────────────────────────────────────────────────────────────────────────────++const EMBED_DIM: usize = 16;+const EMBED_DOCS: usize = 50;+/// The document whose model-B vector is the query vector itself.+const TARGET: usize = 9;++/// "model A": a narrow positive cone. Every component sits within 0.7% of 1.0,+/// so after cosine's L2 normalisation each dimension occupies a band about+/// 0.0006 wide around 0.25. Real embedding models are famously anisotropic in+/// exactly this way, and a per-dimension min/max fit over such a corpus is a+/// codebook that can represent almost nothing else.+fn model_a(i: usize) -> Vec<f32> {+ (0..EMBED_DIM)+ .map(|d| 1.0 + ((i * 31 + d * 17) % 64) as f32 / 10_000.0)+ .collect()+}++/// "model B": a different embedding space entirely — components spread over+/// `[-1, 1]`, which is what swapping an embedding model actually does to a+/// corpus. Nothing here is inside model A's fitted range.+fn model_b(i: usize) -> Vec<f32> {+ (0..EMBED_DIM)+ .map(|d| ((i * 53 + d * 29) % 128) as f32 / 63.5 - 1.0)+ .collect()+}++#[tokio::test]+async fn codebook_tracks_a_whole_corpus_re_embedding() {+ let (app, _dir) = app().await;+ create_pair(&app, EMBED_DIM).await;++ let a: Vec<Vec<f32>> = (0..EMBED_DOCS).map(model_a).collect();+ let b: Vec<Vec<f32>> = (0..EMBED_DOCS).map(model_b).collect();++ bulk_index(&app, SQ8, &a).await;+ bulk_index(&app, EXACT, &a).await;++ // Query once under model A. This is what fits the codebook — over vectors+ // that all live in [0, 0.25].+ let warm = model_a(0);+ knn(&app, SQ8, &warm, EMBED_DOCS).await;+ knn(&app, EXACT, &warm, EMBED_DOCS).await;++ // Re-embed: rewrite every document with its model-B vector.+ bulk_index(&app, SQ8, &b).await;+ bulk_index(&app, EXACT, &b).await;+ for index in [SQ8, EXACT] {+ assert_source(&app, index, &TARGET.to_string(), &b[TARGET]).await;+ }++ // Query with a model-B vector whose exact match is doc TARGET.+ let query = model_b(TARGET);+ let sq8 = knn(&app, SQ8, &query, EMBED_DOCS).await;+ let exact = knn(&app, EXACT, &query, EMBED_DOCS).await;++ // Control first.+ assert_eq!(+ exact[0].0,+ TARGET.to_string(),+ "EXACT control: doc {TARGET} IS the query vector and must rank first: {exact:?}"+ );++ // A codebook clamped to model A's [0, 0.25] band maps the whole re-embedded+ // corpus onto the same handful of codes, which collapses every score onto+ // one value and destroys ranking entirely.+ let distinct = distinct_scores(&sq8);+ assert!(+ distinct > EMBED_DOCS / 2,+ "SQ8: {distinct} distinct scores across {EMBED_DOCS} re-embedded \+ documents — the codebook is still fitted to the pre-re-embedding \+ corpus and has clamped them together (#371): {sq8:?}"+ );+ let rank = rank_of(&sq8, &TARGET.to_string());+ assert_eq!(+ rank, 0,+ "SQ8: doc {TARGET} IS the query vector after re-embedding but ranks \+ {rank} — the codebook did not follow the corpus (#371): {sq8:?}"+ );+ // Doc TARGET is the query vector itself, so its `_score` is 1.0 on the+ // control. A codebook fitted to the pre-re-embedding corpus crushes it+ // into the same ~0.59 band as everything else; a codebook fitted to the+ // corpus that is actually there has to put it back near 1.0.+ let target_score = score_of(&sq8, &TARGET.to_string());+ assert!(+ target_score > 0.95,+ "SQ8: doc {TARGET} IS the query vector after re-embedding but scored \+ {target_score} (control: {}) — the codebook did not follow the corpus \+ (#371): {sq8:?}",+ score_of(&exact, &TARGET.to_string())+ );+ // Ranking discrimination, pinned against the control rather than against a+ // threshold picked out of this corpus: the quantized index must agree with+ // the full-precision one on the top of the re-embedded list. Under a stale+ // codebook the SQ8 order here is unrelated to the control's.+ let sq8_order: Vec<&str> = sq8.iter().map(|(id, _)| id.as_str()).collect();+ let exact_order: Vec<&str> = exact.iter().map(|(id, _)| id.as_str()).collect();+ assert_eq!(+ sq8_order[..5],+ exact_order[..5],+ "SQ8 and the full-precision control disagree on the post-re-embedding \+ top 5: {sq8:?} vs {exact:?}"+ );+ // And the score range must still span the corpus rather than sit in a+ // clamped band. The control spreads over roughly [0.22, 1.0]; a stale+ // codebook squeezed the whole 50 documents into 0.002.+ let spread = sq8[0].1 - sq8[sq8.len() - 1].1;+ assert!(+ spread > 0.5,+ "SQ8: the whole re-embedded corpus spans only {spread} in _score — \+ the codebook has clamped it into a band (#371): {sq8:?}"+ );+}diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rsindex 582acea6f..5bcb0e21d 100644--- a/engine/crates/xerj-common/src/config.rs+++ b/engine/crates/xerj-common/src/config.rs@@ -1148,12 +1148,17 @@ pub struct VectorConfig {/// **not implemented in this build** and is rejected at startup.////// - `"none"` — full float32 vectors (highest accuracy, most memory).- /// - `"scalar8"` — 8-bit scalar quantization (~4× memory reduction) — WIRED- /// into the kNN serving path. A `scalar8` dense_vector field keeps a- /// per-field u8 code store (1 byte/dim) and scores candidates by decoding- /// those codes, so the memory saving is real, not cosmetic. Typically- /// opted into per field via `index_options.type: int8_hnsw` on the- /// mapping; this global default applies the same scheme index-wide.+ /// - `"scalar8"` — 8-bit scalar quantization — WIRED into the kNN serving+ /// path, but it buys **precision, not memory**. A `scalar8` dense_vector+ /// field scores candidates from 1-byte-per-dimension codes, so it has the+ /// recall profile of int8 (measured recall@10 ≈ 0.998). It does NOT+ /// reduce resident memory: the scan reads the full-precision vector from+ /// `_source` and quantizes it per query, which is what keeps an updated+ /// document from being scored on stale codes or a stale codebook (#371).+ /// The ingest-time code array that would make a memory claim true is+ /// tracked in #392. Typically opted into per field via+ /// `index_options.type: int8_hnsw` on the mapping; this global default+ /// applies the same scheme index-wide./// - `"binary"` — 1-bit binary quantization (~32× memory reduction) — NOT/// YET IMPLEMENTED (no `BinaryQuantizer` exists).///diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 3c9c6de65..6b1859d77 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -5116,34 +5116,6 @@ impl RequestCacheSeen {// ── SQ8 serving-path codec ────────────────────────────────────────────────────-/// Per-field SQ8 (scalar8) codec used by the kNN serving path.-///-/// Holds the shared [`Sq8Params`] for one dense_vector field — the-/// per-dimension min/scale pair, fitted once from the first ~1000 vectors the-/// field is scanned with — and nothing else. In particular it does NOT cache-/// per-document codes: [`Index::run_knn_brute_force`] already has each-/// candidate's live f32 vector in hand (it just read it out of `_source` to-/// apply the filter), so it quantizes and dequantizes on the spot.-///-/// That is deliberate, and it is issue #371. The map this replaced was a-/// write-once `doc_id -> Vec<u8>`: a document's codes were computed by the-/// first kNN that observed it and never recomputed, so overwriting its vector-/// left it scored from the stale code forever — a document whose stored vector-/// was the exact negation of the query still came back at cosine 1.000000. Any-/// per-document code cache has to be invalidated on update, delete, reindex-/// and merge; keeping none removes the class. Lucene does not cache either —-/// it addresses quantized vectors by ordinal in a flat per-segment array-/// written at index time, so there is nothing to go stale.-struct Sq8FieldStore {- /// Shared per-dimension min/scale codec for this field.- ///- /// `Arc` so a scan can take a handle and drop the lock before scoring,- /// rather than holding a guard across the whole candidate loop.- params: Arc<Sq8Params>,- /// Vector dimensionality the params were fitted for.- dim: usize,-}-/// L2-normalise a vector in place (no-op for a zero vector). Used for cosine/// fields so SQ8 fits over bounded per-dimension ranges (better recall).fn l2_normalize_vec(v: &mut [f32]) {@@ -5367,16 +5339,6 @@ pub struct Index {/// `abort_background_tasks` so an unfinished rebuild can't hold the/// runtime (or the index Arc) alive across shutdown.hnsw_rebuild_task: Arc<parking_lot::Mutex<Option<tokio::task::JoinHandle<()>>>>,- /// Per-field SQ8 (scalar8) codecs for the kNN serving path.- ///- /// Keyed by dense_vector field name. Populated only for fields whose- /// mapping opts into `scalar8` quantization (`index_options.type:- /// int8_hnsw`). Each entry holds one shared [`Sq8Params`], fitted lazily on- /// the first kNN over the field from the same candidate vectors the- /// brute-force scan already gathers. No per-document state lives here — see- /// [`Sq8FieldStore`] for why (#371). Default (none) fields never touch this- /// map, so their exact f32 brute-force path is byte-identical to before.- sq8_stores: Arc<RwLock<HashMap<String, Sq8FieldStore>>>,// ── Per-index concurrency control ─────────────────────────────────────────/// Semaphore that limits the number of queries executing concurrently/// against this index. The default is 64 permits, matching the global@@ -6062,7 +6024,6 @@ impl Index {hnsw_stale: Arc::new(std::sync::atomic::AtomicBool::new(false)),hnsw_rebuilding: Arc::new(std::sync::atomic::AtomicBool::new(false)),hnsw_rebuild_task: Arc::new(parking_lot::Mutex::new(None)),- sq8_stores: Arc::new(RwLock::new(HashMap::new())),metric_query_count: Arc::new(AtomicU64::new(0)),metric_query_total_ms: Arc::new(AtomicU64::new(0)),metric_index_count: Arc::new(AtomicU64::new(0)),@@ -6428,7 +6389,6 @@ impl Index {hnsw_stale: Arc::new(std::sync::atomic::AtomicBool::new(hnsw_stale_init)),hnsw_rebuilding: Arc::new(std::sync::atomic::AtomicBool::new(false)),hnsw_rebuild_task: Arc::new(parking_lot::Mutex::new(None)),- sq8_stores: Arc::new(RwLock::new(HashMap::new())),metric_query_count: Arc::new(AtomicU64::new(0)),metric_query_total_ms: Arc::new(AtomicU64::new(0)),metric_index_count: Arc::new(AtomicU64::new(0)),@@ -10430,7 +10390,7 @@ impl Index {/// * the graph is field-pinned to exactly the queried field and not/// flush-time stale (see `hnsw_field` / `hnsw_stale`);/// * the field does not opt into SQ8 (`scalar8` keeps its dedicated- /// code-store scoring path);+ /// quantize-then-score brute path, which the graph does not model);/// * `vector_doc_count >= HNSW_MIN_DOCS` — small vector sets (every/// ES-YAML vector test is ≤ a few hundred docs) keep today's/// byte-identical exact path;@@ -10893,9 +10853,11 @@ impl Index {// ── Determine whether this field opts into SQ8 (scalar8) ──────// Default fields keep the exact f32 brute-force scan below,- // byte-identical to before. A `scalar8` field instead scores against- // a per-field u8 code store — decoding each doc's SQ8 codes rather- // than reading its f32 vector from `_source` for scoring.+ // byte-identical to before. A `scalar8` field takes the branch above+ // instead: it reads the same live f32 vector out of `_source`, but+ // rounds it through 1-byte-per-dimension SQ8 codes before scoring, so+ // the score carries `scalar8`'s precision loss. Nothing is cached —+ // neither the codes nor the codebook outlive the query (#371).let use_sq8 = {let schema = self.schema.read().await;lookup_vector_quantization(&schema.schema, field).as_deref() == Some("scalar8")@@ -10948,61 +10910,50 @@ impl Index {cand.push((id, src, doc_vec));}- // Take (or fit) this field's SQ8 codec. Only the per-dimension- // min/scale params are kept between queries — never per-document- // codes; see [`Sq8FieldStore`] for why (#371). The params are- // fitted from the first ≤1000 vectors the field is scanned with and- // then reused, so the codebook is stable across queries and a- // document's score does not depend on which query first saw it.- let params = {- let cached = {- let stores = self.sq8_stores.read().await;- stores- .get(field)- .filter(|store| store.dim == dim)- .map(|store| Arc::clone(&store.params))- };- match cached {- Some(params) => params,- None => {- let sample: Vec<Vec<f32>> =- cand.iter().take(1000).map(|(_, _, v)| v.clone()).collect();- let params = Arc::new(Sq8Params::fit(&sample, dim));- // Only publish a codec fitted on real vectors. A query- // whose candidate set came back empty (every doc- // filtered out, or a query vector of the wrong length)- // would otherwise install a degenerate all-zero-scale- // codebook and every later score on the field would- // collapse onto it.- if !sample.is_empty() {- debug!(- field,- dim,- sample = sample.len(),- normalize,- "SQ8 codec fitted"- );- // A concurrent first query may have fitted the same- // field meanwhile; either sample is equally valid,- // so overwrite rather than re-read under the lock.- self.sq8_stores.write().await.insert(- field.to_string(),- Sq8FieldStore {- params: Arc::clone(¶ms),- dim,- },- );- }- params- }- }- };+ // Fit this field's SQ8 codebook over the candidate vectors this+ // query is about to score, and drop it when the query ends. No+ // codec state survives a query (#371).+ //+ // The codebook used to be fitted from the first ≤1000 vectors the+ // field was ever scanned with and then kept for the life of the+ // process, which is the same write-once defect as the per-document+ // code map one level up: a vector written afterwards outside the+ // fitted per-dimension range is CLAMPED into it, and when that+ // range is narrow the clamped decode is indistinguishable from the+ // vector the document used to hold. A corpus whose dimension 0+ // never left +1.0 fitted `[1,1]` there, so overwriting a document+ // with its exact negation decoded straight back to +1.0 and it+ // stayed top at cosine 1.000000 — verbatim the reported symptom,+ // with the per-document map already gone.+ //+ // Fitting over exactly the set being encoded also makes clamping+ // structurally impossible here rather than merely unlikely: every+ // value passed to `encode_into` is inside `[min,max]` by+ // construction. An empty candidate set fits degenerate params, but+ // the scoring loop below is then empty too, so nothing observes+ // them — the old code had to guard against publishing that codec+ // because it outlived the query that produced it.+ //+ // ACCEPTED CONSEQUENCE: the codebook now depends on the candidate+ // set, so the same document can score marginally differently under+ // two different `filter`s. The difference is bounded by SQ8's own+ // quantization step (1/255 of the fitted range per dimension) —+ // inside the approximation error `scalar8` already advertises, and+ // the same class of dependency Lucene has by fitting per segment.+ let params = Sq8Params::fit_borrowed(cand.iter().map(|(_, _, v)| v.as_slice()), dim);+ debug!(+ field,+ dim,+ candidates = cand.len(),+ normalize,+ "SQ8 codec fitted for this query"+ );// Score by quantizing each candidate's CURRENT vector and decoding// it straight back — 1 byte/dim, so `scalar8` keeps its recall- // profile, and the score always describes the vector the document- // holds right now rather than one a previous query cached. Both- // buffers are reused across the scan, so this allocates nothing per+ // profile, and the score describes the vector the document holds+ // right now rather than one a previous query cached. Both buffers+ // are reused across the scan, so this allocates nothing per// document. `v.len() == dim` was established when `cand` was built.let mut codes = vec![0u8; dim];let mut decoded = vec![0.0f32; dim];diff --git a/engine/crates/xerj-vector/src/quantizer.rs b/engine/crates/xerj-vector/src/quantizer.rsindex c8af26a19..59c41b86d 100644--- a/engine/crates/xerj-vector/src/quantizer.rs+++ b/engine/crates/xerj-vector/src/quantizer.rs@@ -315,13 +315,26 @@ impl Quantizer for Scalar8Quantizer {/// Serializable per-dimension scalar-quantization (SQ8) parameters.////// This is the serving-path counterpart to [`Scalar8Quantizer`]: instead of-/// packing a whole batch into one blob, it exposes a fitted codec that the-/// engine keeps *per dense_vector field*. The engine stores one shared-/// `Sq8Params` per field (fitted from the first ~1000 vectors the field is-/// scanned with) and nothing else — the brute-force kNN scan quantizes each-/// candidate's current vector through it and dequantizes straight back, so-/// scores come from **1 byte/dim** codes without any per-document code cache-/// that could go stale after an update (issue #371).+/// packing a whole batch into one blob, it exposes a fitted codec cheap enough+/// to build per query. The brute-force kNN scan fits one of these over exactly+/// the candidate vectors it is about to score ([`Sq8Params::fit_borrowed`]),+/// quantizes each candidate's current vector through it, dequantizes straight+/// back, and drops it — so scores come from **1 byte/dim** codes while **no+/// SQ8 state outlives the query** (issue #371).+///+/// That is deliberate. Both a per-document `doc_id -> Vec<u8>` code map and a+/// per-field cached codebook were tried, and both were write-once in practice:+/// the map never recomputed a document's codes after an update, and the+/// codebook, fitted from the first ~1000 vectors a field was ever scanned+/// with, silently *clamped* every later vector into that range — so a document+/// overwritten with its own negation decoded straight back to its old value+/// and kept ranking first at cosine 1.000000. Fitting over the set being+/// encoded also makes clamping impossible here rather than merely unlikely.+///+/// The cost is that `scalar8` does not reduce resident memory: the scan reads+/// the full-precision vector from `_source` either way. Making codes live with+/// the data, addressed by ordinal and written at ingest as Lucene does, is+/// tracked in issue #392.////// `mins[d]`/`scales[d]` are the per-dimension minimum and range (`max-min`)/// observed in the fitting sample. `encode` maps `v[d]` linearly to a u8 in@@ -343,6 +356,22 @@ impl Sq8Params {/// different length are skipped. If no usable vector is present the/// params degenerate to zero scale (every code becomes 0, decoding to 0).pub fn fit(sample: &[Vec<f32>], dim: usize) -> Sq8Params {+ Sq8Params::fit_borrowed(sample.iter().map(|v| v.as_slice()), dim)+ }++ /// Fit per-dimension min/max over borrowed vectors.+ ///+ /// Identical math to [`Sq8Params::fit`], without requiring the caller to+ /// own the fitting sample. The kNN serving path fits over exactly the+ /// candidate vectors it is about to encode — which it already holds — so+ /// this lets it do that without copying the candidate set to build a+ /// sample. Fitting over the encoded set is also what makes clamping+ /// impossible on that path: every value encoded is inside `[min,max]` by+ /// construction (#371).+ pub fn fit_borrowed<'a, I>(sample: I, dim: usize) -> Sq8Params+ where+ I: IntoIterator<Item = &'a [f32]>,+ {let mut mins = vec![f32::MAX; dim];let mut maxs = vec![f32::MIN; dim];let mut seen = false;diff --git a/recipes/vector_quantization.py b/recipes/vector_quantization.pyindex 256cf6085..5ee7a4f6a 100644--- a/recipes/vector_quantization.py+++ b/recipes/vector_quantization.py@@ -4,7 +4,7 @@XERJ stores dense vectors at full float32 precision by default. Opting a`dense_vector` field into scalar8 quantization (`index_options.type:int8_hnsw`) makes the kNN *serving* path score against 1-byte-per-dimension-codes instead of 4-byte floats — a ~4x smaller vector working set with+codes instead of 4-byte floats — the recall profile of int8, withalmost no recall loss. `_source` still returns the original vectors.This recipe embeds the 40 real KB articles (demo/data/ai_kb.ndjson) into@@ -15,7 +15,13 @@ shows that:1. kNN returns the same top results from both,2. recall@10 of the quantized index vs the exact index stays >= 0.90,- 3. the quantized field's vector footprint is 4x smaller (1 vs 4 bytes/dim).+ 3. what the int8 encoding costs vs float32 (1 vs 4 bytes/dim).++NOTE: this changes PRECISION, not memory. XERJ reads the full-precision+vector from `_source` and quantizes it per query, so `scalar8` does not+shrink the resident vector working set today — see issue #392. The+footprint line below is the size of the ENCODING, not a saving XERJ+currently realises.Usage:xerj --insecure --data-dir ./data & # start XERJ@@ -138,10 +144,11 @@ def main():total += len(exact)recall = hits / total if total else 0.0print(f"recall@10 (scalar8 vs float32 ground truth): {recall:.3f}")- print(f"vector footprint: float32 = {DIM * 4} B/vec → scalar8 = {DIM} B/vec (4x smaller)")+ print(f"encoding size: float32 = {DIM * 4} B/vec → scalar8 = {DIM} B/vec (4x smaller)")if recall < 0.90:raise SystemExit(f"FAIL: recall {recall:.3f} < 0.90")- print("\nOK — 4x smaller vectors, recall preserved. `_source` still holds the originals.")+ print("\nOK — recall preserved through 1-byte-per-dim codes. `_source` still holds")+ print("the originals. scalar8 changes precision, not resident memory (issue #392).")if __name__ == "__main__":