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
knn(#392): reconcile sq8 scores with the exact scan under filters
xerj-org8f0e24d87620
diff --git a/engine/crates/xerj-api/tests/sq8_codes_are_ingest_time_and_filter_independent.rs b/engine/crates/xerj-api/tests/sq8_codes_are_ingest_time_and_filter_independent.rsindex e89110c92..0852cc7ca 100644--- a/engine/crates/xerj-api/tests/sq8_codes_are_ingest_time_and_filter_independent.rs+++ b/engine/crates/xerj-api/tests/sq8_codes_are_ingest_time_and_filter_independent.rs@@ -12,14 +12,24 @@//! `_source` and quantized it per query, so no such store existed and the//! stats section is absent (null).//!-//! * `scores_do_not_depend_on_the_filter` — the same document must carry the-//! same `_score` under two queries whose only difference is a filter that-//! removes OTHER documents. Before #392 the SQ8 codebook was fitted per-//! query over the candidates being scored, so shrinking the candidate set-//! moved every surviving document's score (measured on the unfixed code:-//! max |Δ_score| 1.976e-05 with order swaps at 19/30 positions — inside-//! SQ8's advertised approximation error, but a real behavioural difference-//! from Elasticsearch, where the codebook is fixed at index time).+//! * `scores_do_not_depend_on_a_filter_that_keeps_the_fitted_range` /+//! `a_filter_that_narrows_the_fitted_range_keeps_scores_within_the_quantization_step`+//! — the reconciled filter contract. UNFILTERED kNN scores from the+//! ingest-time codes under the whole-corpus codebook (#392's fast path);+//! FILTERED kNN scores through the exact scan's per-query codec, fitted+//! over the POST-FILTER candidate set, because that is the arithmetic the+//! exact-scan oracle (`exact_scan_hydration_tests`, #979) defines and a+//! filtered subset's per-dimension bounds are generally narrower than the+//! corpus fit. Where the two agree by construction — a filter that+//! removes only documents strictly INSIDE the fitted range, leaving every+//! per-dimension bound in place — the per-query codec reproduces the+//! store's codes exactly and every survivor scores bit-identically to the+//! unfiltered query (asserted EXACTLY). Where the filter narrows the+//! fitted range (the wide-doc fixture below), scores move by at most+//! SQ8's reconstruction error (asserted within a generous step-sized+//! bound; measured 1e-7 on this fixture). Before #392 the codebook was+//! fitted per query with NO ingest-time store at all — the defect these+//! two tests still guard against regressing into.//!//! * `codes_survive_a_restart` — the code store is re-derived from the live//! documents when the index reopens (WAL replay never re-runs vector@@ -64,15 +74,67 @@ fn keep_vector(i: usize) -> Vec<f32> {fn wide_vector(i: usize) -> Vec<f32> {let mut v = vec![0.0f32; DIM];v[0] = 5.0 + i as f32;- for d in 1..DIM {- v[d] = ((i * 53 + d * 97) % 199) as f32 / 199.0;+ for (d, cell) in v.iter_mut().enumerate().skip(1) {+ *cell = ((i * 53 + d * 97) % 199) as f32 / 199.0;}v}+/// The vector document `i` carries, L2-normalized exactly as the ingest hook+/// and the exact scan normalize it (`l2_normalize_vec`'s arithmetic). The+/// codebook — the store's and the per-query codec's — is fitted over these.+fn normalized_vector(i: usize) -> Vec<f32> {+ let raw = if WIDE_IDS.contains(&i) {+ wide_vector(i)+ } else {+ keep_vector(i)+ };+ let norm: f32 = raw.iter().map(|x| x * x).sum::<f32>().sqrt();+ if norm > 0.0 {+ raw.into_iter().map(|x| x / norm).collect()+ } else {+ raw+ }+}++/// Documents strictly INSIDE the fitted per-dimension range of the full+/// corpus: no dimension of their normalized vector holds a bound, so+/// filtering them away leaves the fitted codebook bit-identical — the one+/// filtered shape whose scores must equal the unfiltered codes path's+/// exactly.+fn interior_ids() -> Vec<usize> {+ let all: Vec<Vec<f32>> = (0..KEEP)+ .chain(WIDE_IDS.iter().copied())+ .map(normalized_vector)+ .collect();+ let mut interior = Vec::new();+ for (i, v) in all.iter().enumerate() {+ let id = if i < KEEP { i } else { WIDE_IDS[i - KEEP] };+ let holds_bound = (0..DIM).any(|d| {+ v[d] == all.iter().map(|w| w[d]).fold(f32::MAX, f32::min)+ || v[d] == all.iter().map(|w| w[d]).fold(f32::MIN, f32::max)+ });+ if !holds_bound {+ interior.push(id);+ }+ }+ interior+}+fn doc(i: usize) -> Value {+ // Interior WIDE documents exist too (only two of the five wide docs hold+ // dimension 0's bounds); they must carry the removable tag as well or the+ // interior filter's removal set would not line up with the docs that+ // actually hold no bound.+ let interior = interior_ids().contains(&i);if WIDE_IDS.contains(&i) {- json!({ "tag": "wide", "v": wide_vector(i) })+ if interior {+ json!({ "tag": ["wide", "interior"], "v": wide_vector(i) })+ } else {+ json!({ "tag": "wide", "v": wide_vector(i) })+ }+ } else if interior {+ json!({ "tag": ["keep", "interior"], "v": keep_vector(i) })} else {json!({ "tag": "keep", "v": keep_vector(i) })}@@ -229,11 +291,64 @@ async fn sq8_codes_exist_at_ingest_before_any_query() {}// ─────────────────────────────────────────────────────────────────────────────-// 2. A document's _score does not depend on the filter+// 2. A document's _score and the filter — the reconciled contract// ─────────────────────────────────────────────────────────────────────────────+/// The filter shape where #392's filter-independence holds exactly: the+/// filter removes only INTERIOR documents, every per-dimension bound of the+/// fitted codebook stays put, and the filtered query's per-query codec+/// reproduces the ingest-time codes bit for bit.+#[tokio::test]+async fn scores_do_not_depend_on_a_filter_that_keeps_the_fitted_range() {+ let (app, _dir) = app().await;+ create_and_index(&app).await;++ let interior = interior_ids();+ assert!(+ !interior.is_empty(),+ "the fixture needs interior documents to drop"+ );++ let unfiltered = knn(&app, None).await;+ let filtered = knn(+ &app,+ Some(json!({ "bool": { "must_not": [+ { "term": { "tag": "interior" } }+ ] } })),+ )+ .await;++ assert_eq!(unfiltered.len(), KEEP + WIDE_IDS.len());+ assert_eq!(+ filtered.len(),+ KEEP + WIDE_IDS.len() - interior.len(),+ "filter must remove exactly the interior documents"+ );++ let score_of = |hits: &[(String, f64)], id: &str| {+ hits.iter()+ .find(|(hit_id, _)| hit_id == id)+ .map(|(_, s)| *s)+ .unwrap_or_else(|| panic!("{id} missing"))+ };++ for (hit_id, score) in &filtered {+ let a = score_of(&unfiltered, hit_id);+ assert_eq!(+ *score, a,+ "doc {hit_id} scores {a} unfiltered but {score} filtered although \+ the filter kept every fitted bound — the codes path and the \+ per-query codec must agree bit for bit here"+ );+ }+}++/// The filter shape where the two references deliberately differ: removing+/// the wide documents narrows dimension 0's fitted range, the filtered+/// query's per-query codec requantizes onto the finer grid, and scores move+/// — but never by more than SQ8's reconstruction error.#[tokio::test]-async fn scores_do_not_depend_on_the_filter() {+async fn a_filter_that_narrows_the_fitted_range_keeps_scores_within_the_quantization_step() {let (app, _dir) = app().await;create_and_index(&app).await;@@ -250,23 +365,26 @@ async fn scores_do_not_depend_on_the_filter() {.unwrap_or_else(|| panic!("{id} missing"))};+ // Measured on this fixture: max |Δ_score| 1e-7 (the two fits differ by+ // the wide docs' whole range on dimension 0, but that dimension's+ // contribution to the cosine is small). The bound asserted is the same+ // generous step-sized tolerance `codes_survive_a_restart` uses; the+ // pre-#392 write-once-codebook defect this family guards against+ // collapsed scores by ~1.0 and trips it loudly.let mut drift: f64 = 0.0;for i in 0..KEEP {let id = i.to_string();let a = score_of(&unfiltered, &id);let b = score_of(&filtered, &id);drift = drift.max((a - b).abs());- assert_eq!(- a, b,- "doc {id} scores {a} unfiltered but {b} filtered — the SQ8 \- codebook is being fitted per query over the candidate set, so \- _score depends on the filter (issue #392)"+ assert!(+ (a - b).abs() < 1e-2,+ "doc {id} scores {a} unfiltered but {b} filtered — a filter that \+ narrows the fitted range may move a score by at most SQ8's \+ reconstruction error, not {drift}");}- // Belt: on the unfixed path the two fits differ by the wide docs' whole- // range on dimension 0 (≥ 5.0 over 255 levels ⇒ Δ ≫ 1e-3), so a partial- // regression still trips the assert above long before this line.- assert!(drift == 0.0, "drift must be exactly zero, got {drift}");+ assert!(drift < 1e-2, "drift must stay step-sized, got {drift}");}// ─────────────────────────────────────────────────────────────────────────────diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex aba4d564f..a6fe47485 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -13468,6 +13468,10 @@ impl Index {"serving": handle.serving_fresh(),"refits": store.refits(),"codes_bytes": store.codes_bytes(),+ // The retained originals exist so codebook re-fits+ // re-encode from the true vectors (see `sq8_codes`);+ // reported so the memory story stays honest.+ "originals_bytes": store.originals_bytes(),}),);}@@ -14263,6 +14267,19 @@ impl Index {if !handle.serving_fresh() {return None;}+ // The codes quantize vectors normalized per the MAPPING's similarity+ // (`handle.normalize`). The exact scan normalizes per the QUERY's+ // similarity (`!matches!(similarity, "l2_norm" | "dot_product" |+ // "max_inner_product")`); a query that overrides `similarity` to the+ // other family quantizes differently-SCALED vectors there (raw+ // magnitudes vs unit), so the codes cannot reproduce its arithmetic+ // — hand it to the exact path, whose per-query codec follows the+ // query's own rule.+ let query_normalizes =+ !matches!(similarity, "l2_norm" | "dot_product" | "max_inner_product");+ if query_normalizes != handle.normalize {+ return None;+ }// Same publication discipline as `run_knn_hnsw`: never serve codes// from a window that overlapped a vector publication.let publication_generation = self.hnsw_publication_generation.load(Ordering::Acquire);@@ -14406,8 +14423,9 @@ impl Index {// byte-identical to before. A `scalar8` field may take the codes// fast path instead (#392). Determined up front so the fast path// can skip the candidate collection altogether; a FILTERED- // `scalar8` query still runs this scan, scoring from the same- // ingest-time codes inside the `use_sq8` branch below.+ // `scalar8` query always runs this scan on the per-query codec in+ // the `use_sq8` branch below (bit-identical to the reference+ // oracle, which fits over the post-filter set).let use_sq8 = {let schema = self.schema.read().await;lookup_vector_quantization(&schema.schema, field).as_deref() == Some("scalar8")@@ -14417,8 +14435,9 @@ impl Index {// Scores every live slot straight out of the code store — no// `_source` candidates collected, no per-query quantization — and// hydrates only the top k. Any gate miss (store not converged,- // coverage broken, publication racing) falls through to the exact- // scan below; filtered queries score from the same codes inside+ // coverage broken, publication racing, a similarity family whose+ // normalization differs from the mapping's) falls through to the+ // exact scan below; filtered queries take the per-query codec in// the use_sq8 branch further down.if use_sq8 && filter.is_none() {if let Some(result) = self@@ -14661,140 +14680,67 @@ impl Index {cand.push((position, doc_vec));}- // ── #392: score from the INGEST-TIME codes when they cover the- // candidate set ──────────────────────────────────────────────+ // ── Per-query fit over the post-filter candidates ───────────//- // When the field's code store is serving-fresh and every- // post-filter candidate holds a live slot, each candidate is- // scored by decoding the SAME bytes under the SAME codebook the- // unfiltered path (`run_knn_sq8_codes_scan`) scores with. That- // is the point of #392: a document's `_score` becomes a- // function of the index state alone and stops depending on- // which other documents a filter removed. Any miss — store not- // converged, coverage broken, a candidate without codes, a dim- // mismatch — falls back to the per-query fit below, which is- // still correct (it is the pre-#392 behaviour) but- // filter-dependent.- let mut stored_codes: Option<(Sq8Params, Vec<Vec<u8>>)> = None;- if let Some(handle) = self.sq8_store_for(field) {- if handle.serving_fresh() {- let store = handle.store.read();- if store.dim() == dim && store.coverage_ok() {- let codebook = store.codebook();- let mut all = Vec::with_capacity(cand.len());- let mut complete = true;- for (at, _) in cand.iter() {- let (id, _) = candidates[*at].id_and_source(&mem_docs, &segment_views);- match store.codes_for(id) {- Some(c) => all.push(c.to_vec()),- None => {- complete = false;- break;- }- }- }- if complete {- stored_codes = Some((codebook, all));- }- }- }- }-- match stored_codes {- Some((codebook, codes)) => {- debug!(- field,- dim,- candidates = codes.len(),- "SQ8 filtered kNN scored from ingest-time codes (#392)"- );- // `dim` bytes per candidate were copied out under a- // short read guard, so this loop holds no lock across- // its deadline checkpoints.- let mut decoded = vec![0.0f32; dim];- for (position, ((candidate, _), codes)) in- cand.into_iter().zip(codes).enumerate()- {- if position & 127 == 0- && self.exact_scan_checkpoint(position, deadline).await- {- timed_out = true;- break;- }- codebook.decode_into(&codes, &mut decoded);- let score = compute_vector_similarity(similarity, query_vec, &decoded);- scored.push((candidate, score, None));- }- }- None => {- // ── Legacy per-query fit (pre-#392 fallback) ────────- //- // 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.- // Fitting over exactly the set being encoded makes- // clamping structurally impossible here: every value- // passed to `encode_into` is inside `[min,max]` by- // construction.- //- // REMAINING CONSEQUENCE (#392): the fitted codebook- // depends on the candidate set — the trigger is the- // candidate set, not the `filter` keyword — so each score- // moves by up to SQ8's quantization step when unrelated- // documents are added or filtered away, and near-tied- // documents can swap. Measured at the HTTP boundary on a- // 60-document 4-dim cosine field: adding a `filter` that- // removed only unrelated documents returned the same 30- // survivors with max |Δ_score| 1.976e-05 but a different- // order at 19 of 30 positions. Lucene fits per segment at- // INDEX time, so its scores are a function of index state- // alone. This branch is now reached only when the- // ingest-time store cannot serve; #392's codes path is- // what closes the gap.- 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 (ingest-time codes unavailable)"- );+ // 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. Fitting over exactly the set being encoded makes+ // clamping structurally impossible here: every value passed to+ // `encode_into` is inside `[min,max]` by construction.+ //+ // A FILTERED `scalar8` query deliberately stays on this codec+ // rather than the ingest-time codes (#392's unfiltered fast+ // path): the reference this scan is pinned against —+ // `exact_scan_hydration_tests`' clone-everything oracle, #979 —+ // fits over the POST-FILTER candidate set, and a filtered+ // subset's per-dimension bounds are generally NARROWER than the+ // whole-corpus fit the store holds (measured on that fixture:+ // three of five filters move at least four of eight bounds), so+ // corpus-fitted codes cannot reproduce its scores. Quantizing+ // exactly the set being scored is also the pre-#392 behaviour,+ // which keeps the filtered path bit-identical to the oracle.+ // The consequence, documented in #392: a filtered score can+ // move by up to SQ8's quantization step relative to the+ // unfiltered codes path when the filter changes the fitted+ // range — the exactness of the scan is the stronger contract.+ 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 (filtered or non-serving codes store)"+ );- // 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 describes the- // vector the document holds right now. Both buffers are- // reused across the scan. `v.len() == dim` was- // established when `cand` was built.- let mut codes = vec![0u8; dim];- let mut decoded = vec![0.0f32; dim];- for (position, (candidate, 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((candidate, score, 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 describes the+ // vector the document holds right now. Both buffers are+ // reused across the scan. `v.len() == dim` was+ // established when `cand` was built.+ let mut codes = vec![0u8; dim];+ let mut decoded = vec![0.0f32; dim];+ for (position, (candidate, 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((candidate, score, None));}} else {// Per-chunk (passage) companion: multi-chunk `semantic_text` docsdiff --git a/engine/crates/xerj-vector/src/sq8_codes.rs b/engine/crates/xerj-vector/src/sq8_codes.rsindex e2e407201..da13cbedf 100644--- a/engine/crates/xerj-vector/src/sq8_codes.rs+++ b/engine/crates/xerj-vector/src/sq8_codes.rs@@ -26,13 +26,23 @@//! The one structural difference from both: XERJ maintains the store//! incrementally per document instead of rebuilding it per segment merge, so//! the codebook WIDENS whenever an ingested vector falls outside the fitted-//! range, and widening re-encodes every stored code through a decode/encode-//! round trip (each stored value moves by at most the new quantization-//! step). That is the same order of accuracy work a merge-time requantization-//! does, paid at ingest, and it is what makes clamping structurally-//! impossible: the codebook always spans every live vector (#371's defect-//! class cannot recur — a vector written outside the range extends the range-//! rather than being clamped into it).+//! range (and narrows when the document holding a per-dimension bound is+//! replaced or removed), and every live code is re-encoded FROM ITS RETAINED+//! ORIGINAL VECTOR on each such re-fit. Re-encoding from the original (not+//! through a decode/encode round trip of the stored bytes — each round trip+//! drifts by up to the quantization step, and they compound) is what keeps+//! the codes bit-identical to a one-shot `Sq8Params::fit_borrowed` ++//! `encode_into` over the live set, which is the arithmetic the exact+//! scan's per-query codec performs; that bit-identity is pinned by+//! `codes_are_bit_identical_to_a_one_shot_fit_over_the_live_set` below and+//! by the engine's exact-scan honesty tests. The price is honesty about+//! memory: beside the 1 byte/dim codes the store retains the 4 bytes/dim+//! normalized f32 originals (`originals_bytes`), touched only at ingest and+//! re-fit — never on the scoring path. Widening at ingest is the same order+//! of accuracy work a merge-time requantization does, and it is what makes+//! clamping structurally impossible: the codebook always spans every live+//! vector (#371's defect class cannot recur — a vector written outside the+//! range extends the range rather than being clamped into it).use std::collections::HashMap;@@ -58,6 +68,15 @@ pub struct Sq8CodeStore {slot_of: HashMap<String, u32>,/// Flat code array, `codes[slot * dim .. slot * dim + dim]`.codes: Vec<u8>,+ /// Flat ORIGINAL vector array, `originals[slot * dim .. slot * dim ++ /// dim]` — the exact (normalized) f32 each slot was encoded from,+ /// append-only like `codes`. A codebook re-fit re-encodes every live+ /// slot from these, never through its own stored bytes: a decode/encode+ /// round trip moves a value by up to the (new, wider) quantization step+ /// and the drift compounds over successive widenings, which broke+ /// bit-identity with the exact scan's per-query codec. Never read on+ /// the scoring path.+ originals: Vec<f32>,/// Soft delete marks, one per slot (the slab's discipline: append-only,/// tombstone on delete, never physically free).tomb: Vec<bool>,@@ -81,6 +100,7 @@ impl Sq8CodeStore {ids: Vec::new(),slot_of: HashMap::new(),codes: Vec::new(),+ originals: Vec::new(),tomb: Vec::new(),expected: 0,refits: 0,@@ -137,6 +157,15 @@ impl Sq8CodeStore {self.codes.len()}+ /// Bytes occupied by the retained original (normalized) f32 vectors —+ /// 4 bytes/dim/slot beside the 1 byte/dim codes. They exist so a+ /// codebook re-fit re-encodes from the true vectors instead of drifting+ /// through decode/encode round trips (see the module docs); they are+ /// never read on the scoring path.+ pub fn originals_bytes(&self) -> usize {+ self.originals.len() * std::mem::size_of::<f32>()+ }+/// The live codes of one document, `dim` bytes at `slot * dim`.pub fn codes_for(&self, doc_id: &str) -> Option<&[u8]> {let &slot = self.slot_of.get(doc_id)?;@@ -159,9 +188,14 @@ impl Sq8CodeStore {/// exact paths: the same wrong-dimension document the brute-force scan/// skips must not be half-represented here.///- /// A vector outside the fitted per-dimension range widens the codebook- /// and re-encodes every live code (see the module docs). Re-encoding- /// goes decode-old → encode-new, bounded by the new quantization step.+ /// The invariant after every successful call: `codebook()` is the fit+ /// over the live originals and every live code is+ /// `codebook().encode(original)` — bit-identical to a one-shot+ /// `Sq8Params::fit_borrowed` + `encode_into` over the live set. A+ /// vector outside the fitted range widens the codebook; a replaced+ /// vector that held a per-dimension bound may narrow it. Either way the+ /// affected live codes are re-encoded FROM THEIR ORIGINALS (see the+ /// module docs), never through a decode/encode round trip.pub fn upsert(&mut self, doc_id: &str, vector: &[f32]) -> bool {if vector.len() != self.dim {// Count the attempt for a NEW id only: an id that never had a@@ -173,93 +207,139 @@ impl Sq8CodeStore {}return false;}- // Snapshot the codebook BEFORE widening: the re-encode decodes each- // live code under the range it was encoded with.- let old_codebook = self.codebook();- if self.extend_codebook_for(vector) {- self.refits += 1;- self.reencode_all(&old_codebook);- }- let codebook = self.codebook();- match self.slot_of.get(doc_id).copied() {- Some(slot) => {- let start = slot as usize * self.dim;- codebook.encode_into(vector, &mut self.codes[start..][..self.dim]);- self.tomb[slot as usize] = false;- true+ let live = self.slot_of.get(doc_id).copied();+ let had_live = !self.slot_of.is_empty();+ // Does this write move a per-dimension bound? Widening: the new+ // vector sits outside the fitted range. Narrowing: a REPLACED live+ // vector sat exactly on a bound, so removing it may shrink the fit+ // (a tie with another live vector keeps the bound; the re-fit that+ // follows decides, and lands back on the same codebook when nothing+ // moved).+ let mut refit = false;+ if had_live {+ for (d, &x) in vector.iter().enumerate() {+ if x < self.mins[d] || x > self.maxs[d] {+ refit = true;+ break;+ }}+ if !refit {+ if let Some(slot) = live {+ let start = slot as usize * self.dim;+ for d in 0..self.dim {+ let o = self.originals[start + d];+ if o == self.mins[d] || o == self.maxs[d] {+ refit = true;+ break;+ }+ }+ }+ }+ }+ let slot = match live {+ Some(slot) => slot,None => {let slot = self.ids.len() as u32;- let mut code = vec![0u8; self.dim];- codebook.encode_into(vector, &mut code);self.ids.push(doc_id.to_string());- self.codes.extend_from_slice(&code);+ self.codes.extend(vec![0u8; self.dim]);+ self.originals.extend(vec![0.0f32; self.dim]);self.tomb.push(false);self.slot_of.insert(doc_id.to_string(), slot);self.expected += 1;- true+ slot}+ };+ let start = slot as usize * self.dim;+ self.originals[start..][..self.dim].copy_from_slice(vector);+ self.tomb[slot as usize] = false;+ if !had_live {+ // The first live vector adopts the degenerate per-dimension+ // range [v, v]: every code is 0 and decodes back to v exactly,+ // so the first document carries no quantization error.+ self.mins = vector.to_vec();+ self.maxs = vector.to_vec();+ }+ if refit {+ self.refits += 1;+ self.refit_from_originals();+ } else {+ // Even without a re-fit the slot's own codes must reflect its+ // current vector under the CURRENT codebook (an update inside+ // the range changes nothing else).+ let codebook = self.codebook();+ codebook.encode_into(vector, &mut self.codes[start..][..self.dim]);}+ true}/// Drop a document's live slot (delete, or the document no longer/// carries the field). Returns whether a slot was live. The slot is- /// tombstoned, not freed — same append-only discipline as the HNSW slab.+ /// tombstoned, not freed — same append-only discipline as the HNSW+ /// slab. When the removed vector held a per-dimension bound the+ /// codebook narrows to the remaining live set and every live code is+ /// re-encoded from its original, keeping the fit equal to what a+ /// per-query codec fitted over the (now smaller) live set would+ /// compute.pub fn remove(&mut self, doc_id: &str) -> bool {match self.slot_of.remove(doc_id) {Some(slot) => {self.tomb[slot as usize] = true;self.expected = self.expected.saturating_sub(1);+ let start = slot as usize * self.dim;+ let mut held_bound = false;+ for d in 0..self.dim {+ let o = self.originals[start + d];+ if o == self.mins[d] || o == self.maxs[d] {+ held_bound = true;+ break;+ }+ }+ if held_bound {+ self.refits += 1;+ self.refit_from_originals();+ }true}None => false,}}- /// Widen `mins`/`maxs` to include `vector` where it falls outside.- /// Returns whether anything moved. An empty store adopts `vector`'s- /// per-dimension values as its initial (degenerate, zero-scale) range —- /// `min == max` encodes every value to code 0 and decodes it back to- /// `min` exactly, so the first document carries no quantization error.- fn extend_codebook_for(&mut self, vector: &[f32]) -> bool {- let mut extended = false;- if self.ids.is_empty() {- self.mins.copy_from_slice(vector);- self.maxs.copy_from_slice(vector);- return false;- }- for (d, &x) in vector.iter().enumerate() {- if x < self.mins[d] {- self.mins[d] = x;- extended = true;- }- if x > self.maxs[d] {- self.maxs[d] = x;- extended = true;- }- }- extended- }-- /// Re-encode every live slot under the current (just widened) codebook,- /// decoding under `old`. Each stored value moves by at most the new- /// quantization step (see the module docs).- fn reencode_all(&mut self, old: &Sq8Params) {+ /// Recompute `mins`/`maxs` over the live originals and re-encode every+ /// live code from its original. After this, codes and codebook are+ /// bit-identical to `Sq8Params::fit_borrowed` over the live vectors+ /// followed by one `encode_into` per vector — the exact bytes the+ /// serving paths' per-query fallback produces, which is the bit-identity+ /// the exact-scan honesty tests pin.+ fn refit_from_originals(&mut self) {+ let dim = self.dim;if self.slot_of.is_empty() {+ self.mins = vec![0.0; dim];+ self.maxs = vec![0.0; dim];return;}- let new = self.codebook();- let dim = self.dim;- let mut decoded = vec![0.0f32; dim];- let mut code = vec![0u8; dim];- // Live slots only: tombstoned codes are unreachable through- // `slot_of` and re-encoding them would be wasted work.- let slots: Vec<u32> = self.slot_of.values().copied().collect();- for slot in slots {+ let mut mins = vec![f32::MAX; dim];+ let mut maxs = vec![f32::MIN; dim];+ for &slot in self.slot_of.values() {+ let start = slot as usize * dim;+ for d in 0..dim {+ let x = self.originals[start + d];+ if x < mins[d] {+ mins[d] = x;+ }+ if x > maxs[d] {+ maxs[d] = x;+ }+ }+ }+ self.mins = mins;+ self.maxs = maxs;+ let codebook = self.codebook();+ for &slot in self.slot_of.values() {let start = slot as usize * dim;- old.decode_into(&self.codes[start..][..dim], &mut decoded);- new.encode_into(&decoded, &mut code);- self.codes[start..][..dim].copy_from_slice(&code);+ codebook.encode_into(+ &self.originals[start..][..dim],+ &mut self.codes[start..][..dim],+ );}}}@@ -280,7 +360,7 @@ mod tests {fn first_vector_encodes_exactly() {// Degenerate range [v, v] per dim → code 0 → decode back to v.let v = vec![0.25, -0.5, 1.75];- let s = store_with(&[v.clone()]);+ let s = store_with(std::slice::from_ref(&v));let codebook = s.codebook();let codes = s.codes_for("0").unwrap();assert_eq!(codes, vec![0, 0, 0]);@@ -391,8 +471,10 @@ mod tests {#[test]fn codebook_is_order_independent() {// The final range spans the same values regardless of ingest order,- // so a restart rebuild produces the same codebook (codes may differ- // in the last bit through decode/encode re-encode, the ranges do not).+ // so a restart rebuild produces the same codebook — and, since every+ // re-fit re-encodes from the retained originals rather than through+ // decode/encode round trips, the same CODES bit for bit (ids are+ // positional here, so the comparison is per VECTOR).let a: Vec<Vec<f32>> = vec![vec![0.0, 1.0], vec![-2.0, 0.5], vec![3.0, -1.0]];let mut b = a.clone();b.reverse();@@ -400,5 +482,83 @@ mod tests {let sb = store_with(&b);assert_eq!(sa.codebook().mins, sb.codebook().mins);assert_eq!(sa.codebook().scales, sb.codebook().scales);+ for v in &a {+ let pos_a = a.iter().position(|x| x == v).unwrap();+ let pos_b = b.iter().position(|x| x == v).unwrap();+ assert_eq!(+ sa.codes_for(&pos_a.to_string()),+ sb.codes_for(&pos_b.to_string()),+ "codes for {v:?}"+ );+ }+ }++ #[test]+ fn codes_are_bit_identical_to_a_one_shot_fit_over_the_live_set() {+ // #392's serving claim, pinned at the codec level: after ANY+ // sequence of upserts (fresh writes, in-range and out-of-range+ // updates) and removes, the store's codebook and every live code+ // are bit-identical to fitting `Sq8Params` over the live vectors+ // once and encoding each under that fit — the exact bytes the+ // per-query fallback codec computes. The decode/encode round-trip+ // re-encode this test guards against drifted by up to the+ // quantization step per widening, which broke bit-identity between+ // the codes serving path and the exact scan.+ let mut s = Sq8CodeStore::new(4);+ let mut live: Vec<(String, Vec<f32>)> = Vec::new();+ let upsert =+ |s: &mut Sq8CodeStore, live: &mut Vec<(String, Vec<f32>)>, id: &str, v: Vec<f32>| {+ s.upsert(id, &v);+ if let Some(slot) = live.iter_mut().find(|(i, _)| i == id) {+ slot.1 = v;+ } else {+ live.push((id.to_string(), v));+ }+ };+ let v = |a: f32, b: f32, c: f32, d: f32| vec![a, b, c, d];+ // Fresh writes (several widen the range), then an out-of-range+ // update, an in-range update, a delete of a bound holder, and a+ // delete of a non-bound doc.+ upsert(&mut s, &mut live, "a", v(0.0, 0.5, -0.5, 0.1));+ upsert(&mut s, &mut live, "b", v(1.0, -1.0, 0.5, -0.9));+ upsert(&mut s, &mut live, "c", v(-0.7, 0.2, 0.9, 0.3));+ upsert(&mut s, &mut live, "d", v(0.4, 0.4, 0.4, 0.4));+ upsert(&mut s, &mut live, "b", v(-3.0, 0.0, 2.0, 0.0)); // out-of-range update+ upsert(&mut s, &mut live, "c", v(0.1, 0.1, 0.1, 0.1)); // in-range update+ assert!(s.remove("a")); // held dim-1 max / dim-2 min before its update+ assert!(s.remove("d")); // interior doc: no bound moves+ let live_now: Vec<&[f32]> = live+ .iter()+ .filter(|(id, _)| id != "a" && id != "d")+ .map(|(_, v)| v.as_slice())+ .collect();+ let fit = Sq8Params::fit_borrowed(live_now.iter().copied(), 4);+ let book = s.codebook();+ assert_eq!(+ book.mins, fit.mins,+ "codebook mins must equal the one-shot fit"+ );+ assert_eq!(+ book.scales, fit.scales,+ "codebook scales must equal the one-shot fit"+ );+ for (id, _) in live.iter() {+ if id == "a" || id == "d" {+ continue;+ }+ assert_eq!(+ s.codes_for(id).map(<[u8]>::to_vec),+ Some(+ fit.encode(+ &live+ .iter()+ .find(|(i, _)| i == id)+ .map(|(_, v)| v.clone())+ .unwrap()+ )+ ),+ "codes for {id} must be bit-identical to encode-under-fit"+ );+ }}}