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
fix(search): tied scores — constant_score pages a mixed corpus like match_all, and every re-sort uses the one page-order key (fixes #270)
xerj-org3839ba1fa09a
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex c4462fe25..77b02dbab 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -11873,6 +11873,38 @@ impl Index {(kept, worst)}+ /// Sort `hits` into the ONE total order every score-ranked page uses:+ /// `score DESC, seq_no ASC (arrival — ES `_doc`), _id ASC`. Decorates+ /// with the resolved `seq_no` once, sorts, undecorates — same shape as+ /// the main page sort (a per-comparison `VersionMap` lookup was ~6% of a+ /// `term` page in the P1 profile).+ ///+ /// #270 — five post-sort re-sorts (the bool-text IDF rescore, the TF-IDF+ /// fallback, and the three `request.rescore` sorts) used to tie by `_id`+ /// ALONE, so any of them firing on a tied hit set silently reordered the+ /// page into `_id` ASC — for UUID-shaped ids exactly the "essentially+ /// random" ordering the main sort's `seq_no` tie-break replaced. The+ /// peer engines keep ONE comparator through collection, merge and final+ /// sort (Lucene `HitQueue.java:76-82`; tantivy+ /// `collector/sort_key/sort_by_score.rs:105-109` heap entry vs `:187`+ /// final sort, same key; quickwit `quickwit-search/src/collector.rs:+ /// 1131-1156` ties by `GlobalDocAddress` in both comparators) — every+ /// score re-sort routes through here so they cannot drift again.+ fn sort_hits_page_order(&self, hits: &mut Vec<Hit>) {+ let mut decorated: Vec<(u64, Hit)> = std::mem::take(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))+ });+ *hits = decorated.into_iter().map(|(_, h)| h).collect();+ }+/// Look up the latest `seq_no` for a document by id via the version/// map. Returns `None` when the doc is unknown or tombstoned.///@@ -14359,6 +14391,34 @@ impl Index {// Anything more complex (Bool, Range, Match) currently returns// `None` — `Range` will be shortcut-able once G3 (BKD) lands.let is_match_all = matches!(query, QueryNode::MatchAll);+ // #270 — a top-level `constant_score`/`boosted` chain over+ // `match_all` matches exactly the documents `match_all` matches, but+ // the raw flag above left it with `count_authoritative == false` (no+ // `try_shortcut_count` arm resolves a bare MatchAll — MatchAll totals+ // are handled by the flag, which the wrapper defeated). The scan+ // then ran in exact-counting mode: it TALLIES past a full collector+ // but never materialises into it, so with the memtable walked first+ // the bounded page was all memtable documents (`size:1` →+ // `mem0000` where the full page starts `seg0000`) even though the+ // segment documents hold the lowest `seq_no`s and own the head of+ // the page. This flag widens ONLY the count/bounds decisions+ // (`count_authoritative`, the final `live_doc_count()` total+ // overwrite) so wrapped match_all takes the same bounded-scan ++ // cross-segment re-merge path as bare match_all. SCORING keeps the+ // raw flag: wrapper hits still go through `score_doc`, and a+ // top-level `Constant`'s scores are overwritten with the wrapper+ // boost before the page sort regardless.+ let is_match_all_effective = is_match_all || {+ let mut q = query;+ loop {+ match q {+ QueryNode::Constant { query, .. } | QueryNode::Boosted { query, .. } => {+ q = query+ }+ other => break matches!(other, QueryNode::MatchAll),+ }+ }+ };// For MatchAll we now skip the memtable iteration entirely at// `MemSnapshot` time (it was cloning 200 k doc_ids just to tick a@@ -14718,7 +14778,7 @@ impl Index {// pre-F1 scan time — correctness over speed until the shortcut// itself is made delete-aware. (`deletes_present` hoisted above.)let count_authoritative: bool = !query_needs_fts- && (is_match_all || (shortcut_count.is_some() && !deletes_present));+ && (is_match_all_effective || (shortcut_count.is_some() && !deletes_present));// Whether a Regexp query's field is keyword-typed — gates the// FST term-dictionary route of the regexp pre-filter (computed@@ -16251,23 +16311,7 @@ impl Index {hit.score = *score;}}- // Precompute seq_no ONCE per hit, not once per comparison. The- // former `seq(&a.id)`/`seq(&b.id)` closure did a `VersionMap`- // dashmap string-hash get inside the comparator — O(n log n) gets- // per page sort (~6% of a `term` page in the P1 profile). Decorate- // with the resolved seq_no, then sort on the plain u64.- let mut decorated: Vec<(u64, Hit)> = std::mem::take(&mut final_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))- });- final_hits = decorated.into_iter().map(|(_, h)| h).collect();+ self.sort_hits_page_order(&mut final_hits);}// --- IDF-weighted rescore for Bool queries with multiple terms ---@@ -16322,13 +16366,9 @@ impl Index {hit.score = score;}}- // Re-sort by the new scores.- final_hits.sort_by(|a, b| {- b.score- .partial_cmp(&a.score)- .unwrap_or(std::cmp::Ordering::Equal)- .then_with(|| a.id.cmp(&b.id))- });+ // Re-sort by the new scores (#270 — full page-order key, so+ // hits the rescore left tied keep arrival order).+ self.sort_hits_page_order(&mut final_hits);}}@@ -16387,13 +16427,10 @@ impl Index {for (hit, score) in final_hits.iter_mut().zip(new_scores) {hit.score = score;}- // Re-sort with new TF-IDF scores.- final_hits.sort_by(|a, b| {- b.score- .partial_cmp(&a.score)- .unwrap_or(std::cmp::Ordering::Equal)- .then_with(|| a.id.cmp(&b.id))- });+ // Re-sort with new TF-IDF scores (#270 — full page-order+ // key; on ~640 identical docs every fallback score is+ // exactly 1.0, and an `_id` tie-break inverted the page).+ self.sort_hits_page_order(&mut final_hits);}}}@@ -16419,13 +16456,11 @@ impl Index {// For each rescore stage, re-score the top window_size hits using the secondary query.// Final score = original_score * query_weight + rescore_score * rescore_query_weightif !request.rescore.is_empty() {- // Sort by score before applying rescore so we work on the correct top-N.- final_hits.sort_by(|a, b| {- b.score- .partial_cmp(&a.score)- .unwrap_or(std::cmp::Ordering::Equal)- .then_with(|| a.id.cmp(&b.id))- });+ // Sort by score before applying rescore so we work on the correct+ // top-N (#270 — full page-order key at every stage, so the+ // window selection and any hits a stage leaves tied both follow+ // arrival order rather than `_id`).+ self.sort_hits_page_order(&mut final_hits);for rescore_stage in &request.rescore {apply_rescore(&mut final_hits, rescore_stage);@@ -16433,21 +16468,11 @@ impl Index {// next stage's `window_size` applies to the top-N// of the just-rescored order, not the pre-rescore// BM25 order.- final_hits.sort_by(|a, b| {- b.score- .partial_cmp(&a.score)- .unwrap_or(std::cmp::Ordering::Equal)- .then_with(|| a.id.cmp(&b.id))- });+ self.sort_hits_page_order(&mut final_hits);}// Re-sort after rescoring.- final_hits.sort_by(|a, b| {- b.score- .partial_cmp(&a.score)- .unwrap_or(std::cmp::Ordering::Equal)- .then_with(|| a.id.cmp(&b.id))- });+ self.sort_hits_page_order(&mut final_hits);}// --- match_all total = authoritative live doc count ---@@ -16456,7 +16481,10 @@ impl Index {// an UPDATE would inflate hits.total. For an unfiltered match_all the// true total is the live doc count (one entry per `_id`). min_score// below still adjusts from this corrected base if present.- if is_match_all {+ // `_effective` (#270): a wrapped match_all now scans in bounded+ // `count_authoritative` mode, so its tally is partial and needs this+ // same overwrite.+ if is_match_all_effective {total_count = self.live_doc_count();} else if !count_only&& !query_needs_ftsdiff --git a/engine/crates/xerj-engine/tests/tied_score_page_order.rs b/engine/crates/xerj-engine/tests/tied_score_page_order.rsindex 6101dd730..92bf1d850 100644--- a/engine/crates/xerj-engine/tests/tied_score_page_order.rs+++ b/engine/crates/xerj-engine/tests/tied_score_page_order.rs@@ -234,15 +234,18 @@ async fn tie_straddling_a_page_boundary_resolves_the_same_way_at_every_size() {/// became. Measured on this fixture at the pre-repair commit, `size` 60, 100/// and 150 each returned a non-prefix page for all three shapes below.///-/// `constant_score` is deliberately NOT one of the shapes here, and that is a-/// known gap rather than an oversight: on a MIXED corpus its bounded page-/// contains only memtable documents (`size:1` returns `mem0000` where the full-/// page starts `seg0000`) because the segment walk is skipped once the-/// collector is already full. That reproduces identically before and after-/// this change — it is a separate, pre-existing defect in the segment-side-/// early-out, not the memtable bound under test here — and it is why this PR-/// says `Refs #191` rather than `Fixes #191`. The memtable-only test below-/// does cover `constant_score`, which is the path this change fixes.+/// `constant_score` was originally NOT one of the shapes here: on a MIXED+/// corpus its bounded page contained only memtable documents (`size:1`+/// returned `mem000` where the full page starts `seg0000`) — the+/// segment-side counterpart (#270) of the memtable bound this test was+/// written for. The wrapper defeated the `is_match_all` flag, no+/// `try_shortcut_count` arm resolves a bare MatchAll, so the scan ran with+/// `count_authoritative == false`: it tallied segment matches past the full+/// collector but never materialised them, and the memtable (walked first)+/// owned the whole page. Asserted since `is_match_all_effective` peels+/// `constant_score`/`boosted` chains for the count/bounds decisions, putting+/// the wrapped query on the same bounded-scan + cross-segment re-merge path+/// as bare `match_all`.#[tokio::test]async fn tied_scores_page_the_same_way_with_an_unflushed_memtable() {let dir = TempDir::new().unwrap();@@ -283,6 +286,10 @@ async fn tied_scores_page_the_same_way_with_an_unflushed_memtable() {("match", json!({"match": {"body": "listpack"}})),("term", json!({"term": {"kind": "same"}})),("match_all", json!({"match_all": {}})),+ (+ "constant_score",+ json!({"constant_score": {"filter": {"match_all": {}}}}),+ ),] {let full = idx.search(&req(0, 1000, &q)).await.unwrap();let full_ids = page_ids(&full.hits);diff --git a/engine/crates/xerj-engine/tests/tied_score_resorts.rs b/engine/crates/xerj-engine/tests/tied_score_resorts.rsnew file mode 100644index 000000000..45c9b8ae5--- /dev/null+++ b/engine/crates/xerj-engine/tests/tied_score_resorts.rs@@ -0,0 +1,202 @@+//! Regression tests for #270 (part 2) — every post-sort re-sort in+//! `Index::search` must break score ties with the SAME total order as the+//! main page sort: `(score DESC, seq_no ASC, _id ASC)`.+//!+//! The main sort decorates each hit with its `seq_no` (arrival order — the+//! `_doc` analogue, see `HitQueue.lessThan` breaking equal scores by the+//! smaller doc id in `lucene/core/src/java/org/apache/lucene/search/+//! HitQueue.java:76-82`) so an all-tied page comes back in arrival order.+//! Five later re-sorts used to tie by `_id` ALONE — the IDF-weighted rescore+//! for bool-text queries, the TF-IDF fallback for near-zero BM25 scores, and+//! three in the `request.rescore` path — so any of them firing on a tied hit+//! set silently reordered the page into `_id` ASC, which for UUID-shaped ids+//! is exactly the "essentially random" ordering the main sort comment says+//! was replaced.+//!+//! The fixtures below make the misordering visible with readable ids: the+//! flushed documents are named `seg…` and the unflushed ones `mem…`, so `_id`+//! ASC ("m" < "s") puts every LATER memtable document ahead of every segment+//! document — the exact inversion measured in #270 (`mem0000…mem0599` before+//! `seg0000…seg0039`).++use serde_json::{json, Value};+use tempfile::TempDir;+use xerj_common::config::Config;+use xerj_common::types::Schema;+use xerj_engine::Engine;+use xerj_query::ast::{RescoreQuery, RescoreQueryInner};+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(from: usize, size: usize, q: &Value) -> xerj_query::ast::SearchRequest {+ parse_request(&json!({"from": from, "size": size, "query": q})).expect("parse_request")+}++fn page_ids(hits: &[xerj_query::Hit]) -> Vec<String> {+ hits.iter().map(|h| h.id.clone()).collect()+}++/// `flushed` byte-identical documents flushed to segments, then `unflushed`+/// more left in the memtable. Segment ids sort AFTER memtable ids in `_id`+/// order but arrived first, so any `_id`-only tie-break inverts the page.+async fn mixed_corpus(+ idx: &std::sync::Arc<xerj_engine::index::Index>,+ flushed: usize,+ unflushed: usize,+) -> Vec<String> {+ let mut inserted = Vec::new();+ for i in 0..flushed {+ let id = format!("seg{i:04}");+ idx.index_document(+ Some(id.clone()),+ json!({"body": "listpack encoding", "kind": "same"}),+ )+ .await+ .unwrap();+ inserted.push(id);+ }+ idx.flush().await.unwrap();+ for i in 0..unflushed {+ let id = format!("mem{i:04}");+ idx.index_document(+ Some(id.clone()),+ json!({"body": "listpack encoding", "kind": "same"}),+ )+ .await+ .unwrap();+ inserted.push(id);+ }+ inserted+}++fn assert_tied_and_in_arrival_order(+ label: &str,+ hits: &[xerj_query::Hit],+ inserted: &[String],+ total: u64,+ reported_total: u64,+) {+ assert_eq!(reported_total, total, "{label}: every doc matches");+ let scores: Vec<f32> = hits.iter().map(|h| h.score).collect();+ assert!(+ scores.windows(2).all(|w| w[0].to_bits() == w[1].to_bits()),+ "{label}: fixture must produce an EXACT tie, got {:?}…",+ &scores[..scores.len().min(5)]+ );+ assert_eq!(+ page_ids(hits),+ inserted,+ "{label}: an all-tied page must come back in arrival order \+ (segment documents before the later memtable ones), not `_id` ASC"+ );+}++/// #270's own reproduction: 40 flushed + 600 unflushed identical documents,+/// plain `match`. With ~640 identical documents the BM25 IDF collapses to+/// `ln(1 + 0.5/(N+0.5))` ≈ 0.0008, the max page score drops under the 0.001+/// threshold, and the TF-IDF fallback fires — its recomputed score is+/// `tf.sqrt() * (1 + ln(N/df))` = exactly 1.0 for identical docs (the+/// measured bit pattern 1065353216), and its re-sort used to tie by `_id`+/// alone, returning `mem0000…mem0599` before `seg0000…seg0039`.+#[tokio::test]+async fn tfidf_fallback_resort_keeps_arrival_order() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("tfidf", Schema::empty()).unwrap();+ let idx = engine.get_index("tfidf").unwrap();+ let inserted = mixed_corpus(&idx, 40, 600).await;++ let q = json!({"match": {"body": "listpack"}});+ let full = idx.search(&req(0, 1000, &q)).await.unwrap();+ assert_tied_and_in_arrival_order("match/tfidf", &full.hits, &inserted, 640, full.total.value);++ // Bounded pages must stay prefixes of the full page through the re-sort.+ for size in [1usize, 5, 41, 100] {+ let p = idx.search(&req(0, size, &q)).await.unwrap();+ assert_eq!(+ page_ids(&p.hits),+ inserted[..size],+ "match/tfidf: size:{size} page disagrees with the full materialisation"+ );+ }+}++/// The IDF-weighted rescore for bool-text queries (a Bool with ≥2 text+/// clauses). On identical documents every clause has df == N, the rescored+/// score is uniform, and the pass's re-sort used to tie by `_id` alone. The+/// corpus stays SMALL enough (340 docs → rescored score ≈ 0.005 > 0.001)+/// that the TF-IDF fallback does not also fire — this isolates the bool-text+/// re-sort.+///+/// Only the FULL materialisation is asserted, and that is a known residual+/// rather than an oversight: bounded pages for a multi-clause bool on a+/// MIXED corpus are selected under the FIRST-PASS scores, where the+/// memtable's uniform tf-sum (no IDF — the divergence this rescore pass+/// exists to repair, see the comment above the pass) does not equal the+/// segment BM25 score, so segment documents lose ADMISSION before the+/// rescore ever ties them. That is a first-pass scoring divergence between+/// the memtable and segment scorers (#188's remit), not the `_id`-only+/// tie-break #270 is about — admission runs before any re-sort, so no+/// re-sort change can affect it — and it needs a scoring fix, not a sort+/// fix.+#[tokio::test]+async fn bool_text_idf_rescore_keeps_arrival_order() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("booltext", Schema::empty()).unwrap();+ let idx = engine.get_index("booltext").unwrap();+ let inserted = mixed_corpus(&idx, 40, 300).await;++ let q = json!({"bool": {"should": [+ {"match": {"body": "listpack"}},+ {"match": {"body": "encoding"}}+ ]}});+ let full = idx.search(&req(0, 1000, &q)).await.unwrap();+ assert_tied_and_in_arrival_order("bool-text", &full.hits, &inserted, 340, full.total.value);+}++/// The three re-sorts in the `request.rescore` path (before the first stage,+/// between chained stages, and after the last). A `match_all` primary with a+/// uniform rescore query keeps every score tied through every stage, so all+/// three sorts see an all-tied hit set; each used to tie by `_id` alone.+/// Two chained stages make sure the between-stages sort runs too.+#[tokio::test]+async fn rescore_path_resorts_keep_arrival_order() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("rescore", Schema::empty()).unwrap();+ let idx = engine.get_index("rescore").unwrap();+ let inserted = mixed_corpus(&idx, 40, 300).await;++ let stage = RescoreQuery {+ window_size: 1000,+ query: Some(RescoreQueryInner {+ rescore_query: xerj_query::parse_query(&json!({"term": {"kind": "same"}}))+ .expect("parse rescore query"),+ query_weight: 1.0,+ rescore_query_weight: 1.0,+ }),+ script: None,+ };+ let mut request = req(0, 1000, &json!({"match_all": {}}));+ request.rescore = vec![stage.clone(), stage];++ let full = idx.search(&request).await.unwrap();+ assert_tied_and_in_arrival_order("rescore", &full.hits, &inserted, 340, full.total.value);++ for size in [1usize, 5, 41, 100] {+ let mut bounded = req(0, size, &json!({"match_all": {}}));+ bounded.rescore = request.rescore.clone();+ let p = idx.search(&bounded).await.unwrap();+ assert_eq!(+ page_ids(&p.hits),+ inserted[..size],+ "rescore: size:{size} page disagrees with the full materialisation"+ );+ }+}