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(search): BM25 statistics must be index-wide, not per scoring arm (#188)

xerj-org798baf2adfc2
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 2d635a515..e32300a0c 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -13470,6 +13470,73 @@ impl Index {
// paths, FTS, DocsForScan, and match_all.
let mut mem_matches_known: Option<u64> = None;
let mem_doc_count = self.memtable.doc_count();
+
+ // ── #188: INDEX-WIDE BM25 collection statistics ───────────────────
+ //
+ // BM25 only compares two documents when both were scored against the
+ // same `N`, `avgdl` and `doc_freq`. Historically every arm used its
+ // own: each segment scored against its own `FieldStats`, and the
+ // memtable against the union over its shards only. Two user-visible
+ // consequences:
+ //
+ // * overwriting a document PROMOTED it — its live copy moves to the
+ // memtable, and alone there it scores idf=ln(4/3), dl/avgdl=1,
+ // i.e. a fixed 0.28768 that beats almost any correctly-normalised
+ // segment hit, regardless of the document's real length;
+ // * scores tracked segment TOPOLOGY — the same 365-doc corpus
+ // flushed into 1 segment vs 16 scored `strong0` at 0.177 vs 0.570.
+ //
+ // Fix: fold one `CollectionStats` over every live arm (all segments
+ // plus the memtable) and hand it to BOTH the memtable scorer and every
+ // segment `FtsSearcher`. This is Lucene's shape —
+ // `IndexSearcher.fieldStats` sums `docCount`/`sumTotalTermFreq` over
+ // `reader.leaves()` and `TermStates.build` sums `docFreq` over them,
+ // then ONE `SimScorer` scores every leaf — and tantivy's
+ // (`Bm25StatisticsProvider for Searcher` sums over `segment_readers()`,
+ // `Bm25Weight::for_terms` builds one weight from it). It is also
+ // already this repo's convention on the columnar path:
+ // `leaf_constant_score` sums df + total_docs across every segment.
+ //
+ // SINGLE-ARM GATE. With at most one live scoring arm the union is the
+ // identity, so we skip it and take the historical path verbatim. That
+ // is not just an optimisation: for a memtable-only index the union
+ // would also redefine `N` from `doc_count()` (all memtable docs) to
+ // per-field docs-with-field, so the gate is what keeps every
+ // index → refresh → search shape — the ES-YAML suite's dominant one,
+ // and one segment per refresh on a 1-ingest-shard runner — byte-exact.
+ //
+ // `count_only` skips it too: a size:0 count never builds a scorer, and
+ // the pre-pass would be pure cost on the `term_doc_freq` shortcut.
+ //
+ // The stats derive from the SAME `snap` binding as the segment walk —
+ // taking a second snapshot would reintroduce the flush double-count
+ // race documented above and let scores and `hits.total` disagree
+ // mid-flush.
+ //
+ // LAZY. Several shapes that project to FTS never build a BM25 scorer
+ // at all — the columnar `scored_columnar` / `leaf_constant_score`
+ // routes, the precomputed-agg route, a segment loop the F1 early-break
+ // skips. Computing behind a `OnceCell` means only a query that
+ // actually scores pays the pre-pass, and it is computed at most once
+ // per search however many arms ask for it.
+ let stats_gate_open =
+ !count_only && snap.segments.len() + usize::from(mem_doc_count > 0) > 1;
+ // `OnceLock`, not `OnceCell`: `search_inner` is an async fn whose
+ // future must stay `Send`, and a `&OnceCell` is not.
+ let stats_cell: std::sync::OnceLock<Option<Arc<xerj_fts::CollectionStats>>> =
+ std::sync::OnceLock::new();
+ let collection_stats = || -> Option<Arc<xerj_fts::CollectionStats>> {
+ if !stats_gate_open {
+ return None;
+ }
+ stats_cell
+ .get_or_init(|| {
+ self.build_collection_stats(&snap, query, &text_fields, &exact_fields)
+ .map(Arc::new)
+ })
+ .clone()
+ };
+
let mem_snapshot = {
let mem = &*self.memtable;
if mem_doc_count == 0 {
@@ -13714,11 +13781,17 @@ impl Index {
let mut field_boosts: std::collections::HashMap<String, f32> =
std::collections::HashMap::new();
collect_field_boosts(query, &mut field_boosts);
- let (hits, mem_total) = mem.search_text_boosted_with_total(
+ // #188: score against the INDEX-WIDE statistics when the
+ // index has more than one live arm, so a document that an
+ // overwrite just moved into the memtable is normalised
+ // against the whole corpus rather than against itself.
+ let mem_stats = collection_stats();
+ let (hits, mem_total) = mem.search_text_boosted_with_total_using(
&text,
&field_filter,
mem_limit,
&field_boosts,
+ mem_stats.as_deref(),
);
if !hits.is_empty() {
let uncollected = mem_total.saturating_sub(hits.len() as u64);
@@ -14370,7 +14443,13 @@ impl Index {
// `timed_out: false`).
let searcher =
FtsSearcher::new(Arc::clone(&reader), Arc::clone(&self.registry))
- .with_deadline(Some(search_deadline));
+ .with_deadline(Some(search_deadline))
+ // #188: index-wide BM25 statistics — one union of
+ // avgdl/N/df over every segment plus the memtable,
+ // so `_score` stops depending on which segment a
+ // document happens to sit in. `None` keeps this
+ // segment's own stats (single-arm gate).
+ .with_collection_stats(collection_stats());
let fts_query = query_node_to_fts(query, &text_fields, &exact_fields);
// Count-only fast path for single-term FTS queries:
@@ -14540,7 +14619,9 @@ impl Index {
// candidate (rare). The exact live count above used
// `dead_matches` over the FULL set and is untouched.
let mut seg_hits = seg_hits;
- if deletes_present && fts_cap != usize::MAX && seg_total > fts_cap as u64
+ if deletes_present
+ && fts_cap != usize::MAX
+ && seg_total > fts_cap as u64
{
let dead_in_top = ghost_bm
.as_deref()
@@ -14794,30 +14875,31 @@ impl Index {
// set). Shared by the in-walk 2×cap eager
// trim and the end-of-run trim so admission
// and final ordering always agree.
- let trim_to_cap = |hits: Vec<Hit>| -> (Vec<Hit>, Option<f32>) {
- let mut decorated: Vec<(u64, Hit)> = hits
- .into_iter()
- .map(|h| {
- (
- self.lookup_seq_no(&h.id)
- .unwrap_or(u64::MAX),
- h,
- )
- })
- .collect();
- decorated.sort_by(|a, b| {
- b.1.score
- .partial_cmp(&a.1.score)
- .unwrap_or(std::cmp::Ordering::Equal)
- .then_with(|| a.0.cmp(&b.0))
- .then_with(|| a.1.id.cmp(&b.1.id))
- });
- decorated.truncate(materialisation_limit);
- let worst = decorated.last().map(|(_, h)| h.score);
- let kept =
- decorated.into_iter().map(|(_, h)| h).collect();
- (kept, worst)
- };
+ let trim_to_cap =
+ |hits: Vec<Hit>| -> (Vec<Hit>, Option<f32>) {
+ let mut decorated: Vec<(u64, Hit)> = hits
+ .into_iter()
+ .map(|h| {
+ (
+ self.lookup_seq_no(&h.id)
+ .unwrap_or(u64::MAX),
+ h,
+ )
+ })
+ .collect();
+ decorated.sort_by(|a, b| {
+ b.1.score
+ .partial_cmp(&a.1.score)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ .then_with(|| a.0.cmp(&b.0))
+ .then_with(|| a.1.id.cmp(&b.1.id))
+ });
+ decorated.truncate(materialisation_limit);
+ let worst = decorated.last().map(|(_, h)| h.score);
+ let kept =
+ decorated.into_iter().map(|(_, h)| h).collect();
+ (kept, worst)
+ };
for sh in &seg_hits {
// `seg_hits` descends by score, so once
// a hit's score is STRICTLY below the
@@ -18856,6 +18938,122 @@ impl Index {
/// instead of the IDF-less flat scorer. `None` (→ legacy flat scoring)
/// when the query isn't such a leaf, the memtable is non-empty, or any
/// segment lacks a clean column.
+ /// Fold the INDEX-WIDE BM25 collection statistics for one query (#188):
+ /// per-field `FieldStats` and per-(field, term) `doc_freq`, unioned over
+ /// every segment in `snap` PLUS the memtable.
+ ///
+ /// Modelled on `IndexSearcher.fieldStats` (sums `docCount` over
+ /// `reader.leaves()`) + `TermStates.build` (sums `docFreq` over them) —
+ /// Apache-2.0, adapted, not copied:
+ /// `lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java:1144-1159`
+ /// and `.../index/TermStates.java:96-126,158-164`; the Rust shape follows
+ /// tantivy's `Bm25StatisticsProvider for Searcher`
+ /// (`tantivy/src/query/bm25.rs:26-49`, MIT).
+ ///
+ /// `None` when there is nothing to unify — no FTS projection, or a query
+ /// whose field × term cross-product is too wide to be worth a pre-pass.
+ /// The caller then keeps the historical per-arm statistics.
+ ///
+ /// COST. Per segment this opens a STATS-ONLY reader
+ /// (`FtsIndexReader::open_stats_only`): the FST is mmap'd and `.meta` is
+ /// read, but the postings envelope (whole-file read + zstd decompress) and
+ /// the norms table (O(docs)) are skipped — they are the expensive parts of
+ /// a full open and the statistics never touch them. The pre-pass also
+ /// cannot defeat the two read-path fast paths it sits near: F1's
+ /// early-break requires `!query_needs_fts`, and the `term_doc_freq`
+ /// count-only shortcut requires `count_only` — the caller gates this
+ /// whole block off for both.
+ fn build_collection_stats(
+ &self,
+ snap: &xerj_storage::index_store::IndexSnapshot,
+ query: &QueryNode,
+ text_fields: &[String],
+ exact_fields: &HashSet<String>,
+ ) -> Option<xerj_fts::CollectionStats> {
+ // Widest (field × term) pre-pass we will pay for. A field-less
+ // `query_string` over a wide mapping can project hundreds of leaves;
+ // past this point the FST seeks stop being cheap relative to the
+ // search itself, and falling back to per-arm statistics is the
+ // conservative choice (same "decline rather than over-serve"
+ // convention as `MAX_QS_CROSS_PRODUCT`).
+ const MAX_STATS_PROBES: usize = 4096;
+
+ let fq = query_node_to_fts(query, text_fields, exact_fields)?;
+ let mut fields: Vec<String> = Vec::new();
+ collect_fts_query_fields(&fq, &mut fields);
+ if fields.is_empty() {
+ return None;
+ }
+ let mut pairs: Vec<(String, String)> = Vec::new();
+ collect_fts_query_terms(&fq, &mut pairs);
+ let field_refs: Vec<&str> = fields.iter().map(|s| s.as_str()).collect();
+
+ // The memtable's own contribution, analysed with ITS analyzer over the
+ // raw query text — the same input its FTS arm will score, so the
+ // tokens line up with the ones it actually uses. Collected FIRST so
+ // any token the segment projection never named (per-field analyzers
+ // can differ) joins `pairs` and gets its segment-side df in the single
+ // pass below, instead of the memtable silently keeping a local df.
+ let mem_stats: Option<xerj_fts::CollectionStats> = if self.memtable.doc_count() > 0 {
+ extract_query_text(query)
+ .and_then(|text| self.memtable.collection_stats(&text, &field_refs))
+ } else {
+ None
+ };
+ if let Some(ms) = mem_stats.as_ref() {
+ for (f, t) in ms.term_keys() {
+ if !pairs.iter().any(|(pf, pt)| pf == f && pt == t) {
+ pairs.push((f.clone(), t.clone()));
+ }
+ }
+ }
+
+ if (fields.len() + pairs.len()) * snap.segments.len().max(1) > MAX_STATS_PROBES {
+ return None;
+ }
+
+ let mut out = xerj_fts::CollectionStats::new();
+ let segments_dir = self.data_dir.join("segments");
+ for meta in snap.segments.iter() {
+ let Ok(reader) =
+ xerj_fts::FtsIndexReader::open_stats_only(&segments_dir, &meta.id, &field_refs)
+ else {
+ // A segment whose statistics we cannot read would skew the
+ // union low and silently inflate every other arm's IDF.
+ // Fall back to per-arm statistics rather than half a union.
+ return None;
+ };
+ for f in &fields {
+ if let Some(fs) = reader.field_stats(f) {
+ out.add_field(f, fs);
+ }
+ }
+ for (f, term) in &pairs {
+ if let Some(df) = reader.term_doc_freq(f, term) {
+ out.add_doc_freq(f, term, df as u64);
+ }
+ }
+ }
+ if let Some(ms) = mem_stats.as_ref() {
+ for (f, fs) in ms.field_iter() {
+ if fields.iter().any(|x| x == f) {
+ out.add_field(f, fs);
+ }
+ }
+ for (f, term) in &pairs {
+ if let Some(df) = ms.df(f, term) {
+ out.add_doc_freq(f, term, df);
+ }
+ }
+ }
+
+ if out.is_empty() {
+ None
+ } else {
+ Some(out)
+ }
+ }
+
fn leaf_constant_score(
&self,
q: &QueryNode,
@@ -31312,6 +31510,56 @@ fn collect_fts_query_fields(q: &FtsQuery, out: &mut Vec<String>) {
}
}
+/// The EXACT `(field, term)` pairs whose BM25 `doc_freq` this projected query
+/// will feed to a scorer (#188).
+///
+/// Only the leaves that carry a literal, analysed term are collected — the
+/// multi-term expansions (prefix / wildcard / fuzzy / phrase-prefix) resolve
+/// their terms per segment from that segment's own dictionary, so there is no
+/// query-time term set to gather an index-wide df for. Those leaves keep
+/// their local df; the index-wide `avgdl`/`N` from the same `CollectionStats`
+/// still applies to them via `make_scorer`, which is the dominant term.
+fn collect_fts_query_terms(q: &FtsQuery, out: &mut Vec<(String, String)>) {
+ let push = |field: &str, term: &str, out: &mut Vec<(String, String)>| {
+ let pair = (field.to_owned(), term.to_owned());
+ if !out.contains(&pair) {
+ out.push(pair);
+ }
+ };
+ match q {
+ FtsQuery::Term(t) => push(&t.field, &t.term, out),
+ FtsQuery::Phrase(p) => {
+ for term in &p.terms {
+ push(&p.field, term, out);
+ }
+ }
+ FtsQuery::PhrasePrefix(p) => {
+ // Every term but the last is a literal; the last is a prefix
+ // expanded per segment.
+ let n = p.terms.len();
+ for term in p.terms.iter().take(n.saturating_sub(1)) {
+ push(&p.field, term, out);
+ }
+ }
+ FtsQuery::Prefix(_) | FtsQuery::Wildcard(_) | FtsQuery::Fuzzy(_) | FtsQuery::MatchAll => {}
+ FtsQuery::Bool(b) => {
+ for sub in b
+ .must
+ .iter()
+ .chain(b.should.iter())
+ .chain(b.must_not.iter())
+ {
+ collect_fts_query_terms(sub, out);
+ }
+ }
+ FtsQuery::DisMax(d) => {
+ for sub in &d.queries {
+ collect_fts_query_terms(sub, out);
+ }
+ }
+ }
+}
+
/// Does this `query_string` analyse to ZERO searchable tokens?
///
/// `query_node_to_fts` declines a `QueryString` (returns `None`) for two
diff --git a/engine/crates/xerj-engine/src/memtable.rs b/engine/crates/xerj-engine/src/memtable.rs
index b46bd5802..5b8a46582 100644
--- a/engine/crates/xerj-engine/src/memtable.rs
+++ b/engine/crates/xerj-engine/src/memtable.rs
@@ -1021,7 +1021,7 @@ impl ShardedFtsMemtable {
limit: usize,
field_boosts: &std::collections::HashMap<String, f32>,
) -> Vec<MemtableHit> {
- self.search_text_boosted_inner(query, fields, limit, limit, field_boosts)
+ self.search_text_boosted_inner(query, fields, limit, limit, field_boosts, None)
.0
}
@@ -1041,54 +1041,94 @@ impl ShardedFtsMemtable {
limit: usize,
field_boosts: &std::collections::HashMap<String, f32>,
) -> (Vec<MemtableHit>, u64) {
- self.search_text_boosted_inner(query, fields, limit, usize::MAX, field_boosts)
+ self.search_text_boosted_inner(query, fields, limit, usize::MAX, field_boosts, None)
}
- /// Shared body: `shard_limit` caps each shard's hit materialisation
- /// (`usize::MAX` ⇒ the returned total is the exact global match count);
- /// `limit` caps the merged, score-sorted result.
- fn search_text_boosted_inner(
+ /// `search_text_boosted_with_total` scored against INDEX-WIDE BM25
+ /// statistics (#188).
+ ///
+ /// `stats` is the union over every live arm (all segments + this
+ /// memtable), computed once per search by the engine. Without it the
+ /// memtable's "global" statistics are global only across its own shards —
+ /// so a document whose live copy has just been moved here by an overwrite
+ /// scores against `N = 1`, `df = 1`, `dl/avgdl = 1`, and outranks every
+ /// correctly-normalised segment hit.
+ ///
+ /// `None` reproduces `search_text_boosted_with_total` bit-for-bit; the
+ /// engine passes `None` when the index has at most one live scoring arm.
+ pub fn search_text_boosted_with_total_using(
&self,
query: &str,
fields: &[&str],
limit: usize,
- shard_limit: usize,
field_boosts: &std::collections::HashMap<String, f32>,
+ stats: Option<&xerj_fts::CollectionStats>,
) -> (Vec<MemtableHit>, u64) {
- // Pre-pass: tokenise the query (use any shard's analyzer — they're
- // all the same registry-provided one) and aggregate per-term
- // global doc_freq + per-field global stats.
+ self.search_text_boosted_inner(query, fields, limit, usize::MAX, field_boosts, stats)
+ }
+
+ /// This memtable's contribution to the index-wide BM25 collection
+ /// statistics (#188): per-field `FieldStats` and per-(field, term)
+ /// doc_freq for the analysed `query` tokens, restricted to `fields`
+ /// (empty ⇒ every indexed field).
+ ///
+ /// Ghost-inclusive, exactly like the in-search aggregation it was hoisted
+ /// out of: tombstoned and superseded versions count until a flush/merge
+ /// purges them, which is what Lucene does and what keeps a delete from
+ /// silently shifting every score.
+ ///
+ /// Returns `None` when the memtable can't analyse the query (no analyzer,
+ /// or the query analyses to zero tokens) — the caller must then not build
+ /// index-wide stats at all rather than build partial ones.
+ pub fn collection_stats(
+ &self,
+ query: &str,
+ fields: &[&str],
+ ) -> Option<xerj_fts::CollectionStats> {
let analyzer = self.shards.iter().find_map(|s| {
let g = s.read();
g.registry
.get_analyzer("default")
.or_else(|| g.registry.get_analyzer("standard"))
- });
- let analyzer = match analyzer {
- Some(a) => a,
- None => return (Vec::new(), 0),
- };
+ })?;
let q_tokens = analyzer.analyze(query);
if q_tokens.is_empty() {
- return (Vec::new(), 0);
+ return None;
+ }
+ let (field_total_len, term_df) = self.aggregate_shard_stats(&q_tokens, fields);
+ let mut out = xerj_fts::CollectionStats::new();
+ for (fname, (sum, n)) in field_total_len {
+ out.add_field(
+ &fname,
+ &xerj_fts::FieldStats {
+ total_docs: n,
+ total_field_length: sum.round() as u64,
+ },
+ );
+ }
+ for ((fname, term), df) in term_df {
+ out.add_doc_freq(&fname, &term, df);
}
+ Some(out)
+ }
- // Delete-aware BM25 collection statistics (Lucene/ES parity): the
- // scoring N counts both live docs AND tombstoned/superseded versions
- // that have not yet been merged away. NOTE: this is *only* the N fed
- // to the BM25 IDF — hits.total and pagination still use the live
- // `doc_count()`, so a search over an index that has never had an
- // update/delete scores bit-for-bit identically to before.
- let mut global_doc_count: u64 = self.doc_count() as u64;
- // Aggregate (per-field global avg_field_len, per-(field,term) doc_freq).
+ /// Shared cross-shard fold behind both [`Self::collection_stats`] and the
+ /// in-search aggregation: `(per-field (Σ field_len, docs-with-field),
+ /// per-(field, term) doc_freq)`, ghosts included.
+ fn aggregate_shard_stats(
+ &self,
+ q_tokens: &[xerj_fts::analyzer::Token],
+ fields: &[&str],
+ ) -> (
+ std::collections::HashMap<String, (f64, u64)>,
+ std::collections::HashMap<(String, String), u64>,
+ ) {
let mut field_total_len: std::collections::HashMap<String, (f64, u64)> =
std::collections::HashMap::new();
- let mut term_global_df: std::collections::HashMap<(String, String), u64> =
+ let mut term_df: std::collections::HashMap<(String, String), u64> =
std::collections::HashMap::new();
for shard in &self.shards {
let g = shard.read();
- // Live N is already in `global_doc_count`; add tombstoned versions.
- global_doc_count += g.ghost_docs;
// Field length sums (live).
for (fname, (sum, n)) in &g.avg_field_lengths {
let entry = field_total_len.entry(fname.clone()).or_insert((0.0, 0));
@@ -1106,9 +1146,9 @@ impl ShardedFtsMemtable {
if !fields.is_empty() && !fields.iter().any(|f| f == fname) {
continue;
}
- for token in &q_tokens {
+ for token in q_tokens {
if let Some(pl) = postings.get(&token.text) {
- *term_global_df
+ *term_df
.entry((fname.clone(), token.text.clone()))
.or_insert(0) += pl.len() as u64;
}
@@ -1119,19 +1159,110 @@ impl ShardedFtsMemtable {
if !fields.is_empty() && !fields.iter().any(|f| f == fname) {
continue;
}
- for token in &q_tokens {
+ for token in q_tokens {
if let Some(df) = terms.get(&token.text) {
- *term_global_df
+ *term_df
.entry((fname.clone(), token.text.clone()))
.or_insert(0) += *df;
}
}
}
}
- let global_avg_field_len: std::collections::HashMap<String, f32> = field_total_len
- .into_iter()
- .map(|(k, (sum, n))| (k, if n == 0 { 0.0 } else { (sum / n as f64) as f32 }))
- .collect();
+ (field_total_len, term_df)
+ }
+
+ /// Shared body: `shard_limit` caps each shard's hit materialisation
+ /// (`usize::MAX` ⇒ the returned total is the exact global match count);
+ /// `limit` caps the merged, score-sorted result.
+ fn search_text_boosted_inner(
+ &self,
+ query: &str,
+ fields: &[&str],
+ limit: usize,
+ shard_limit: usize,
+ field_boosts: &std::collections::HashMap<String, f32>,
+ external: Option<&xerj_fts::CollectionStats>,
+ ) -> (Vec<MemtableHit>, u64) {
+ // Pre-pass: tokenise the query (use any shard's analyzer — they're
+ // all the same registry-provided one) and aggregate per-term
+ // global doc_freq + per-field global stats.
+ let analyzer = self.shards.iter().find_map(|s| {
+ let g = s.read();
+ g.registry
+ .get_analyzer("default")
+ .or_else(|| g.registry.get_analyzer("standard"))
+ });
+ let analyzer = match analyzer {
+ Some(a) => a,
+ None => return (Vec::new(), 0),
+ };
+ let q_tokens = analyzer.analyze(query);
+ if q_tokens.is_empty() {
+ return (Vec::new(), 0);
+ }
+
+ // ── Statistics fed to the per-shard scorers ──────────────────────
+ //
+ // TWO modes, and the difference is deliberate:
+ //
+ // * `external = Some(cs)` (#188) — the engine computed the INDEX-WIDE
+ // union (all segments + this memtable) and every arm scores against
+ // it, so a document's score no longer depends on which arm holds it.
+ // `N` is then per-field docs-with-field, matching Lucene's pairing
+ // of `FieldStats.docCount()` with `TermStats.docFreq()`.
+ // * `external = None` — the historical memtable-only aggregation,
+ // global across SHARDS with a single scalar `N`. Kept byte-exact
+ // because the engine takes this path whenever the index has at most
+ // one live scoring arm, where the union is the identity, and any
+ // drift there would move every memtable-only score.
+ //
+ // Delete-aware in both modes (Lucene/ES parity): the scoring `N`
+ // counts live docs AND tombstoned/superseded versions not yet merged
+ // away. This is *only* the BM25 IDF `N` — hits.total and pagination
+ // still use the live `doc_count()`.
+ let mut global_field_doc_count: std::collections::HashMap<String, u64> =
+ std::collections::HashMap::new();
+ let global_doc_count: u64;
+ let global_avg_field_len: std::collections::HashMap<String, f32>;
+ let term_global_df: std::collections::HashMap<(String, String), u64>;
+ match external {
+ Some(cs) => {
+ // Scalar N is unused in this mode (every scored field is in
+ // the per-field map), but keep it a sane non-zero fallback.
+ global_doc_count = self.doc_count() as u64;
+ let mut avg = std::collections::HashMap::new();
+ for (fname, fs) in cs.field_iter() {
+ avg.insert(fname.clone(), fs.avg_field_length());
+ global_field_doc_count.insert(fname.clone(), fs.total_docs);
+ }
+ global_avg_field_len = avg;
+ let mut df = std::collections::HashMap::new();
+ for token in &q_tokens {
+ for fname in global_avg_field_len.keys() {
+ if !fields.is_empty() && !fields.iter().any(|f| f == fname) {
+ continue;
+ }
+ if let Some(v) = cs.df(fname, &token.text) {
+ df.insert((fname.clone(), token.text.clone()), v);
+ }
+ }
+ }
+ term_global_df = df;
+ }
+ None => {
+ let mut n: u64 = self.doc_count() as u64;
+ for shard in &self.shards {
+ n += shard.read().ghost_docs;
+ }
+ global_doc_count = n;
+ let (field_total_len, df) = self.aggregate_shard_stats(&q_tokens, fields);
+ global_avg_field_len = field_total_len
+ .into_iter()
+ .map(|(k, (sum, n))| (k, if n == 0 { 0.0 } else { (sum / n as f64) as f32 }))
+ .collect();
+ term_global_df = df;
+ }
+ }
let mut all: Vec<MemtableHit> = Vec::new();
for s in &self.shards {
@@ -1140,6 +1271,7 @@ impl ShardedFtsMemtable {
fields,
shard_limit,
global_doc_count,
+ &global_field_doc_count,
&global_avg_field_len,
&term_global_df,
field_boosts,
@@ -2362,12 +2494,20 @@ impl FtsMemtable {
&std::collections::HashMap::new(),
&std::collections::HashMap::new(),
&std::collections::HashMap::new(),
+ &std::collections::HashMap::new(),
)
}
/// search_text variant that uses caller-supplied GLOBAL doc_count,
/// per-field avg lengths, and per-(field,term) doc frequencies.
/// Falls back to local stats when the global maps are empty.
+ ///
+ /// `global_field_doc_count` is the per-field `N` (docs WITH the field).
+ /// When it carries the field, it wins over the scalar `global_doc_count` —
+ /// that is the Lucene pairing (`FieldStats.docCount()` with
+ /// `TermStats.docFreq()`, `BM25Similarity.idfExplain`) and the shape the
+ /// index-wide statistics of #188 arrive in. Empty ⇒ the historical
+ /// single-scalar behaviour, so memtable-only searches score unchanged.
// The stats params mirror the cross-shard aggregation the orchestrator
// computes once per query; bundling them into a struct would just move
// the arity into a builder for a single internal call site.
@@ -2378,6 +2518,7 @@ impl FtsMemtable {
fields: &[&str],
limit: usize,
global_doc_count: u64,
+ global_field_doc_count: &std::collections::HashMap<String, u64>,
global_avg_field_len: &std::collections::HashMap<String, f32>,
global_term_df: &std::collections::HashMap<(String, String), u64>,
field_boosts: &std::collections::HashMap<String, f32>,
@@ -2435,8 +2576,15 @@ impl FtsMemtable {
.get(*field_name)
.copied()
.unwrap_or_else(|| self.avg_field_length(field_name));
+ // Per-field N (docs WITH the field) when the caller supplied
+ // index-wide statistics; the scalar otherwise.
+ let field_doc_count = global_field_doc_count
+ .get(*field_name)
+ .copied()
+ .filter(|n| *n > 0)
+ .unwrap_or(doc_count);
- let scorer = Bm25Scorer::new(avg_field_len, doc_count);
+ let scorer = Bm25Scorer::new(avg_field_len, field_doc_count);
// Per-field boost from the query tree (ES `boost` on match /
// `field^N` on multi_match). 1.0 when unboosted, so scores
// stay bit-identical for boost-free queries.
diff --git a/engine/crates/xerj-engine/tests/bm25_stats_are_index_wide.rs b/engine/crates/xerj-engine/tests/bm25_stats_are_index_wide.rs
new file mode 100644
index 000000000..3fdf09ce2
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/bm25_stats_are_index_wide.rs
@@ -0,0 +1,234 @@
+//! Regression tests for #188 — BM25 collection statistics must be
+//! INDEX-WIDE (every segment + the memtable), not per scoring arm.
+//!
+//! ## What #188 was
+//!
+//! Every arm scored against its own statistics: each segment used its own
+//! `FieldStats`, and the memtable used the union over its own shards only.
+//! BM25 is a comparison between documents, and it is only meaningful when
+//! both were normalised against the same `N`, `avgdl` and `doc_freq`. Two
+//! user-visible consequences fell out of that:
+//!
+//! 1. **Overwriting a document promoted it to first place.** An overwrite
+//! moves the live copy into the memtable. Alone there it scores
+//! `N = 1`, `df = 1`, `dl/avgdl = 1` → `idf = ln(4/3) = 0.2876821` and
+//! `tf_norm = 1.0`: a fixed 0.28768212 that outranks almost any
+//! correctly-normalised segment hit, no matter how long the document
+//! actually is. That is the failure
+//! `search_bounded_under_ghosts::size5_returns_global_top5_under_ghosts_on_large_matchset`
+//! caught on a 2-core box.
+//! 2. **Scores tracked segment TOPOLOGY.** `engine.ingest_shards` defaults
+//! to `(cpus/2).next_power_of_two()` and a flush drains one segment per
+//! non-empty shard, so the SAME corpus lands in 1 segment on a 2-core
+//! runner and ~16 on a 32-core one. Before the fix that alone moved
+//! `strong0` from 0.177 to 0.570 — 3.2× — and moved a never-touched
+//! weak doc by 13×.
+//!
+//! (2) is why (1) reproduced only on 2 cores: with 16 shards the strong docs
+//! land in near-single-doc segments whose inflated local scores happen to
+//! clear the memtable doc's fixed 0.28768. One instance of the bug masked
+//! the other, so "passes on 32 cores" was a false green and nothing in the
+//! suite could see it.
+//!
+//! The test below is therefore written against the property, not the
+//! symptom: **the same corpus and query must produce the same scores
+//! whatever the shard/segment topology.** It needs no `taskset` — it varies
+//! `ingest_shards` directly — and it fails on every pair of topologies before
+//! the fix.
+
+use serde_json::json;
+use std::sync::Arc;
+use tempfile::TempDir;
+use xerj_common::config::Config;
+use xerj_common::types::Schema;
+use xerj_engine::{Engine, Index};
+use xerj_query::parse_request;
+
+fn make_engine(dir: &TempDir, ingest_shards: usize) -> Engine {
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ config.engine.ingest_shards = ingest_shards;
+ Engine::new(config).expect("engine::new")
+}
+
+/// One buried occurrence of the term in a LONG field that grows with `i` —
+/// low BM25, strictly decreasing.
+fn weak_body(i: usize) -> String {
+ let pad = "pad ".repeat(40 + i * 3);
+ format!("{pad} quicklist {pad}")
+}
+
+fn match_body(size: usize) -> xerj_query::ast::SearchRequest {
+ parse_request(&json!({
+ "size": size,
+ "query": {"match": {"body": "quicklist"}}
+ }))
+ .expect("parse_request")
+}
+
+fn page(hits: &[xerj_query::Hit]) -> Vec<(String, f32)> {
+ hits.iter().map(|h| (h.id.clone(), h.score)).collect()
+}
+
+/// 60 weak docs in one flush + 5 strong docs in another, then an overwrite so
+/// one live copy sits in the memtable while everything else is segment-resident.
+async fn build_corpus(idx: &Arc<Index>) {
+ for i in 0..60 {
+ idx.index_document(Some(format!("weak{i:03}")), json!({"body": weak_body(i)}))
+ .await
+ .unwrap();
+ }
+ idx.flush().await.unwrap();
+ for i in 0..5 {
+ let body = "quicklist ".repeat(10 - i) + &"filler ".repeat(i * 4);
+ idx.index_document(Some(format!("strong{i}")), json!({"body": body}))
+ .await
+ .unwrap();
+ }
+ idx.flush().await.unwrap();
+ // The #188 trigger: an overwrite with IDENTICAL content. Nothing about
+ // the document changes — only WHERE its live copy lives.
+ idx.index_document(Some("weak001".into()), json!({"body": weak_body(1)}))
+ .await
+ .unwrap();
+}
+
+/// The gate that defines "fixed": `_score` is a function of the index, not of
+/// how many shards happened to flush.
+#[tokio::test]
+async fn scores_are_identical_across_shard_topologies() {
+ let mut baseline: Option<(usize, Vec<(String, f32)>)> = None;
+
+ for shards in [1usize, 2, 4, 16] {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir, shards);
+ engine.create_index("t", Schema::empty()).unwrap();
+ let idx = engine.get_index("t").unwrap();
+ build_corpus(&idx).await;
+
+ let got = page(&idx.search(&match_body(100)).await.unwrap().hits);
+ assert!(!got.is_empty(), "shards={shards}: no hits at all");
+
+ match &baseline {
+ None => baseline = Some((shards, got)),
+ Some((base_shards, base)) => assert_eq!(
+ &got, base,
+ "ingest_shards={shards} scored differently from ingest_shards={base_shards} \
+ — BM25 statistics are still per-arm, so `_score` depends on segment topology"
+ ),
+ }
+ }
+}
+
+/// The reported symptom, stated directly: an overwrite must not change a
+/// document's rank. `weak001` is the second-longest weak body with a single
+/// buried occurrence — it belongs near the BOTTOM, and it must land in exactly
+/// the same place whether or not its live copy was just moved to the memtable.
+#[tokio::test]
+async fn overwriting_a_document_does_not_change_its_rank() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir, 4);
+ engine.create_index("t", Schema::empty()).unwrap();
+ let idx = engine.get_index("t").unwrap();
+
+ for i in 0..60 {
+ idx.index_document(Some(format!("weak{i:03}")), json!({"body": weak_body(i)}))
+ .await
+ .unwrap();
+ }
+ for i in 0..5 {
+ let body = "quicklist ".repeat(10 - i) + &"filler ".repeat(i * 4);
+ idx.index_document(Some(format!("strong{i}")), json!({"body": body}))
+ .await
+ .unwrap();
+ }
+ idx.flush().await.unwrap();
+
+ let before = page(&idx.search(&match_body(100)).await.unwrap().hits);
+ let rank_before = before.iter().position(|(id, _)| id == "weak001").unwrap();
+ assert!(
+ rank_before > 5,
+ "sanity: weak001 is a long field with one buried hit, it must not start in the top 5 \
+ (was rank {rank_before}): {:?}",
+ &before[..6.min(before.len())]
+ );
+
+ // Re-index it with byte-identical content: the ONLY change is that its
+ // live copy now lives in the memtable instead of a segment.
+ idx.index_document(Some("weak001".into()), json!({"body": weak_body(1)}))
+ .await
+ .unwrap();
+
+ let after = page(&idx.search(&match_body(100)).await.unwrap().hits);
+ let rank_after = after.iter().position(|(id, _)| id == "weak001").unwrap();
+ assert_eq!(
+ rank_after,
+ rank_before,
+ "an overwrite with identical content moved weak001 from rank {rank_before} to \
+ rank {rank_after} — the memtable arm is scoring against its own statistics \
+ (top of page after the overwrite: {:?})",
+ &after[..3.min(after.len())]
+ );
+
+ // The whole ORDER must be unchanged, not just weak001's slot.
+ let ids = |p: &[(String, f32)]| p.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>();
+ assert_eq!(
+ ids(&after),
+ ids(&before),
+ "an overwrite with identical content reordered the page"
+ );
+
+ // Absolute scores DO move very slightly, and that is the designed
+ // behaviour, not a leak: collection statistics are physical /
+ // ghost-inclusive (Lucene counts deleted and superseded documents in
+ // docFreq/docCount until a merge purges them), so the overwrite's
+ // superseded copy adds one document and its 87 tokens to N and to
+ // Σ field length until the next merge. What must NOT happen is a
+ // reordering — pin the drift to something far smaller than the gap
+ // between adjacent ranks so a regression to per-arm statistics (which
+ // moved weak001 by 28×) cannot hide inside it.
+ for ((id_a, s_a), (id_b, s_b)) in after.iter().zip(before.iter()) {
+ assert_eq!(id_a, id_b);
+ let drift = (s_a - s_b).abs() / s_b.max(f32::MIN_POSITIVE);
+ assert!(
+ drift < 0.05,
+ "{id_a}: score moved {:.1}% ({s_b} → {s_a}) on an identical-content overwrite — \
+ more than the ghost-inclusive N can explain",
+ drift * 100.0
+ );
+ }
+}
+
+/// The union must not leak GHOSTS as live hits or lose the delete-aware
+/// accounting: statistics stay physical (Lucene counts deleted docs until a
+/// merge purges them) while `hits.total` stays live.
+#[tokio::test]
+async fn deletes_do_not_break_the_union() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir, 4);
+ engine.create_index("t", Schema::empty()).unwrap();
+ let idx = engine.get_index("t").unwrap();
+ build_corpus(&idx).await;
+
+ assert!(idx.delete_document("weak000").await.unwrap());
+
+ let r = idx.search(&match_body(100)).await.unwrap();
+ // 60 weak - 1 deleted + 5 strong = 64 live matches.
+ assert_eq!(r.total.value, 64, "live total wrong after a delete");
+ assert!(
+ r.hits.iter().all(|h| h.id != "weak000"),
+ "deleted doc leaked into the results"
+ );
+ assert!(
+ r.hits.iter().filter(|h| h.id == "weak001").count() <= 1,
+ "overwritten doc returned twice (stale ghost not skipped)"
+ );
+ // The five short docs are still the true top-5.
+ for (i, (id, _)) in r.hits.iter().take(5).map(|h| (&h.id, h.score)).enumerate() {
+ assert!(
+ id.starts_with("strong"),
+ "rank {i} is {id}, expected a strong doc: {:?}",
+ page(&r.hits)[..5].to_vec()
+ );
+ }
+}
diff --git a/engine/crates/xerj-engine/tests/highlight_does_not_change_ranking.rs b/engine/crates/xerj-engine/tests/highlight_does_not_change_ranking.rs
index 695a42f69..b79e25220 100644
--- a/engine/crates/xerj-engine/tests/highlight_does_not_change_ranking.rs
+++ b/engine/crates/xerj-engine/tests/highlight_does_not_change_ranking.rs
@@ -161,11 +161,23 @@ async fn highlight_block_does_not_change_multi_match_ranking() {
// top-3 is unambiguous (a tie straddling the page boundary is a different
// question — which of several equal-scoring docs to keep — and not what
// this test is about).
+ //
+ // The tf must decrease in BOTH fields, not just `body`. `multi_match`
+ // defaults to `best_fields`, i.e. the MAX over the per-field scores, and
+ // since #188 made BM25 statistics index-wide the winning field here is
+ // `title`: every one of the 44 documents has "listpack" in its body, so
+ // the body IDF collapses to ln(1 + 0.5/44.5) = 0.0112, while only the 4
+ // strong docs have it in the title (IDF = ln(10) = 2.303). A constant
+ // `"title": "listpack"` therefore gave all four strong docs the SAME
+ // 2.859662 and put a 4-way tie across the size:3 page boundary. (Before
+ // #188 the strong docs were alone in their own segment, where both fields
+ // had df == N == 4 and the longer body won the max — which is exactly the
+ // per-segment-statistics artefact #188 removed.)
for i in 0..4 {
let body = "listpack ".repeat(8 - i) + &"filler ".repeat(i * 6);
idx.index_document(
Some(format!("strong{i}")),
- json!({"title": "listpack", "body": body}),
+ json!({"title": "listpack ".repeat(4 - i), "body": body}),
)
.await
.unwrap();
diff --git a/engine/crates/xerj-engine/tests/search_bounded_under_ghosts.rs b/engine/crates/xerj-engine/tests/search_bounded_under_ghosts.rs
index 369293dae..1919b83fc 100644
--- a/engine/crates/xerj-engine/tests/search_bounded_under_ghosts.rs
+++ b/engine/crates/xerj-engine/tests/search_bounded_under_ghosts.rs
@@ -224,7 +224,10 @@ async fn page_reaching_into_truncated_ghost_segment_is_exact() {
// Ground truth: full materialisation.
let full = idx.search(&match_body(500, false)).await.unwrap();
- assert_eq!(full.total.value, expected_total, "live total wrong under ghosts");
+ assert_eq!(
+ full.total.value, expected_total,
+ "live total wrong under ghosts"
+ );
// Pages that reach well into the weak segment must equal the ground-truth
// prefix — this is the assertion the re-expand exists to satisfy.
@@ -232,7 +235,10 @@ async fn page_reaching_into_truncated_ghost_segment_is_exact() {
let mut truth = page(&full.hits);
truth.truncate(size);
let r = idx.search(&match_body(size, false)).await.unwrap();
- assert_eq!(r.total.value, expected_total, "size:{size} total drifted under ghosts");
+ assert_eq!(
+ r.total.value, expected_total,
+ "size:{size} total drifted under ghosts"
+ );
assert_eq!(
page(&r.hits),
truth,
@@ -315,12 +321,23 @@ async fn large_single_segment_with_top_ghost_returns_exact_order() {
.unwrap();
let full = idx.search(&match_body(500, false)).await.unwrap();
- assert_eq!(full.total.value, (n as u64) - 1, "live total wrong under a top ghost");
+ assert_eq!(
+ full.total.value,
+ (n as u64) - 1,
+ "live total wrong under a top ghost"
+ );
for size in [10usize, 50, 200] {
let mut truth = page(&full.hits);
truth.truncate(size);
let r = idx.search(&match_body(size, false)).await.unwrap();
- assert_eq!(page(&r.hits), truth, "size:{size} order wrong with a top-scoring ghost");
- assert!(r.hits.iter().all(|h| h.id != "weak0000"), "deleted top-scorer leaked");
+ assert_eq!(
+ page(&r.hits),
+ truth,
+ "size:{size} order wrong with a top-scoring ghost"
+ );
+ assert!(
+ r.hits.iter().all(|h| h.id != "weak0000"),
+ "deleted top-scorer leaked"
+ );
}
}
diff --git a/engine/crates/xerj-fts/src/bm25.rs b/engine/crates/xerj-fts/src/bm25.rs
index 8ad8d3773..ac5b95dd8 100644
--- a/engine/crates/xerj-fts/src/bm25.rs
+++ b/engine/crates/xerj-fts/src/bm25.rs
@@ -230,6 +230,141 @@ impl FieldStats {
}
}
+/// `FieldStats` is additive: the union of two arms' statistics is the sum of
+/// their doc counts and their total field lengths. This is what makes an
+/// index-wide [`CollectionStats`] a plain fold over the segments plus the
+/// memtable (Lucene does the same fold in `IndexSearcher.fieldStats`, summing
+/// `docCount`/`sumTotalTermFreq` over `reader.leaves()`).
+impl std::ops::AddAssign<&FieldStats> for FieldStats {
+ fn add_assign(&mut self, rhs: &FieldStats) {
+ self.total_docs += rhs.total_docs;
+ self.total_field_length += rhs.total_field_length;
+ }
+}
+
+// ── Collection stats (index-wide: every segment + the memtable) ──────────────
+
+/// Index-wide BM25 collection statistics — the union over every live scoring
+/// arm (all segments **and** the memtable), for exactly the (field, term)
+/// pairs one query needs.
+///
+/// ## Why this exists (#188)
+///
+/// BM25 is only comparable between two documents when both were scored
+/// against the *same* `N`, `avgdl` and `doc_freq`. Before this type each arm
+/// scored against its own local statistics: every segment used its own
+/// `FieldStats`, and the memtable used the union over its shards. Two
+/// consequences, both user-visible:
+///
+/// * **Overwriting a document promoted it.** An overwrite moves the live
+/// copy into the memtable; if it is the only doc there, `N = 1`,
+/// `df = 1` and `dl/avgdl = 1`, so `idf = ln(4/3) = 0.2877` and
+/// `tf_norm = 1.0` — a fixed 0.2877 that outranks almost any correctly
+/// scored segment hit, regardless of the document's real length or the
+/// corpus.
+/// * **Scores depended on segment topology.** The same corpus flushed into
+/// 1 segment vs 16 gave the same document scores differing by >3×,
+/// because `avgdl`/`N` were per-segment.
+///
+/// Feeding one `CollectionStats` to every arm makes the score a function of
+/// the index, not of where a document happens to be sitting.
+///
+/// ## Semantics
+///
+/// Statistics are **physical / ghost-inclusive** — tombstoned and superseded
+/// versions still count until a merge purges them. That matches Lucene (which
+/// counts deleted docs in `docFreq`/`docCount` until they are merged away) and
+/// the memtable's existing delete-aware aggregation.
+///
+/// `N` is the per-field *docs-with-field* count, not the index doc count —
+/// the same pairing Lucene's `BM25Similarity.idfExplain` uses
+/// (`fieldStats.docCount()` with `termStats.docFreq()`).
+#[derive(Debug, Clone, Default)]
+pub struct CollectionStats {
+ /// Per-field union over every live arm.
+ fields: std::collections::HashMap<String, FieldStats>,
+ /// Index-wide doc_freq for exactly the (field, term) pairs the query needs.
+ doc_freq: std::collections::HashMap<(String, String), u64>,
+}
+
+impl CollectionStats {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Fold one arm's `FieldStats` for `field` into the union.
+ pub fn add_field(&mut self, field: &str, stats: &FieldStats) {
+ if stats.total_docs == 0 && stats.total_field_length == 0 {
+ return;
+ }
+ match self.fields.get_mut(field) {
+ Some(acc) => *acc += stats,
+ None => {
+ self.fields.insert(field.to_owned(), stats.clone());
+ }
+ }
+ }
+
+ /// Fold one arm's doc_freq for `(field, term)` into the union.
+ pub fn add_doc_freq(&mut self, field: &str, term: &str, df: u64) {
+ if df == 0 {
+ return;
+ }
+ *self
+ .doc_freq
+ .entry((field.to_owned(), term.to_owned()))
+ .or_insert(0) += df;
+ }
+
+ /// The union `FieldStats` for `field`, if any arm indexed it.
+ pub fn field(&self, field: &str) -> Option<&FieldStats> {
+ self.fields.get(field)
+ }
+
+ /// A scorer seeded with the index-wide `avgdl` + `N` for `field`.
+ ///
+ /// `None` when no arm reported the field — callers must then fall back to
+ /// their local statistics rather than score against `N = 0` (which would
+ /// clamp every IDF to zero).
+ pub fn scorer(&self, field: &str) -> Option<Bm25Scorer> {
+ self.fields
+ .get(field)
+ .filter(|s| s.total_docs > 0)
+ .map(|s| s.to_scorer())
+ }
+
+ /// Index-wide doc_freq for `(field, term)`; `None` when the pair was not
+ /// collected (caller falls back to its local df).
+ pub fn df(&self, field: &str, term: &str) -> Option<u64> {
+ // Borrowing a `(String, String)` key without allocating needs the
+ // `Borrow` trick, which tuples don't support — this map is only ever
+ // probed a handful of times per query (once per field × query term),
+ // so the two short allocations are not worth a custom key type.
+ self.doc_freq
+ .get(&(field.to_owned(), term.to_owned()))
+ .copied()
+ }
+
+ /// True when no arm contributed anything — the caller should use its
+ /// local statistics unchanged.
+ pub fn is_empty(&self) -> bool {
+ self.fields.is_empty() && self.doc_freq.is_empty()
+ }
+
+ /// Per-field union view (used by the memtable arm, which needs `N` and
+ /// `avgdl` separately from a `Bm25Scorer`).
+ pub fn field_iter(&self) -> impl Iterator<Item = (&String, &FieldStats)> {
+ self.fields.iter()
+ }
+
+ /// The `(field, term)` pairs this instance carries a df for — lets a
+ /// caller that folded one arm's stats discover which terms that arm
+ /// analysed, so the same set can be collected from the others.
+ pub fn term_keys(&self) -> impl Iterator<Item = (&String, &String)> {
+ self.doc_freq.keys().map(|(f, t)| (f, t))
+ }
+}
+
// ── Tests ─────────────────────────────────────────────────────────────────────
#[cfg(test)]
@@ -310,4 +445,140 @@ mod tests {
};
assert_eq!(stats.avg_field_length(), 5.0);
}
+
+ // ── #188: index-wide collection statistics ───────────────────────────
+
+ #[test]
+ fn field_stats_add_assign_is_the_union() {
+ let mut a = FieldStats {
+ total_docs: 2,
+ total_field_length: 20,
+ };
+ let b = FieldStats {
+ total_docs: 3,
+ total_field_length: 60,
+ };
+ a += &b;
+ assert_eq!(a.total_docs, 5);
+ assert_eq!(a.total_field_length, 80);
+ assert_eq!(a.avg_field_length(), 16.0);
+ }
+
+ #[test]
+ fn collection_stats_folds_arms_and_answers_per_field() {
+ let mut cs = CollectionStats::new();
+ // Two "segments" and a "memtable", the shape the engine folds.
+ cs.add_field(
+ "body",
+ &FieldStats {
+ total_docs: 300,
+ total_field_length: 300_000,
+ },
+ );
+ cs.add_field(
+ "body",
+ &FieldStats {
+ total_docs: 65,
+ total_field_length: 1_300,
+ },
+ );
+ cs.add_field(
+ "body",
+ &FieldStats {
+ total_docs: 1,
+ total_field_length: 87,
+ },
+ );
+ cs.add_doc_freq("body", "quicklist", 300);
+ cs.add_doc_freq("body", "quicklist", 65);
+ cs.add_doc_freq("body", "quicklist", 1);
+
+ let fs = cs.field("body").expect("body present");
+ assert_eq!(fs.total_docs, 366);
+ assert_eq!(fs.total_field_length, 301_387);
+ assert_eq!(cs.df("body", "quicklist"), Some(366));
+ // Unknown field / term fall back to the caller's local stats.
+ assert!(cs.scorer("title").is_none());
+ assert_eq!(cs.df("body", "absent"), None);
+
+ let scorer = cs.scorer("body").expect("scorer");
+ assert_eq!(scorer.total_docs, 366);
+ assert!((scorer.avg_dl - 301_387.0 / 366.0).abs() < 0.01);
+ }
+
+ /// The single-arm identity: folding exactly ONE arm must produce a scorer
+ /// bit-identical to that arm's own `FieldStats::to_scorer()`. This is the
+ /// property the engine's single-arm gate relies on being true.
+ #[test]
+ fn collection_stats_of_one_arm_is_that_arm() {
+ let only = FieldStats {
+ total_docs: 365,
+ total_field_length: 416_960,
+ };
+ let mut cs = CollectionStats::new();
+ cs.add_field("body", &only);
+ let a = cs.scorer("body").unwrap();
+ let b = only.to_scorer();
+ assert_eq!(a.total_docs, b.total_docs);
+ assert_eq!(a.avg_dl.to_bits(), b.avg_dl.to_bits());
+ assert_eq!(a.k1.to_bits(), b.k1.to_bits());
+ assert_eq!(a.b.to_bits(), b.b.to_bits());
+ }
+
+ /// An arm that reported the field but has zero documents must not produce
+ /// a scorer: `N = 0` drives `idf` negative and the `.max(0.0)` clamp would
+ /// silently zero every score.
+ #[test]
+ fn collection_stats_declines_an_empty_field() {
+ let mut cs = CollectionStats::new();
+ cs.add_field(
+ "body",
+ &FieldStats {
+ total_docs: 0,
+ total_field_length: 0,
+ },
+ );
+ assert!(cs.scorer("body").is_none());
+ assert!(cs.is_empty());
+ }
+
+ /// The concrete #188 arithmetic: the memtable-alone statistics that made
+ /// an overwritten document jump to first place, versus the index-wide
+ /// statistics that put it back where it belongs.
+ #[test]
+ fn index_wide_stats_demote_the_lone_memtable_document() {
+ // weak001: one occurrence of the term in an 87-token field.
+ let (tf, dl) = (1u32, 87u32);
+
+ // BEFORE — memtable alone: N = 1, df = 1, avgdl = 87.
+ let lone = FieldStats {
+ total_docs: 1,
+ total_field_length: 87,
+ };
+ let before = lone.to_scorer().score_term(1, tf, dl);
+ assert!(
+ (before - 0.28768212).abs() < 1e-6,
+ "the reported failure value should reproduce exactly, got {before}"
+ );
+
+ // AFTER — index-wide: 366 physical docs, df = 366, Σ len = 417 047.
+ let union = FieldStats {
+ total_docs: 366,
+ total_field_length: 417_047,
+ };
+ let scorer = union.to_scorer();
+ let weak = scorer.score_term(366, tf, dl);
+ // strong0: 10 occurrences in a 10-token field.
+ let strong = scorer.score_term(366, 10, 10);
+ assert!(
+ strong > weak,
+ "the short, term-dense document must outrank the long, buried one \
+ (strong={strong}, weak={weak})"
+ );
+ assert!(
+ before > strong,
+ "sanity: it is precisely because the lone-memtable score ({before}) beat the \
+ correctly-scored top hit ({strong}) that an overwrite promoted the document"
+ );
+ }
}
diff --git a/engine/crates/xerj-fts/src/index.rs b/engine/crates/xerj-fts/src/index.rs
index ea6ec7e2d..0d1f21e20 100644
--- a/engine/crates/xerj-fts/src/index.rs
+++ b/engine/crates/xerj-fts/src/index.rs
@@ -930,6 +930,13 @@ pub struct FtsIndexReader {
segment_id: String,
/// Loaded per-field data
fields: HashMap<String, LoadedField>,
+ /// Set by [`FtsIndexReader::open_stats_only`]: the postings envelope and
+ /// the norms table were NOT loaded, so this reader can answer
+ /// `field_stats` / `term_doc_freq` (FST + `.meta` only) and nothing else.
+ /// `postings_data` and `field_length` fail closed (`None`) rather than
+ /// silently returning empty payloads — a stats-only reader handed to the
+ /// searcher must produce zero hits, never wrong ones.
+ stats_only: bool,
}
/// Backing storage for a field's postings bytes.
@@ -990,6 +997,40 @@ impl FtsIndexReader {
segment_dir: impl AsRef<Path>,
segment_id: impl Into<String>,
field_names: &[&str],
+ ) -> Result<Self> {
+ Self::open_inner(segment_dir, segment_id, field_names, false)
+ }
+
+ /// Open ONLY what BM25 collection statistics need: the FST term
+ /// dictionary (mmap'd) and the small `.meta` side-car.
+ ///
+ /// Skips the two expensive parts of a full [`Self::open`]:
+ ///
+ /// * the postings envelope — a whole-file `fs::read` plus a zstd
+ /// decompress of every posting list in the field, O(index bytes);
+ /// * the norms table — a whole-file `fs::read` plus decode, O(docs).
+ ///
+ /// That makes the per-segment `field_stats` + `term_doc_freq` pre-pass
+ /// the index-wide scorer needs (#188) cost one mmap and one small read
+ /// per field, instead of re-paying the full open a second time.
+ ///
+ /// The returned reader can answer [`Self::field_stats`],
+ /// [`Self::term_doc_freq`] and [`Self::lookup_term`]; [`Self::postings_data`]
+ /// and [`Self::field_length`] return `None` on it by construction, so
+ /// handing one to a searcher yields zero hits rather than wrong ones.
+ pub fn open_stats_only(
+ segment_dir: impl AsRef<Path>,
+ segment_id: impl Into<String>,
+ field_names: &[&str],
+ ) -> Result<Self> {
+ Self::open_inner(segment_dir, segment_id, field_names, true)
+ }
+
+ fn open_inner(
+ segment_dir: impl AsRef<Path>,
+ segment_id: impl Into<String>,
+ field_names: &[&str],
+ stats_only: bool,
) -> Result<Self> {
let segment_dir = segment_dir.as_ref().to_path_buf();
let segment_id = segment_id.into();
@@ -1035,8 +1076,15 @@ impl FtsIndexReader {
//
// The query path references `post_data` by slice in all
// three cases, so there's no per-query decompress cost.
- let raw_post = fs::read(&post_path)
- .with_context(|| format!("reading postings {:?}", post_path))?;
+ //
+ // STATS-ONLY: skip the read + decompress entirely — the caller
+ // only wants `field_stats`/`term_doc_freq`, both of which live
+ // in `.meta`/`.fst`.
+ let raw_post = if stats_only {
+ Vec::new()
+ } else {
+ fs::read(&post_path).with_context(|| format!("reading postings {:?}", post_path))?
+ };
let post_data = if raw_post.len() >= 8 && &raw_post[..4] == POST_MAGIC_ZSTD {
let mut len_buf = [0u8; 4];
len_buf.copy_from_slice(&raw_post[4..8]);
@@ -1111,7 +1159,13 @@ impl FtsIndexReader {
}
};
- let norms = Self::load_norms(&norms_path)?;
+ // STATS-ONLY: the norms table is a whole-file read + decode that
+ // is O(docs); the statistics pre-pass never asks for a doc length.
+ let norms = if stats_only {
+ Vec::new()
+ } else {
+ Self::load_norms(&norms_path)?
+ };
fields.insert(
field_name.to_owned(),
@@ -1128,6 +1182,7 @@ impl FtsIndexReader {
segment_dir,
segment_id,
fields,
+ stats_only,
})
}
@@ -1243,7 +1298,14 @@ impl FtsIndexReader {
}
/// Get the raw postings bytes for a term (to hand to `PostingsReader`).
+ ///
+ /// Always `None` on a [`Self::open_stats_only`] reader — it never read the
+ /// postings envelope, so a caller that got this far would otherwise decode
+ /// an empty buffer and silently see zero postings.
pub fn postings_data<'a>(&'a self, field: &str, tp: &TermPostings) -> Option<&'a [u8]> {
+ if self.stats_only {
+ return None;
+ }
let loaded = self.fields.get(field)?;
let start = tp.postings_offset as usize;
let end = start + tp.postings_length as usize;
@@ -1284,7 +1346,9 @@ impl FtsIndexReader {
}
/// Look up the field length (norm) for a specific document.
- /// Returns `None` if the document has no data for this field.
+ /// Returns `None` if the document has no data for this field — which is
+ /// every document on a [`Self::open_stats_only`] reader, whose norms
+ /// table was deliberately not loaded.
pub fn field_length(&self, field: &str, doc_id: u32) -> Option<u16> {
let loaded = self.fields.get(field)?;
// Binary search by doc_id
diff --git a/engine/crates/xerj-fts/src/lib.rs b/engine/crates/xerj-fts/src/lib.rs
index b174ed925..d37239bb3 100644
--- a/engine/crates/xerj-fts/src/lib.rs
+++ b/engine/crates/xerj-fts/src/lib.rs
@@ -70,7 +70,10 @@ pub use analyzer::{
WhitespaceTokenizer,
};
-pub use bm25::{Bm25Scorer, FieldStats, QueryExplanation, ScoreBreakdown, DEFAULT_B, DEFAULT_K1};
+pub use bm25::{
+ Bm25Scorer, CollectionStats, FieldStats, QueryExplanation, ScoreBreakdown, DEFAULT_B,
+ DEFAULT_K1,
+};
pub use index::{FieldIndexConfig, FtsIndexReader, FtsIndexWriter};
diff --git a/engine/crates/xerj-fts/src/search.rs b/engine/crates/xerj-fts/src/search.rs
index b7069bff7..22f28e6be 100644
--- a/engine/crates/xerj-fts/src/search.rs
+++ b/engine/crates/xerj-fts/src/search.rs
@@ -16,7 +16,7 @@
use crate::{
analyzer::AnalyzerRegistry,
- bm25::{Bm25Scorer, QueryExplanation, ScoreBreakdown},
+ bm25::{Bm25Scorer, CollectionStats, QueryExplanation, ScoreBreakdown},
index::FtsIndexReader,
postings::PostingsReader,
};
@@ -438,6 +438,14 @@ pub struct FtsSearcher {
/// searcher are partial. Atomic (not `Cell`) so the searcher stays
/// `Sync`.
deadline_tripped: std::sync::atomic::AtomicBool,
+ /// Index-wide BM25 statistics (#188). When set, every scorer this
+ /// searcher builds uses the union `avgdl`/`N` over ALL segments plus the
+ /// memtable, and every scoring `doc_freq` is the union df — so a
+ /// document's score no longer depends on which segment it landed in.
+ /// `None` keeps the historical per-segment statistics, which the engine
+ /// uses when the index has at most one live scoring arm (where the union
+ /// is the identity).
+ collection: Option<Arc<CollectionStats>>,
}
impl FtsSearcher {
@@ -447,6 +455,7 @@ impl FtsSearcher {
registry,
deadline: None,
deadline_tripped: std::sync::atomic::AtomicBool::new(false),
+ collection: None,
}
}
@@ -456,6 +465,13 @@ impl FtsSearcher {
self
}
+ /// Builder: score against index-wide collection statistics instead of
+ /// this segment's own (#188). `None` (default) keeps per-segment stats.
+ pub fn with_collection_stats(mut self, stats: Option<Arc<CollectionStats>>) -> Self {
+ self.collection = stats;
+ self
+ }
+
/// True when any expansion loop stopped early because the deadline
/// passed — the hits/totals produced by this searcher are partial.
pub fn deadline_tripped(&self) -> bool {
@@ -600,6 +616,11 @@ impl FtsSearcher {
};
let scorer = self.make_scorer(&tq.field);
+ // IDF df: index-wide when the engine supplied collection stats (#188).
+ // `tp.doc_frequency` below stays LOCAL — it is the postings-decode
+ // length for this segment's list, a different quantity that happens to
+ // share a name.
+ let score_df = self.scoring_df(&tq.field, &tq.term, tp.doc_frequency as u64);
let post_data = match self.reader.postings_data(&tq.field, &tp) {
Some(d) => d,
None => return Ok(()),
@@ -616,18 +637,12 @@ impl FtsSearcher {
.unwrap_or(1) as u32;
let (score, explanation) = if explain {
- let bd = scorer.score_term_explain(
- &tq.term,
- tp.doc_frequency as u64,
- posting.term_freq,
- doc_len,
- );
+ let bd = scorer.score_term_explain(&tq.term, score_df, posting.term_freq, doc_len);
let s = bd.score * tq.boost;
let boosted_bd = ScoreBreakdown { score: s, ..bd };
(s, Some(QueryExplanation::new(vec![boosted_bd])))
} else {
- let s = scorer.score_term(tp.doc_frequency as u64, posting.term_freq, doc_len)
- * tq.boost;
+ let s = scorer.score_term(score_df, posting.term_freq, doc_len) * tq.boost;
(s, None)
};
@@ -696,6 +711,14 @@ impl FtsSearcher {
.unwrap_or(0);
let scorer = self.make_scorer(&pq.field);
+ // Per-term IDF df, index-wide when available (#188). `term_maps[i].1`
+ // remains the segment-local postings length used to size the decode.
+ let score_dfs: Vec<u64> = pq
+ .terms
+ .iter()
+ .enumerate()
+ .map(|(i, term)| self.scoring_df(&pq.field, term, term_maps[i].1 as u64))
+ .collect();
let mut hits = Vec::new();
'doc: for &doc_id in term_maps[min_idx].0.keys() {
@@ -717,14 +740,15 @@ impl FtsSearcher {
let mut total_score = 0.0f32;
let mut breakdowns = Vec::new();
for (term_idx, term) in pq.terms.iter().enumerate() {
- let (map, df) = &term_maps[term_idx];
+ let (map, _local_df) = &term_maps[term_idx];
+ let df = score_dfs[term_idx];
let tf = map.get(&doc_id).map(|(f, _)| *f).unwrap_or(1);
if explain {
- let bd = scorer.score_term_explain(term, *df as u64, tf, doc_len);
+ let bd = scorer.score_term_explain(term, df, tf, doc_len);
total_score += bd.score;
breakdowns.push(bd);
} else {
- total_score += scorer.score_term(*df as u64, tf, doc_len);
+ total_score += scorer.score_term(df, tf, doc_len);
}
}
total_score *= pq.boost;
@@ -1211,12 +1235,33 @@ impl FtsSearcher {
// ── Helpers ───────────────────────────────────────────────────────────────
+ /// The scorer for `field`: index-wide statistics when the engine supplied
+ /// them (#188), else this segment's own — the historical behaviour, kept
+ /// as the fallback for direct `xerj-fts` users and for fields the union
+ /// never saw.
fn make_scorer(&self, field: &str) -> Bm25Scorer {
+ if let Some(scorer) = self.collection.as_ref().and_then(|c| c.scorer(field)) {
+ return scorer;
+ }
self.reader
.field_stats(field)
.map(|stats| stats.to_scorer())
.unwrap_or_else(|| Bm25Scorer::new(1.0, 1))
}
+
+ /// The `doc_freq` to FEED THE SCORER for `(field, term)`.
+ ///
+ /// NOT interchangeable with the segment-local `TermPostings::doc_frequency`
+ /// used to size a `PostingsReader` — that one is the number of postings to
+ /// decode from THIS segment's list and must stay local. Only the IDF
+ /// argument becomes index-wide.
+ #[inline]
+ fn scoring_df(&self, field: &str, term: &str, local: u64) -> u64 {
+ self.collection
+ .as_ref()
+ .and_then(|c| c.df(field, term))
+ .unwrap_or(local)
+ }
}
// ── Wildcard / fuzzy term-matching predicates ─────────────────────────────────