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): a highlight block must not change _score or hit order (#177)
xerj-org58e88fb14255
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 19eb69ec7..92bc19c12 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -13020,16 +13020,20 @@ impl Index {// Determine whether we need hit *sources* at all.// - size > 0 → sources for hits output- // - rescore/highlight → mutate source after collection+ // - rescore → mutates source after collection// - collapse → needs source field// - sort on a field → needs source// - aggs without DV fast path → needs sources// When none of these apply (classic `size:0 + match_all + track_total_hits`// counting query), we skip materialisation entirely and just count.+ //+ // `highlight` is deliberately NOT in this list (#177): it is a pure+ // post-pass over the rendered page (`apply_highlight`), so at `size: 0`+ // — where there is no page — it has nothing to do, and a `size: 0` body+ // must execute identically with and without it.let need_hits_output: bool = size > 0;let need_sources_for_post: bool = need_hits_output|| !request.rescore.is_empty()- || request.highlight.is_some()|| request.collapse.is_some()|| request.sort@@ -14088,11 +14092,20 @@ impl Index {// `from+size` stored-doc parses (live: the 256-doc floor was ~60% of// the range/term page cost). Every excluded shape (sorts, aggs —// the brute agg fallback aggregates the materialised sources —- // rescore/collapse/highlight/explain, min_score, count-only,+ // rescore/collapse/explain, min_score, count-only,// pinned's phase-4 overlay headroom) keeps the original slack// byte-for-byte. Shadowed AFTER the memtable snapshot: the gate// requires the memtable be empty, so the earlier `fetch_limit` uses// are untouched.+ //+ // `highlight` was in the excluded list until #177. It never belonged+ // there — highlighting is a post-pass over the rendered page — and+ // while the segment merge was arrival-order it made this cap+ // observable: a body with `highlight` got 256 candidates, the same+ // body without it got `from+size`, and the two pages carried+ // different `_id`s and different `_score`s. The merge now selects the+ // global top-k by score (see the FTS admission below), so the cap+ // controls only how much work is done, never which hits win.let materialisation_limit: usize = if mem_doc_count == 0&& !deletes_present&& size > 0@@ -14101,7 +14114,6 @@ impl Index {&& request.aggs.is_none()&& request.rescore.is_empty()&& request.collapse.is_none()- && request.highlight.is_none()&& request.min_score.is_none()&& !request.explain&& !matches!(query, QueryNode::Pinned { .. })@@ -14562,13 +14574,53 @@ impl Index {}}// Materialise sources for the top hits only.- // `seg_hits` is score-sorted descending, so taking- // the prefix that fits under `materialisation_limit`- // preserves top-k ordering/scoring.+ // `seg_hits` is score-sorted descending, so the+ // prefix we take is this SEGMENT's top-k.+ //+ // #177 — across segments the collector used to be+ // a plain FIFO capped at `materialisation_limit`:+ // the first segments visited filled it and every+ // later segment was dropped whole, however well+ // its documents scored. The page was therefore+ // "the best hits of whichever segments happened to+ // fit", not the global top-k, and it moved+ // whenever the cap moved — which is what made a+ // `highlight` block (which only widened the cap)+ // rewrite every `_score` and `_id`.+ //+ // `page_worst` is the lowest score currently kept,+ // defined only once the collector is at its cap+ // (below the cap nothing has to be displaced). A+ // segment is opened when it can beat that, and its+ // descending run is walked until it can't; the+ // overflow is trimmed back to the cap by score+ // right after. Bounded by 2×cap in the worst case.+ let page_worst: Option<f32> = if sort_topk.is_none()+ && !count_only+ && all_hits.len() >= materialisation_limit+ {+ all_hits.iter().map(|h| h.score).fold(+ None,+ |acc: Option<f32>, s| {+ Some(match acc {+ Some(a) if a <= s => a,+ _ => s,+ })+ },+ )+ } else {+ None+ };+ let seg_can_enter = sort_topk.is_some()+ || all_hits.len() < materialisation_limit+ || seg_hits+ .first()+ .zip(page_worst)+ .is_some_and(|(sh, worst)| sh.score > worst);if !fts_sorted_handled&& !count_only&& !seg_hits.is_empty()- && all_hits.len() < materialisation_limit+ && seg_can_enter{// F2 RANDOM-ACCESS source hydration. The// scored FTS page needs `_source` for only@@ -14647,17 +14699,24 @@ impl Index {}};for sh in &seg_hits {- // Page full — the rest are already- // counted in `total_count`, so stop- // decoding sources. When a field- // sort is active we must NOT stop:- // every match has to be offered to- // the bounded top-N heap so the- // survivors are the GLOBAL top-N by- // the sort key, not the highest-- // scoring prefix.+ // `seg_hits` descends by score, so once+ // a hit cannot displace the worst kept+ // one neither can any hit after it —+ // the rest are already counted in+ // `total_count`, so stop decoding+ // sources. While the collector is+ // still below its cap `page_worst` is+ // `None` and everything this segment+ // offers is taken (at most one cap's+ // worth; the trim below restores the+ // bound). When a field sort is active+ // we must NOT stop: every match has to+ // be offered to the bounded top-N heap+ // so the survivors are the GLOBAL top-N+ // by the sort key, not the+ // highest-scoring prefix.if sort_topk.is_none()- && all_hits.len() >= materialisation_limit+ && page_worst.is_some_and(|worst| sh.score <= worst){break;}@@ -14719,6 +14778,42 @@ impl Index {all_hits.push(hit);}}+ // #177 — trim the overflow back to the cap+ // by SCORE, so what survives into the next+ // segment is the best `materialisation_limit`+ // seen so far rather than the oldest. The+ // comparator is the one the post-loop page+ // sort uses (score DESC, seq_no ASC, `_id`+ // ASC), so admission and final ordering+ // agree and the page is stable under any+ // cap: `size:1` and `size:200` return the+ // same top hit, and adding `highlight`+ // returns the same page.+ if sort_topk.is_none()+ && all_hits.len() > materialisation_limit+ {+ let mut decorated: Vec<(u64, Hit)> =+ std::mem::take(&mut all_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);+ all_hits =+ decorated.into_iter().map(|(_, h)| h).collect();+ }}}}@@ -31853,8 +31948,15 @@ fn compute_field_value_factor(fvf: &FieldValueFactor, source: &Value) -> f32 {/// `script_score`/`script`/`distance_feature`/`rank_feature`/`_name` — any of/// which would need `_source` or the doc id beyond the scored field), on a/// "plain" request (`size > 0`, and no aggs/min_score/sort/rescore/collapse/-/// search_after/highlight/explain/script_fields/fields). Every other shape+/// search_after/explain/script_fields/fields). Every other shape/// returns `None` so the caller runs the unchanged brute stored-scan path.+///+/// `highlight` is ADMITTED (#177), on the same argument `scored_fast_plan`+/// already makes for it: `function_score_columnar` hydrates `_source` for the+/// winners, and `apply_highlight` runs over the final rendered page from that+/// `_source` plus the query AST — no scan-time state. Bailing on it sent an+/// otherwise identical body down the brute path, and the two paths select+/// their pages differently, so `highlight` changed `_score` and `_id`.fn function_score_fast_fvf<'q>(query: &'q QueryNode,request: &SearchRequest,@@ -31869,7 +31971,6 @@ fn function_score_fast_fvf<'q>(|| !request.rescore.is_empty()|| request.collapse.is_some()|| request.search_after.is_some()- || request.highlight.is_some()|| request.explain|| request.script_fields.is_some()|| !request.fields.is_empty()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.rsnew file mode 100644index 000000000..695a42f69--- /dev/null+++ b/engine/crates/xerj-engine/tests/highlight_does_not_change_ranking.rs@@ -0,0 +1,243 @@+//! Regression test for #177 — a `highlight` block must not change `_score`+//! or hit order.+//!+//! `highlight` is a presentation concern: it is applied by `apply_highlight`+//! as a post-pass over the already-selected, already-scored page. On the+//! pre-fix build its mere presence widened the executor's `materialisation_limit`+//! (the arrival-order cap on the bounded hit collector), and because the+//! cross-segment merge admitted hits FIFO rather than by score, a wider cap+//! produced a *different* page. Adding `"highlight"` therefore changed every+//! `_score` and reordered — indeed replaced — the hits.+//!+//! The test builds two segments where the second holds the genuinely+//! top-scoring documents and the first holds enough matches to fill a small+//! page on its own, then asserts:+//! 1. the page is the same with and without `highlight` (ids + scores), and+//! 2. that page is the true global top-k (matches a full-materialisation+//! run at `size` >= total matches), and+//! 3. highlighting still produces fragments containing the matched term.++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::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 body(size: usize, highlight: bool) -> xerj_query::ast::SearchRequest {+ let mut b = json!({+ "size": size,+ "query": {"match": {"body": "quicklist"}}+ });+ if highlight {+ b.as_object_mut()+ .unwrap()+ .insert("highlight".into(), json!({"fields": {"body": {}}}));+ }+ parse_request(&b).expect("parse_request")+}++/// `(id, score)` page fingerprint.+fn page(hits: &[xerj_query::Hit]) -> Vec<(String, f32)> {+ hits.iter().map(|h| (h.id.clone(), h.score)).collect()+}++#[tokio::test]+async fn highlight_block_does_not_change_scores_or_order() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("hl", Schema::empty()).unwrap();+ let idx = engine.get_index("hl").unwrap();++ // ── Segment 0: 60 long, weakly-matching docs ─────────────────────────+ // One occurrence of the term buried in a long body → low BM25 (long+ // field norm). 60 of them is more than enough to fill a size:5 page on+ // its own, which is exactly what the pre-fix FIFO merge did.+ let filler =+ "the server allocates a buffer and appends the reply object to the client output list "+ .repeat(12);+ for i in 0..60 {+ idx.index_document(+ Some(format!("weak{i:02}")),+ json!({"body": format!("{filler} quicklist {filler}")}),+ )+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();++ // ── Segment 1: 5 short, strongly-matching docs ───────────────────────+ // Short field + repeated term → high BM25. These are the true top-5.+ // Strictly decreasing term frequency keeps the ranking tie-free, so+ // "the top-5" has exactly one right answer.+ 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();++ // Ground truth: materialise every match, then take the top 5.+ let full = idx.search(&body(200, false)).await.unwrap();+ assert_eq!(full.total.value, 65, "all 65 docs match");+ let mut truth = page(&full.hits);+ truth.truncate(5);+ assert!(+ truth.iter().all(|(id, _)| id.starts_with("strong")),+ "sanity: the 5 short docs must be the global top-5, got {truth:?}"+ );++ // ── The invariant under test ─────────────────────────────────────────+ let plain = idx.search(&body(5, false)).await.unwrap();+ let lit = idx.search(&body(5, true)).await.unwrap();++ assert_eq!(+ page(&plain.hits),+ page(&lit.hits),+ "adding a `highlight` block changed the page: without={:?} with={:?}",+ page(&plain.hits),+ page(&lit.hits)+ );+ assert_eq!(+ page(&plain.hits),+ truth,+ "size:5 page is not the global top-5"+ );+ assert_eq!(+ plain.total.value, lit.total.value,+ "`highlight` changed hits.total"+ );++ // ── ...and highlighting still highlights ─────────────────────────────+ for h in &lit.hits {+ let frags = h+ .highlight+ .as_ref()+ .and_then(|m| m.get("body"))+ .unwrap_or_else(|| panic!("hit {} has no `body` highlight", h.id));+ assert!(!frags.is_empty(), "hit {} has zero fragments", h.id);+ assert!(+ frags.iter().any(|f| f.contains("<em>quicklist</em>")),+ "hit {} fragments do not mark the matched term: {frags:?}",+ h.id+ );+ }+ assert!(+ plain.hits.iter().all(|h| h.highlight.is_none()),+ "hits carried a `highlight` key without a highlight block"+ );+}++/// The same invariant one level up, through the ES `_search` request shape+/// used in the issue: `multi_match` over several fields, with the highlight+/// block naming a concrete field.+#[tokio::test]+async fn highlight_block_does_not_change_multi_match_ranking() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("hl2", Schema::empty()).unwrap();+ let idx = engine.get_index("hl2").unwrap();++ let filler =+ "generic prose about clients connections buffers and replies that dilutes the term "+ .repeat(10);+ for i in 0..40 {+ idx.index_document(+ Some(format!("weak{i:02}")),+ json!({"title": format!("file {i}"), "body": format!("{filler} listpack {filler}")}),+ )+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();+ // Strictly decreasing term frequency → strictly decreasing scores, so the+ // 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).+ 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}),+ )+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();++ let mk = |size: usize, highlight: bool| {+ let mut b = json!({+ "size": size,+ "query": {"multi_match": {"query": "listpack", "fields": ["body", "title"]}}+ });+ if highlight {+ b.as_object_mut()+ .unwrap()+ .insert("highlight".into(), json!({"fields": {"body": {}}}));+ }+ parse_request(&b).expect("parse_request")+ };++ let full = idx.search(&mk(200, false)).await.unwrap();+ let mut truth = page(&full.hits);+ truth.truncate(3);++ let plain = idx.search(&mk(3, false)).await.unwrap();+ let lit = idx.search(&mk(3, true)).await.unwrap();++ assert_eq!(+ page(&plain.hits),+ page(&lit.hits),+ "multi_match: `highlight` changed the page"+ );+ assert_eq!(page(&plain.hits), truth, "multi_match: page is not top-3");+}++/// Selection must not depend on the page size either: the top-1 of a+/// `size:1` request is the top-1 of a `size:200` request. This is the same+/// arrival-order-cap defect seen from the other side, and it is what made+/// `highlight` (which only widened the cap) look like a scoring knob.+#[tokio::test]+async fn top_hit_is_stable_across_page_sizes() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("hl3", Schema::empty()).unwrap();+ let idx = engine.get_index("hl3").unwrap();++ let filler = "padding words that make the field long and the norm large ".repeat(10);+ for i in 0..80 {+ idx.index_document(+ Some(format!("weak{i:02}")),+ json!({"body": format!("{filler} ziplist")}),+ )+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();+ idx.index_document(Some("best".into()), json!({"body": "ziplist ziplist"}))+ .await+ .unwrap();+ idx.flush().await.unwrap();++ let q = |size: usize| -> xerj_query::ast::SearchRequest {+ parse_request(&json!({"size": size, "query": {"match": {"body": "ziplist"}}}))+ .expect("parse_request")+ };++ let deep = idx.search(&q(200)).await.unwrap();+ let expected: Value = json!([deep.hits[0].id.clone(), deep.hits[0].score]);+ assert_eq!(deep.hits[0].id, "best", "sanity: `best` is the top hit");++ for size in [1usize, 2, 5, 10, 50] {+ let r = idx.search(&q(size)).await.unwrap();+ let got: Value = json!([r.hits[0].id.clone(), r.hits[0].score]);+ assert_eq!(got, expected, "size:{size} returned a different top hit");+ }+}