Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(engine): #834 memtable dis_max scores subs through the real per-field BM25 path (#869)

Onyeka Obi318e43604179
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index c0d2e89a9..c27b81ac1 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -16556,6 +16556,39 @@ impl Index {
let extra = total.saturating_sub(ids.len() as u64);
MemSnapshot::AllDocIds(ids, extra)
}
+ } else if let Some((dm_subs, dm_tie)) = dis_max_mem_fts_subs(query) {
+ // #834: a `dis_max` of single-field text `match` subs used
+ // to fall through to the stored-doc scan, whose scorer has
+ // no DisMax arm — every buffered match took the flat-1.0
+ // catch-all, so a doc matching MORE disjuncts tied with
+ // single-disjunct docs and the ranking changed at flush.
+ // Score each sub through the SAME memtable BM25 path a
+ // standalone `match` takes and combine per doc as
+ // max + tie_breaker·Σ(rest), mirroring the segment's
+ // `execute_dis_max`. GHOST WINDOW: same complete-hit-list
+ // widening as the single-`Match` arm below — the consume
+ // arm's liveness filter needs every hit.
+ let mem_limit = if self.store.version_map.ghost_events() > 0 {
+ usize::MAX
+ } else {
+ fetch_limit
+ };
+ let mem_stats = collection_stats();
+ let (hits, mem_total) = mem.search_dis_max_boosted_with_total_using(
+ &dm_subs,
+ dm_tie,
+ mem_limit,
+ mem_stats.as_deref(),
+ );
+ if hits.is_empty() {
+ MemSnapshot::Empty
+ } else {
+ let uncollected = mem_total.saturating_sub(hits.len() as u64);
+ MemSnapshot::FtsHits(
+ hits.into_iter().map(|h| (h.doc_id, h.score)).collect(),
+ uncollected,
+ )
+ }
} else if is_doc_scan_query(query) {
// count_only + Term/Range short-circuits BEFORE
// `try_doc_values_query` because the DV-term path walks
@@ -36625,6 +36658,49 @@ fn extract_query_text(q: &QueryNode) -> Option<String> {
}
}
+/// The per-sub `(field, query, boost)` triples and the `tie_breaker` of a
+/// `dis_max` whose EVERY sub is a single-field `Match` the memtable BM25
+/// path can score — the same shapes the standalone-`Match` FTS arm serves,
+/// minus the carve-outs `is_doc_scan_query` routes to the doc-scan
+/// (wildcard field, `operator: and`, `minimum_should_match`, date-shaped
+/// query text). Any other sub shape answers `None` so the query keeps its
+/// existing doc-scan route — in particular the keyword-rewrite
+/// `DisMax{[Term, MultiMatch]}` shape (#572) stays untouched: those subs
+/// score through paths this arm cannot reproduce, and changing only the
+/// combine step would move that query's score without moving its
+/// standalone sub scores.
+fn dis_max_mem_fts_subs(q: &QueryNode) -> Option<(Vec<(&str, &str, f32)>, f32)> {
+ match q {
+ QueryNode::DisMax {
+ queries,
+ tie_breaker,
+ } if !queries.is_empty() => queries
+ .iter()
+ .map(|sub| match sub {
+ QueryNode::Match {
+ field,
+ query,
+ operator,
+ minimum_should_match,
+ boost,
+ ..
+ } if field != "*"
+ && !field.ends_with('*')
+ && !matches!(operator, xerj_query::ast::BoolOperator::And)
+ && minimum_should_match.is_none()
+ && !(crate::aggs::parse_date_ms(&Value::String(query.clone())).is_some()
+ && query.chars().any(|c| c == '-' || c == '/' || c == 'T')) =>
+ {
+ Some((field.as_str(), query.as_str(), boost.unwrap_or(1.0)))
+ }
+ _ => None,
+ })
+ .collect::<Option<Vec<_>>>()
+ .map(|subs| (subs, *tie_breaker)),
+ _ => None,
+ }
+}
+
/// Erase `bool` wrappers whose only clause is a single SCORING clause.
///
/// `{"bool":{"must":[X]}}` and bare `X` are the same query and ES gives them
diff --git a/engine/crates/xerj-engine/src/memtable.rs b/engine/crates/xerj-engine/src/memtable.rs
index a72e52802..b692635f1 100644
--- a/engine/crates/xerj-engine/src/memtable.rs
+++ b/engine/crates/xerj-engine/src/memtable.rs
@@ -1236,6 +1236,64 @@ impl ShardedFtsMemtable {
self.search_text_boosted_inner(query, fields, limit, usize::MAX, field_boosts, stats)
}
+ /// `dis_max` over single-field text subs, each scored through the SAME
+ /// per-field BM25 path a standalone `match` takes (#834): every
+ /// `(field, query, boost)` sub runs UNCAPPED (a doc outside one sub's
+ /// page can still win the max via another sub, and a capped sub list
+ /// would silently drop its contribution), the per-doc scores combine as
+ /// `max + tie_breaker × (Σ − max)` — mirroring the segment's
+ /// `FtsSearcher::execute_dis_max` — and only the COMBINED result is
+ /// page-key sorted and truncated to `limit`. A doc lives in exactly
+ /// one shard, so its `seq_no` is identical across subs and the first
+ /// contributing sub's value is authoritative.
+ pub fn search_dis_max_boosted_with_total_using(
+ &self,
+ subs: &[(&str, &str, f32)],
+ tie_breaker: f32,
+ limit: usize,
+ stats: Option<&xerj_fts::CollectionStats>,
+ ) -> (Vec<MemtableHit>, u64) {
+ // Per-doc (max, sum, seq_no) accumulator over sub scores — the same
+ // f32 (max, sum) pair `execute_dis_max` keeps.
+ let acc: std::collections::HashMap<String, (f32, f32, u64)> = subs.iter().fold(
+ std::collections::HashMap::new(),
+ |acc, &(field, query, boost)| {
+ let boosts: std::collections::HashMap<String, f32> =
+ std::iter::once((field.to_string(), boost)).collect();
+ let (hits, _) = self.search_text_boosted_inner(
+ query,
+ &[field],
+ usize::MAX,
+ usize::MAX,
+ &boosts,
+ stats,
+ );
+ hits.into_iter().fold(acc, |mut acc, h| {
+ let e = acc
+ .entry(h.doc_id)
+ .or_insert((f32::NEG_INFINITY, 0.0, h.seq_no));
+ if h.score > e.0 {
+ e.0 = h.score;
+ }
+ e.1 += h.score;
+ acc
+ })
+ },
+ );
+ let mut all: Vec<MemtableHit> = acc
+ .into_iter()
+ .map(|(doc_id, (max, sum, seq_no))| MemtableHit {
+ doc_id,
+ score: max + tie_breaker * (sum - max),
+ seq_no,
+ })
+ .collect();
+ sort_hits_by_page_key(&mut all);
+ let total = all.len() as u64;
+ all.truncate(limit);
+ (all, total)
+ }
+
/// 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`
diff --git a/engine/crates/xerj-engine/tests/dis_max_memtable_scoring.rs b/engine/crates/xerj-engine/tests/dis_max_memtable_scoring.rs
new file mode 100644
index 000000000..752ead23e
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/dis_max_memtable_scoring.rs
@@ -0,0 +1,203 @@
+//! Issue #834: `dis_max` scored every buffered match a flat 1.0 on the
+//! memtable — the stored-doc scorer had no DisMax arm, so its catch-all
+//! fired — while the segment path applies the real
+//! `max(sub_scores) + tie_breaker × Σ(rest)` combination. A doc matching
+//! MORE disjuncts (which must rank highest) tied with single-disjunct
+//! docs pre-flush, and the ranking changed at `_flush`.
+//!
+//! The fix scores each single-field `match` sub through the SAME memtable
+//! BM25 path a standalone `match` takes (`search_text_boosted`, per
+//! (field, query) sub) and combines per doc exactly like the segment's
+//! `execute_dis_max`. These tests pin both properties in BOTH phases:
+//!
+//! * the two-disjunct doc ranks strictly first;
+//! * per doc, the `dis_max` score equals
+//! `max + tie_breaker × (Σ − max)` over the scores the SAME standalone
+//! sub-queries return in the SAME phase — the invariant that kept the
+//! reverted stored-doc-scorer attempt (PR #835) out (#572: sub scores
+//! inside the compound must equal the standalone sub scores).
+//!
+//! Elasticsearch is referenced for wire semantics only; no ES code is here.
+
+use serde_json::{json, Value};
+use std::collections::BTreeSet;
+use tempfile::TempDir;
+use xerj_common::config::Config;
+use xerj_common::types::{FieldConfig, FieldType, Schema};
+use xerj_engine::{Engine, Index};
+use xerj_query::parse_request;
+
+fn make_engine(dir: &TempDir) -> Engine {
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ Engine::new(config).expect("engine::new")
+}
+
+fn req(q: Value) -> xerj_query::ast::SearchRequest {
+ parse_request(&json!({ "query": q, "size": 50 })).expect("parse_request")
+}
+
+/// Score of `id` under `q`, or 0.0 when the doc is not a hit — the
+/// contribution a non-matching `dis_max` sub makes.
+async fn score_or_zero(idx: &Index, q: &Value, id: &str) -> f32 {
+ idx.search(&req(q.clone()))
+ .await
+ .unwrap()
+ .hits
+ .iter()
+ .find(|h| h.id == id)
+ .map(|h| h.score)
+ .unwrap_or(0.0)
+}
+
+async fn hit_ids(idx: &Index, q: &Value) -> BTreeSet<String> {
+ idx.search(&req(q.clone()))
+ .await
+ .unwrap()
+ .hits
+ .iter()
+ .map(|h| h.id.clone())
+ .collect()
+}
+
+fn expect(ids: &[&str]) -> BTreeSet<String> {
+ ids.iter().map(|s| s.to_string()).collect()
+}
+
+/// Per-doc dis_max contract: the compound's score equals
+/// `max + tie·(Σ − max)` over the SAME standalone sub scores.
+async fn assert_dis_max_contract(
+ idx: &Index,
+ dm: &Value,
+ sub_x: &Value,
+ sub_y: &Value,
+ tie: f32,
+ id: &str,
+ phase: &str,
+) {
+ let s_dm = score_or_zero(idx, dm, id).await;
+ let s_x = score_or_zero(idx, sub_x, id).await;
+ let s_y = score_or_zero(idx, sub_y, id).await;
+ let max = s_x.max(s_y);
+ let want = max + tie * (s_x + s_y - max);
+ assert!(
+ (s_dm - want).abs() < 1e-4,
+ "{phase}: dis_max({id}) = {s_dm}, want max + tie·(Σ−max) = \
+ {want} from standalone subs x={s_x} y={s_y} (#834)"
+ );
+}
+
+async fn assert_phase(
+ idx: &Index,
+ dm: &Value,
+ sub_x: &Value,
+ sub_y: &Value,
+ tie: f32,
+ phase: &str,
+) {
+ let res = idx.search(&req(dm.clone())).await.unwrap();
+ let ids: BTreeSet<String> = res.hits.iter().map(|h| h.id.clone()).collect();
+ assert_eq!(
+ ids,
+ expect(&["a", "b", "ab"]),
+ "{phase}: docs matching ANY disjunct are hits (#834)"
+ );
+ assert_eq!(
+ res.hits.first().map(|h| h.id.as_str()),
+ Some("ab"),
+ "{phase}: the two-disjunct doc must rank first (#834)"
+ );
+
+ assert_dis_max_contract(idx, dm, sub_x, sub_y, tie, "a", phase).await;
+ assert_dis_max_contract(idx, dm, sub_x, sub_y, tie, "b", phase).await;
+ assert_dis_max_contract(idx, dm, sub_x, sub_y, tie, "ab", phase).await;
+
+ let s_ab = score_or_zero(idx, dm, "ab").await;
+ let s_a = score_or_zero(idx, dm, "a").await;
+ let s_b = score_or_zero(idx, dm, "b").await;
+ assert!(
+ s_ab > s_a + 1e-4 && s_ab > s_b + 1e-4,
+ "{phase}: ab={s_ab} must score strictly above a={s_a} and b={s_b} (#834)"
+ );
+}
+
+#[tokio::test]
+async fn dis_max_ranks_multi_disjunct_doc_first_and_combines_like_the_segment() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+
+ let mut schema = Schema::empty();
+ schema.fields.push(FieldConfig::new("x", FieldType::Text));
+ schema.fields.push(FieldConfig::new("y", FieldType::Text));
+ engine.create_index("dmscore", schema).unwrap();
+ let idx = engine.get_index("dmscore").unwrap();
+
+ // `a` matches only the x-disjunct, `b` only the y-disjunct, `ab` both —
+ // so `ab` must score max + tie_breaker·min and rank strictly first.
+ idx.index_document(Some("a".into()), json!({ "x": "quick", "y": "other" }))
+ .await
+ .unwrap();
+ idx.index_document(Some("b".into()), json!({ "x": "other", "y": "quick" }))
+ .await
+ .unwrap();
+ idx.index_document(Some("ab".into()), json!({ "x": "quick", "y": "quick" }))
+ .await
+ .unwrap();
+
+ let tie = 0.3_f32;
+ let dm = json!({ "dis_max": {
+ "queries": [ { "match": { "x": "quick" } }, { "match": { "y": "quick" } } ],
+ "tie_breaker": tie,
+ }});
+ let sub_x = json!({ "match": { "x": "quick" } });
+ let sub_y = json!({ "match": { "y": "quick" } });
+
+ assert_phase(&idx, &dm, &sub_x, &sub_y, tie, "pre-flush").await;
+ idx.flush().await.unwrap();
+ assert_phase(&idx, &dm, &sub_x, &sub_y, tie, "post-flush").await;
+}
+
+/// A `dis_max` with a sub the memtable BM25 path cannot score (here a
+/// `term`) must keep its existing doc-scan route unchanged — the #572
+/// keyword-rewrite shape `DisMax{[Term, MultiMatch]}` depends on it. The
+/// hit SET (docs matching any disjunct) is asserted in both phases.
+#[tokio::test]
+async fn dis_max_with_non_match_sub_keeps_its_hit_set() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+
+ let mut schema = Schema::empty();
+ schema
+ .fields
+ .push(FieldConfig::new("tag", FieldType::Keyword));
+ schema.fields.push(FieldConfig::new("y", FieldType::Text));
+ engine.create_index("dmmixed", schema).unwrap();
+ let idx = engine.get_index("dmmixed").unwrap();
+
+ idx.index_document(Some("t".into()), json!({ "tag": "vip", "y": "other" }))
+ .await
+ .unwrap();
+ idx.index_document(Some("m".into()), json!({ "tag": "guest", "y": "quick" }))
+ .await
+ .unwrap();
+ idx.index_document(Some("n".into()), json!({ "tag": "guest", "y": "other" }))
+ .await
+ .unwrap();
+
+ let dm = json!({ "dis_max": {
+ "queries": [ { "term": { "tag": "vip" } }, { "match": { "y": "quick" } } ],
+ "tie_breaker": 0.5,
+ }});
+
+ assert_eq!(
+ hit_ids(&idx, &dm).await,
+ expect(&["t", "m"]),
+ "pre-flush: mixed-sub dis_max hit set (#834 scope gate)"
+ );
+ idx.flush().await.unwrap();
+ assert_eq!(
+ hit_ids(&idx, &dm).await,
+ expect(&["t", "m"]),
+ "post-flush: mixed-sub dis_max hit set (#834 scope gate)"
+ );
+}