Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

fix(engine,vector): #371 scalar8 kNN scored updated docs from stale codes

xerj-orgb832a6985de8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e94227142..73c40662d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
hits and every ES-compat response field are unchanged, and the hint stays
quiet 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**
+ ([#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.
## [1.0.0-rc.17] - 2026-08-15
diff --git a/demo/playbooks/ES_COMPATIBILITY.md b/demo/playbooks/ES_COMPATIBILITY.md
index 2411d061b..8a4bdcf90 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 (~4× smaller vector working set, recall@10 ≈ 0.99); `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.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.
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/engine/crates/xerj-api/tests/sq8_codes_follow_document_updates.rs b/engine/crates/xerj-api/tests/sq8_codes_follow_document_updates.rs
new file mode 100644
index 000000000..f9456e65d
--- /dev/null
+++ b/engine/crates/xerj-api/tests/sq8_codes_follow_document_updates.rs
@@ -0,0 +1,396 @@
+//! A `quantization: "scalar8"` field must score the vector the document
+//! CURRENTLY holds — issue #371.
+//!
+//! Before the fix, the per-field SQ8 code store was populated write-once on
+//! the first kNN that observed a document (`index.rs`, `if
+//! !store.codes.contains_key(id)`). Nothing invalidated an entry, so once a
+//! document had been scored its codes were frozen: overwrite its vector with
+//! the exact negation and the quantized index kept returning it at cosine
+//! 1.000000, with scores byte-identical to the query before the update, while
+//! the identical unquantized index correctly dropped it. Wrong results,
+//! silently, through a documented ES mapping option (`int8_hnsw`).
+//!
+//! These tests pin the observable from the outside, over real HTTP, in the
+//! shape the issue reported it:
+//!
+//! * a `PUT /{index}/_doc/{id}` that negates a vector must move that
+//! document out of the top of the result list on the `scalar8` index, not
+//! just on the full-precision control;
+//! * the same through `_bulk`, which is how every realistic re-embedding
+//! pipeline writes.
+//!
+//! The full-precision index is carried through every step as a control: it
+//! establishes that the manipulation itself is sound, so a failure here
+//! cannot be a test artifact. Both indices are asserted to agree on the
+//! ranking *before* the update, which is also what proves the SQ8 store was
+//! populated at all — a store that was never consulted could not go stale.
+//!
+//! 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 DIM: usize = 8;
+const DOCS: usize = 20;
+
+/// The one document the tests move. `[1,0,0,...]` before, its exact negation
+/// `[-1,0,0,...]` after — true cosine 1.0 then -1.0 against the query, the
+/// widest possible swing, so no threshold in here is delicate.
+const MOVED: &str = "0";
+
+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
+}
+
+/// The two indices under test: the quantized one and its full-precision
+/// control, identical in every other respect (8-dim, default `cosine`).
+const SQ8: &str = "sq8";
+const EXACT: &str = "exact";
+
+async fn create_pair(app: &axum::Router, sq8_field: Value) {
+ for (index, field_def) in [
+ (SQ8, sq8_field),
+ (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}");
+ }
+}
+
+/// The document that takes the top slot once doc 0 is negated. Its cosine
+/// against the query is 0.9939 against 0.4918 for the next filler doc, so the
+/// post-update winner is unambiguous and SQ8's approximation error cannot
+/// reorder it.
+const RUNNER_UP: &str = "2";
+
+/// Deterministic corpus.
+///
+/// * doc `0` is the query vector itself — cosine 1.0, the top hit;
+/// * doc `1` is its negation. That also anchors the fitted SQ8 range for
+/// dimension 0 at exactly -1, so doc 0's post-update code is representable
+/// rather than clamped, and its decoded score is exactly 0.0;
+/// * doc `2` is the clear runner-up (see [`RUNNER_UP`]);
+/// * the rest are spread over `[-1,1]` by a prime-stride walk, all distinct
+/// and all well below doc 2.
+fn corpus_vector(i: usize) -> Vec<f32> {
+ match i {
+ 0 => first_dim(1.0),
+ 1 => first_dim(-1.0),
+ 2 => {
+ let mut v = vec![0.0f32; DIM];
+ v[0] = 0.9;
+ v[1] = 0.1;
+ v
+ }
+ _ => (0..DIM)
+ .map(|d| ((i * 37 + d * 101) % 199) as f32 / 99.0 - 1.0)
+ .collect(),
+ }
+}
+
+fn first_dim(x: f32) -> Vec<f32> {
+ let mut v = vec![0.0f32; DIM];
+ v[0] = x;
+ v
+}
+
+fn negated() -> Vec<f32> {
+ corpus_vector(0).iter().map(|x| -x).collect()
+}
+
+async fn index_corpus(app: &axum::Router, index: &str) {
+ for i in 0..DOCS {
+ let (status, body) = json_req(
+ app,
+ "PUT",
+ &format!("/{index}/_doc/{i}"),
+ json!({ "v": corpus_vector(i) }),
+ )
+ .await;
+ assert!(status.is_success(), "index {index}/{i}: {status} {body}");
+ }
+ refresh(app, index).await;
+}
+
+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}");
+}
+
+/// `(id, score)` for the whole corpus, in hit order.
+async fn knn(app: &axum::Router, index: &str) -> Vec<(String, f64)> {
+ let (status, body) = json_req(
+ app,
+ "POST",
+ &format!("/{index}/_search"),
+ json!({
+ "knn": {
+ "field": "v",
+ "query_vector": corpus_vector(0),
+ "k": DOCS,
+ "num_candidates": 100
+ },
+ // `size` defaults to 10 and caps the hit list independently of `k`.
+ "size": DOCS,
+ "_source": false
+ }),
+ )
+ .await;
+ assert!(status.is_success(), "knn on {index}: {status} {body}");
+ let hits = body["hits"]["hits"]
+ .as_array()
+ .unwrap_or_else(|| panic!("no hits on {index}: {body}"));
+ assert_eq!(hits.len(), DOCS, "expected the whole corpus back: {body}");
+ hits.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
+}
+
+/// Assert the corpus is in its pre-update shape on `index`: doc 0 is the query
+/// vector, so it is the single best hit at cosine 1.0 (`_score` (1+cos)/2 = 1).
+/// This is also what populates the SQ8 code store — without it there would be
+/// no cached entry to go stale and the tests below would pass vacuously.
+fn assert_top_before(index: &str, hits: &[(String, f64)]) {
+ assert_eq!(
+ hits[0].0, MOVED,
+ "{index}: doc {MOVED} IS the query vector, it must rank first: {hits:?}"
+ );
+ assert!(
+ hits[0].1 > 0.99,
+ "{index}: doc {MOVED} must score ~1.0 before the update, got {}: {hits:?}",
+ hits[0].1
+ );
+}
+
+/// Assert the update landed in `_source` — the issue's step 3. If this fails
+/// the write never happened and nothing below would mean anything.
+async fn assert_source_negated(app: &axum::Router, index: &str) {
+ let (status, body) = get(app, &format!("/{index}/_doc/{MOVED}")).await;
+ assert!(status.is_success(), "get {index}/{MOVED}: {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> = negated().iter().map(|x| *x as f64).collect();
+ assert_eq!(stored, want, "{index}: _source did not take the update");
+}
+
+/// The assertion the bug fails: after the update, doc 0 holds the exact
+/// negation of the query, so it must be scored on that vector.
+fn assert_moved_out(index: &str, before: &[(String, f64)], after: &[(String, f64)]) {
+ assert_ne!(
+ after[0].0, MOVED,
+ "{index}: doc {MOVED} now holds the NEGATION of the query vector and \
+ must not be the top hit — it is being scored from a stale SQ8 code \
+ (#371): {after:?}"
+ );
+ assert_eq!(
+ after[0].0, RUNNER_UP,
+ "{index}: doc {RUNNER_UP} (cosine 0.9939) must take the top slot once \
+ doc {MOVED} is negated: {after:?}"
+ );
+ let moved = score_of(after, MOVED);
+ assert!(
+ moved < 0.1,
+ "{index}: doc {MOVED} is the exact negation of the query (true cosine \
+ -1, _score 0.0) but scored {moved}: {after:?}"
+ );
+ let before_scores: Vec<f64> = before.iter().map(|(_, s)| *s).collect();
+ let after_scores: Vec<f64> = after.iter().map(|(_, s)| *s).collect();
+ assert_ne!(
+ before_scores, after_scores,
+ "{index}: the score list is unchanged by a vector rewrite — the \
+ ranking is frozen at first observation (#371)"
+ );
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// 1. `PUT /{index}/_doc/{id}` — the shape reported in #371
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test]
+async fn sq8_scores_follow_a_document_update() {
+ let (app, _dir) = app().await;
+ create_pair(
+ &app,
+ json!({ "type": "dense_vector", "dims": DIM, "quantization": "scalar8" }),
+ )
+ .await;
+
+ index_corpus(&app, SQ8).await;
+ index_corpus(&app, EXACT).await;
+
+ // Step 1 — query once, which is what populates the SQ8 code store.
+ let sq8_before = knn(&app, SQ8).await;
+ let exact_before = knn(&app, EXACT).await;
+ assert_top_before(SQ8, &sq8_before);
+ assert_top_before(EXACT, &exact_before);
+
+ // Step 2/3 — overwrite doc 0 with its exact negation, and confirm it took.
+ for index in [SQ8, EXACT] {
+ let (status, body) = json_req(
+ &app,
+ "PUT",
+ &format!("/{index}/_doc/{MOVED}"),
+ json!({ "v": negated() }),
+ )
+ .await;
+ assert!(status.is_success(), "update {index}: {status} {body}");
+ refresh(&app, index).await;
+ assert_source_negated(&app, index).await;
+ }
+
+ // Step 4 — the same query again.
+ let sq8_after = knn(&app, SQ8).await;
+ let exact_after = knn(&app, EXACT).await;
+
+ // The control first: if the full-precision index does not move the
+ // document either, the manipulation is wrong and the SQ8 failure below
+ // would be meaningless.
+ assert_moved_out(EXACT, &exact_before, &exact_after);
+ assert_moved_out(SQ8, &sq8_before, &sq8_after);
+
+ // The quantized index must not merely have moved doc 0 — it must land on
+ // the same ordering the full-precision index does, to within SQ8 error.
+ let sq8_order: Vec<&str> = sq8_after.iter().map(|(id, _)| id.as_str()).collect();
+ let exact_order: Vec<&str> = exact_after.iter().map(|(id, _)| id.as_str()).collect();
+ assert_eq!(
+ sq8_order[..3],
+ exact_order[..3],
+ "quantized and exact indices disagree on the post-update top 3: \
+ {sq8_after:?} vs {exact_after:?}"
+ );
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// 2. `_bulk` — the path a re-embedding pipeline actually writes through
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// #371 was reported against `PUT /_doc/{id}` and explicitly did not test
+/// `_bulk`. `_bulk` is how vectors are rewritten in bulk after a model change,
+/// which is the workload that makes this a blocker, so it gets its own pin.
+/// The mapping is spelled `index_options.type: int8_hnsw` here — the
+/// Elasticsearch spelling an ES user reaches for by default, and the one that
+/// makes the defect reachable without ever typing "scalar8".
+#[tokio::test]
+async fn sq8_scores_follow_a_bulk_update() {
+ let (app, _dir) = app().await;
+ create_pair(
+ &app,
+ json!({
+ "type": "dense_vector",
+ "dims": DIM,
+ "index_options": { "type": "int8_hnsw" }
+ }),
+ )
+ .await;
+
+ index_corpus(&app, SQ8).await;
+ index_corpus(&app, EXACT).await;
+
+ let sq8_before = knn(&app, SQ8).await;
+ let exact_before = knn(&app, EXACT).await;
+ assert_top_before(SQ8, &sq8_before);
+ assert_top_before(EXACT, &exact_before);
+
+ for index in [SQ8, EXACT] {
+ let body = format!(
+ "{}\n{}\n",
+ json!({ "index": { "_index": index, "_id": MOVED } }),
+ json!({ "v": negated() })
+ );
+ 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;
+ assert_source_negated(&app, index).await;
+ }
+
+ let sq8_after = knn(&app, SQ8).await;
+ let exact_after = knn(&app, EXACT).await;
+ assert_moved_out(EXACT, &exact_before, &exact_after);
+ assert_moved_out(SQ8, &sq8_before, &sq8_after);
+}
diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rs
index 52fdc3bbe..582acea6f 100644
--- a/engine/crates/xerj-common/src/config.rs
+++ b/engine/crates/xerj-common/src/config.rs
@@ -275,11 +275,14 @@ impl Config {
));
}
- // Vector: `scalar8` (SQ8) quantization is now wired into the kNN
- // serving path (`Index::run_knn_brute_force`): a `scalar8` dense_vector
- // field keeps a per-field u8 code store (1 byte/dim vs 4) and scores
- // candidates by decoding those codes, giving a real ~4× reduction on
- // that field's vector working set. `none` and `scalar8` are therefore
+ // Vector: `scalar8` (SQ8) quantization is wired into the kNN serving
+ // path (`Index::run_knn_brute_force`): a `scalar8` dense_vector field
+ // scores candidates from 1-byte-per-dimension codes rather than their
+ // f32 values, so it has the recall profile of SQ8. It does not reduce
+ // resident memory today — the scan quantizes each candidate's current
+ // vector per query rather than caching codes, which is what keeps an
+ // updated document from being scored on a stale code (#371).
+ // `none` and `scalar8` are therefore
// accepted. `binary` (1-bit) has no implemented quantizer, so honouring
// it would silently store full-precision vectors while claiming a 32×
// saving — it stays rejected until a BinaryQuantizer lands.
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 00c2c4629..3c9c6de65 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -5114,32 +5114,34 @@ impl RequestCacheSeen {
}
}
-// ── SQ8 serving-path code store ───────────────────────────────────────────────
+// ── SQ8 serving-path codec ────────────────────────────────────────────────────
-/// Per-field in-memory SQ8 (scalar8) code store used by the kNN serving path.
+/// Per-field SQ8 (scalar8) codec used by the kNN serving path.
///
-/// Holds one shared [`Sq8Params`] (fitted from the first ~1000 ingested
-/// vectors for the field) plus a `doc_id -> Vec<u8>` code map. Each code vector
-/// is 1 byte per dimension — a quarter of the 4 bytes/dim an f32 vector costs —
-/// so this is the concrete artifact behind the ~4× memory claim. The store is
-/// consulted by [`Index::run_knn_brute_force`] instead of reading the f32
-/// vector from `_source` for scoring.
+/// 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.
- params: Sq8Params,
+ ///
+ /// `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,
- /// Whether vectors were L2-normalised before quantising (cosine fields).
- normalize: bool,
- /// doc_id → SQ8 codes (1 byte/dim).
- codes: HashMap<String, Vec<u8>>,
-}
-
-impl Sq8FieldStore {
- /// Total bytes held by the u8 code map — the working set we shrank 4×.
- fn code_bytes(&self) -> usize {
- self.codes.values().map(|c| c.len()).sum()
- }
}
/// L2-normalise a vector in place (no-op for a zero vector). Used for cosine
@@ -5365,17 +5367,15 @@ 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) code stores for the kNN serving path.
+ /// 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 store holds one shared [`Sq8Params`] plus a
- /// `doc_id -> Vec<u8>` code map (1 byte/dim, NOT 4), giving a real ~4×
- /// reduction on that field's vector working set. Built lazily on the first
- /// kNN over the field from the same (doc_id, source) candidates the
- /// brute-force scan already gathers, then refreshed incrementally as new
- /// docs appear. Default (none) fields never touch this map, so their exact
- /// f32 brute-force path is byte-identical to before.
+ /// 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
@@ -10948,57 +10948,73 @@ impl Index {
cand.push((id, src, doc_vec));
}
- // Build/refresh the per-field SQ8 code store: fit params once from
- // the first ≤1000 vectors, then encode any doc not yet stored. The
- // store holds u8 codes (1 byte/dim), so its steady-state footprint
- // is ~4× smaller than the f32 vectors it replaces for scoring.
- {
- let mut stores = self.sq8_stores.write().await;
- let store = stores.entry(field.to_string()).or_insert_with(|| {
- let sample: Vec<Vec<f32>> =
- cand.iter().take(1000).map(|(_, _, v)| v.clone()).collect();
- let params = Sq8Params::fit(&sample, dim);
- Sq8FieldStore {
- params,
- dim,
- normalize,
- codes: HashMap::new(),
- }
- });
- if store.dim == dim {
- for (id, _src, v) in cand.iter() {
- if !store.codes.contains_key(id) {
- store.codes.insert(id.clone(), store.params.encode(v));
+ // 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(&params),
+ dim,
+ },
+ );
}
+ params
}
- debug!(
- field,
- docs = store.codes.len(),
- code_bytes = store.code_bytes(),
- f32_bytes = store.codes.len() * store.dim * std::mem::size_of::<f32>(),
- normalize = store.normalize,
- "SQ8 code store refreshed"
- );
}
- }
+ };
- // Score by DECODING the stored SQ8 codes (never the raw f32).
- let stores = self.sq8_stores.read().await;
- if let Some(store) = stores.get(field) {
- let mut decoded = vec![0.0f32; store.dim];
- for (position, (id, src, _v)) in cand.into_iter().enumerate() {
- if position & 127 == 0 && self.exact_scan_checkpoint(position, deadline).await {
- timed_out = true;
- break;
- }
- let codes = match store.codes.get(&id) {
- Some(c) if c.len() == store.dim => c,
- _ => continue,
- };
- store.params.decode_into(codes, &mut decoded);
- let score = compute_vector_similarity(similarity, query_vec, &decoded);
- scored.push((id, score, src, None));
+ // 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
+ // document. `v.len() == dim` was established when `cand` was built.
+ let mut codes = vec![0u8; dim];
+ let mut decoded = vec![0.0f32; dim];
+ for (position, (id, src, v)) in cand.into_iter().enumerate() {
+ if position & 127 == 0 && self.exact_scan_checkpoint(position, deadline).await {
+ timed_out = true;
+ break;
}
+ params.encode_into(&v, &mut codes);
+ params.decode_into(&codes, &mut decoded);
+ let score = compute_vector_similarity(similarity, query_vec, &decoded);
+ scored.push((id, score, src, None));
}
} else {
// Per-chunk (passage) companion: multi-chunk `semantic_text` docs
diff --git a/engine/crates/xerj-vector/src/quantizer.rs b/engine/crates/xerj-vector/src/quantizer.rs
index 8aecc8662..c8af26a19 100644
--- a/engine/crates/xerj-vector/src/quantizer.rs
+++ b/engine/crates/xerj-vector/src/quantizer.rs
@@ -317,10 +317,11 @@ impl Quantizer for Scalar8Quantizer {
/// 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` (fitted from the first ~1000 ingested vectors for the field)
-/// plus a `doc_id -> Vec<u8>` code map, so the brute-force kNN scan reads
-/// **1 byte/dim** instead of the 4 bytes/dim an f32 vector costs — a ~4×
-/// reduction on the quantized field's vector working set.
+/// `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).
///
/// `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
@@ -380,18 +381,30 @@ impl Sq8Params {
/// Encode a full-precision vector to one u8 per dimension.
#[inline]
pub fn encode(&self, v: &[f32]) -> Vec<u8> {
- v.iter()
- .enumerate()
- .map(|(d, &x)| {
- let min = self.mins.get(d).copied().unwrap_or(0.0);
- let scale = self.scales.get(d).copied().unwrap_or(0.0);
- if scale == 0.0 {
- return 0u8;
- }
- let normalized = (x - min) / scale;
- (normalized * 255.0).round().clamp(0.0, 255.0) as u8
- })
- .collect()
+ let mut out = vec![0u8; v.len()];
+ self.encode_into(v, &mut out);
+ out
+ }
+
+ /// Encode into a caller-provided buffer, avoiding per-document allocation
+ /// on the hot kNN scan. `out` must be at least `v.len()` long.
+ ///
+ /// This is the counterpart to [`Sq8Params::decode_into`]: the scan
+ /// quantizes each candidate's current vector and dequantizes it straight
+ /// back, so a `scalar8` score is computed from 1-byte-per-dimension codes
+ /// without anything having to cache those codes per document.
+ #[inline]
+ pub fn encode_into(&self, v: &[f32], out: &mut [u8]) {
+ for (d, &x) in v.iter().enumerate() {
+ let min = self.mins.get(d).copied().unwrap_or(0.0);
+ let scale = self.scales.get(d).copied().unwrap_or(0.0);
+ if scale == 0.0 {
+ out[d] = 0u8;
+ continue;
+ }
+ let normalized = (x - min) / scale;
+ out[d] = (normalized * 255.0).round().clamp(0.0, 255.0) as u8;
+ }
}
/// Decode a code slice back to approximate f32 values (allocating).
@@ -740,7 +753,10 @@ mod tests {
}
}
- /// (b) MEMORY: the SQ8 code store is ~4× smaller than the f32 equivalent.
+ /// (b) MEMORY: SQ8 codes are ~4× smaller than the f32 vectors they encode.
+ /// This is a property of the codec, measured here on the codec. The engine
+ /// does not currently realize it as a resident saving on the kNN path — see
+ /// the note on [`Sq8Params`].
#[test]
fn sq8_store_is_quarter_of_f32() {
let n = 2000usize;