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
Merge real/main (PR #979 semantic-scan rework) into feat/issue-392-dense-scalar8
xerj-orgf04c4734a535
diff --cc engine/crates/xerj-engine/src/index.rsindex a8d4755fb,ef4e9b9fc..21d66dd3e--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@@ -14355,47 -13904,41 +14403,68 @@@ 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 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).+ // 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.++ // 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.let use_sq8 = {let schema = self.schema.read().await;lookup_vector_quantization(&schema.schema, field).as_deref() == Some("scalar8")};++ // ── #392 fast path: unfiltered scalar8 kNN from ingest-time codes ──+ // 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+ // the use_sq8 branch further down.+ if use_sq8 && filter.is_none() {+ if let Some(result) = self+ .run_knn_sq8_codes_scan(+ request,+ deadline,+ field,+ query_vec,+ k,+ similarity,+ boost,+ min_similarity,+ started,+ )+ .await+ {+ return Ok(result);+ }+ }+- // ── Collect all candidate (doc_id, source) pairs ──────────────- let mut candidates: Vec<(String, Value)> = Vec::new();- // Memtable first (newest writes).- {- let mem = &*self.memtable;- candidates.extend(mem.all_docs_with_sources());- }+ // `scalar8` reads only the pooled vector; the default scan prefers the+ // per-passage companion. The two shapes are cached under different keys.+ let column_mode = if use_sq8 {+ ColumnMode::PooledOnly+ } else {+ ColumnMode::BestPassage+ };++ // ── Collect candidate ADDRESSES, not documents (#939) ─────────+ // A candidate is where a live document sits — a memtable slot or a+ // (segment, position) pair — never a copy of it. The scan this+ // replaces deep-cloned every live `_source`, vectors included, into+ // this list before it had scored or filtered anything: ~10 M+ // `Value::Number`s per query on a 5 k-document multi-passage corpus,+ // and half of each request. Sources are now cloned for the documents+ // that are RETURNED, after ranking. Same shape as qdrant's+ // `ScoredPointOffset` → `process_search_result` and tantivy's+ // `DocAddress` → `Searcher::doc` (pointers in `vector_column.rs`).+ //+ // Candidate ORDER is unchanged — memtable first, then segments in+ // snapshot order, then position — because the rank below is a stable+ // sort and that order is what breaks score ties.+ // Memtable first (newest writes). `Arc` clones, not tree clones.+ let mem_docs: Vec<(String, Arc<Value>)> = self.memtable.all_docs_with_sources_arc();+ let mut candidates: Vec<KnnCandidateAt> =+ (0..mem_docs.len()).map(KnnCandidateAt::Memtable).collect();// Then every flushed segment's stored section.let snap = self.store.snapshot();// Track seen IDs so later-segment copies don't duplicate memtable entries.@@@ -14491,12 -14074,20 +14600,22 @@@}let collect_elapsed = started.elapsed();+ // `use_sq8` was determined before candidate collection (the codes+ // fast path above may already have returned).+ // The filter runs BEFORE scoring and without the vectors (#939): see+ // `KnnFilterPlan`. It used to clone the whole source a second time,+ // per candidate, to insert `_id` beside ~1,900 numbers it never read.+ let filter_plan = filter.as_deref().map(KnnFilterPlan::for_filter);+ // Memtable documents have no column (the memtable is mutable), so+ // their vectors are read out of the `Arc`'d source one document at a+ // time into this reused scratch — after the filter, never before.+ let mut memtable_scratch = ColumnBuilder::new(field, column_mode);// ── Score each candidate against the query vector ─────────────- let mut scored: Vec<(String, f32, Value, Option<u32>)> =- Vec::with_capacity(candidates.len());+ // `(candidate index, score, passage ordinal)`: 16 bytes a candidate,+ // where this used to carry every candidate's cloned source through the+ // sort and then drop all but `k` of them.+ let mut scored: Vec<(usize, f32, Option<u32>)> = Vec::with_capacity(candidates.len());if use_sq8 {// Cosine fields are L2-normalised before quantising so SQ8 fits// over bounded [-1,1] per-dim ranges (much better recall); cosine@@@ -14538,133 -14130,81 +14658,143 @@@if normalize {l2_normalize_vec(&mut doc_vec);}- cand.push((id, src, doc_vec));+ cand.push((position, doc_vec));}- // 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.+ // ── #392: score from the INGEST-TIME codes when they cover the+ // candidate set ──────────────────────────────────────────────//- // ACCEPTED CONSEQUENCE: the codebook now depends on the candidate- // set, and that changes the RETURNED ORDER, not merely the score.- // Each individual score moves by at most SQ8's own quantization- // step (1/255 of the fitted range per dimension), which is inside- // the approximation error `scalar8` already advertises — but- // near-tied documents swap, so a caller sees a different ranking.- // Measured at the HTTP boundary on a 60-document 4-dim cosine- // field: adding a `filter` that removes only unrelated documents- // returned the same 30 survivors with max |Δ_score| 1.976e-05 but- // a different order at 19 of 30 positions. The trigger is the- // candidate set, not the `filter` keyword — indexing one more- // unrelated document moved the same corpus by max 7.100e-06 and- // reordered its top 10 — and on an unfiltered corpus over 1000- // documents every score also differs from rc.17, which fitted from- // the first <=1000 candidates and cached that (1500 documents: all- // of the top 40 changed, max 4.880e-05, one adjacent-rank swap).- // Documented in docs/recipes/vector-quantization.md and #392.- //- // This is NOT the dependency Lucene has. Lucene fits per segment at- // INDEX time, so a Lucene score is a function of the index state- // alone; here it is a function of the query's candidate set too.- // #392 is what would close that 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"- );+ // 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 (id, _, _) in cand.iter() {++ 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));+ }+ }+ }+ }- // 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 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, (candidate, v)) in cand.into_iter().enumerate() {- if position & 127 == 0 && self.exact_scan_checkpoint(position, deadline).await {- timed_out = true;- break;+ 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, ((id, src, _), codes)) in cand.into_iter().zip(codes).enumerate()++ 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((id, score, src, None));++ 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.++ // 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, 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.++ // 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);++ 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)"+ );++ // 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, (id, src, v)) in cand.into_iter().enumerate() {++ 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((id, score, src, None));++ scored.push((candidate, score, None));+ }}- 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` docs