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): keep a nested constant_score after flush (#2654) (#2658)

xerj-org7e40cc56ea9b
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 3aa8e33ba..3f483d17d 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -55664,6 +55664,7 @@ fn collect_fts_query_fields(q: &FtsQuery, out: &mut Vec<String>) {
// queried field" gate to check.
FtsQuery::DocScores(_) => {}
FtsQuery::MatchAll => {}
+ FtsQuery::ConstantScore(c) => collect_fts_query_fields(&c.query, out),
}
}
@@ -55725,6 +55726,9 @@ fn collect_fts_query_terms(q: &FtsQuery, out: &mut Vec<(String, String)>) {
collect_fts_query_terms(sub, out);
}
}
+ // Non-scoring like `filter`, but still executed: collected for the
+ // same reason.
+ FtsQuery::ConstantScore(c) => collect_fts_query_terms(&c.query, out),
}
}
@@ -56039,18 +56043,27 @@ fn query_node_to_fts_projected(
}
QueryNode::MatchNone => None,
// `constant_score`: MATCHING is the inner query's (so text filters
- // keep the inverted-index path); the wrapper's constant score is
- // applied post-hoc by the top-level override in `search` (the
- // keyword-schema shape is served bit-exactly by `scored_columnar`
- // before this projection is ever consulted).
- QueryNode::Constant { query, .. } => query_node_to_fts_projected(
+ // keep the inverted-index path), and every match scores exactly the
+ // wrapper's boost. #2654: this used to return the inner projection
+ // bare and rely on the top-level override in `search`, which only
+ // sees a top-level `constant_score`; nested in a `bool` on flushed
+ // segments, the clause added the inner BM25 instead of the boost.
+ // (The keyword-schema shape is served bit-exactly by
+ // `scored_columnar` before this projection is ever consulted.)
+ QueryNode::Constant { query, score } => query_node_to_fts_projected(
query,
text_fields,
exact_fields,
keyword_fields,
binding,
pinned,
- ),
+ )
+ .map(|inner| {
+ FtsQuery::ConstantScore(Box::new(xerj_fts::search::ConstantScoreQuery {
+ query: inner,
+ score: *score,
+ }))
+ }),
QueryNode::Match {
field,
query,
diff --git a/engine/crates/xerj-engine/tests/nested_constant_score_flush_parity.rs b/engine/crates/xerj-engine/tests/nested_constant_score_flush_parity.rs
new file mode 100644
index 000000000..ff8af024a
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/nested_constant_score_flush_parity.rs
@@ -0,0 +1,110 @@
+//! #2654 — a `constant_score` nested in a `bool` must add exactly its boost
+//! on flushed segments.
+//!
+//! The segment FTS projection turned a nested `constant_score` into its inner
+//! query and relied on the top-level override in `search`, which only
+//! handles a `constant_score` at the root. After a flush the clause added
+//! the inner query's BM25 (0.56 here) instead of the boost (1000). The
+//! `xerj code` coverage clauses (#2329) are two boost-1000 `constant_score`
+//! clauses inside a `bool`, so they scored the same wrong way.
+//!
+//! ES semantics: `constant_score` scores every match exactly `boost`
+//! (Lucene `ConstantScoreQuery`), and `bool` sums its matching `must` and
+//! `should` scores.
+
+use std::collections::HashMap;
+
+use serde_json::{json, Value};
+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;
+
+async fn seed_flushed(name: &str) -> (TempDir, std::sync::Arc<Index>) {
+ let dir = TempDir::new().unwrap();
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ let engine = Engine::new(config).expect("engine::new");
+ let mut schema = Schema::empty();
+ schema.fields.push(FieldConfig::new("t", FieldType::Text));
+ engine.create_index(name, schema).unwrap();
+ let idx = engine.get_index(name).unwrap();
+ for (id, t) in [("1", "alpha beta"), ("2", "alpha"), ("3", "gamma beta")] {
+ idx.index_document(Some(id.to_string()), json!({ "t": t }))
+ .await
+ .unwrap();
+ }
+ idx.flush().await.unwrap();
+ (dir, idx)
+}
+
+async fn scores(idx: &Index, query: Value) -> HashMap<String, f32> {
+ let req = parse_request(&json!({"query": query, "size": 10})).expect("parse_request");
+ idx.search(&req)
+ .await
+ .unwrap()
+ .hits
+ .into_iter()
+ .map(|h| (h.id, h.score))
+ .collect()
+}
+
+fn alpha() -> Value {
+ json!({"match": {"t": "alpha"}})
+}
+
+fn boosted_beta(boost: f32) -> Value {
+ json!({"constant_score": {"filter": {"match": {"t": "beta"}}, "boost": boost}})
+}
+
+fn assert_close(label: &str, actual: Option<&f32>, expected: f32) {
+ let actual = *actual.unwrap_or_else(|| panic!("{label}: missing hit"));
+ assert!(
+ (actual - expected).abs() < 1e-3,
+ "{label}: _score is {actual}, expected {expected}"
+ );
+}
+
+#[tokio::test]
+async fn nested_constant_score_adds_its_boost_after_a_flush() {
+ let (_dir, idx) = seed_flushed("cs-should").await;
+ let must_only = scores(&idx, alpha()).await;
+
+ let got = scores(
+ &idx,
+ json!({"bool": {"must": [alpha()], "should": [boosted_beta(1000.0)]}}),
+ )
+ .await;
+ assert_eq!(got.len(), 2, "{got:?}");
+ assert_close(
+ "doc 1 (matches the should)",
+ got.get("1"),
+ must_only["1"] + 1000.0,
+ );
+ assert_close("doc 2 (does not)", got.get("2"), must_only["2"]);
+
+ // In `must`, alone: every match scores exactly the boost.
+ let got = scores(&idx, json!({"bool": {"must": [boosted_beta(7.0)]}})).await;
+ assert_eq!(got.len(), 2, "{got:?}");
+ assert_close("must-only doc 1", got.get("1"), 7.0);
+ assert_close("must-only doc 3", got.get("3"), 7.0);
+
+ // Two scoring clauses, one of them constant.
+ let got = scores(
+ &idx,
+ json!({"bool": {"must": [boosted_beta(3.0), alpha()]}}),
+ )
+ .await;
+ assert_eq!(got.len(), 1, "{got:?}");
+ assert_close("conjunction doc 1", got.get("1"), must_only["1"] + 3.0);
+}
+
+#[tokio::test]
+async fn top_level_constant_score_is_unchanged() {
+ let (_dir, idx) = seed_flushed("cs-top").await;
+ let got = scores(&idx, boosted_beta(2.5)).await;
+ assert_eq!(got.len(), 2, "{got:?}");
+ assert_close("doc 1", got.get("1"), 2.5);
+ assert_close("doc 3", got.get("3"), 2.5);
+}
diff --git a/engine/crates/xerj-fts/src/search.rs b/engine/crates/xerj-fts/src/search.rs
index 0b810a864..26abbe674 100644
--- a/engine/crates/xerj-fts/src/search.rs
+++ b/engine/crates/xerj-fts/src/search.rs
@@ -482,6 +482,18 @@ impl DocScoresQuery {
}
}
+/// ES `constant_score`: the docs `query` matches, each scored exactly
+/// `score` (the wrapper's `boost`). The inner query's own score is dropped.
+///
+/// #2654: without this leaf the engine projected a nested `constant_score`
+/// to its inner query. Inside a `bool` on flushed segments, that clause then
+/// added the inner query's BM25 instead of the boost.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ConstantScoreQuery {
+ pub query: Query,
+ pub score: f32,
+}
+
/// Top-level query enum.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -497,6 +509,8 @@ pub enum Query {
MatchAll,
/// Caller-supplied `(doc_id, score)` set — see [`DocScoresQuery`].
DocScores(DocScoresQuery),
+ /// See [`ConstantScoreQuery`].
+ ConstantScore(Box<ConstantScoreQuery>),
}
// ── FtsSearcher ───────────────────────────────────────────────────────────────
@@ -917,6 +931,18 @@ impl FtsSearcher {
explanation: None,
})
.collect()),
+ // #2654: match with the inner query, score every match `score`.
+ Query::ConstantScore(cq) => {
+ let mut hits = self.execute(&cq.query, false)?;
+ for hit in &mut hits {
+ hit.score = cq.score;
+ hit.explanation = explain.then(|| QueryExplanation {
+ total_score: cq.score,
+ term_breakdowns: Vec::new(),
+ });
+ }
+ Ok(hits)
+ }
}
}
diff --git a/engine/tests/es-compat-yaml/yaml/search/791_nested_constant_score_flushed.yml b/engine/tests/es-compat-yaml/yaml/search/791_nested_constant_score_flushed.yml
new file mode 100644
index 000000000..9d99d227c
--- /dev/null
+++ b/engine/tests/es-compat-yaml/yaml/search/791_nested_constant_score_flushed.yml
@@ -0,0 +1,55 @@
+# #2654: a `constant_score` inside a `bool` scores exactly its `boost` on a
+# flushed segment, as it does in the memtable. `filter` scores 0 and
+# `bool` sums its matching `must`/`should` scores, so the expected scores are
+# exact (no BM25 involved).
+setup:
+ - do:
+ indices.create:
+ index: cs_nested
+ body:
+ mappings:
+ properties:
+ t: { type: text }
+ - do:
+ bulk:
+ refresh: true
+ body:
+ - '{"index": {"_index": "cs_nested", "_id": "1"}}'
+ - '{"t": "alpha beta"}'
+ - '{"index": {"_index": "cs_nested", "_id": "2"}}'
+ - '{"t": "alpha"}'
+ - do:
+ indices.flush:
+ index: cs_nested
+
+---
+"constant_score in should adds its boost":
+ - do:
+ search:
+ index: cs_nested
+ body:
+ query:
+ bool:
+ filter: [ { match: { t: alpha } } ]
+ should: [ { constant_score: { filter: { match: { t: beta } }, boost: 1000 } } ]
+ - match: { hits.total.value: 2 }
+ - match: { hits.hits.0._id: "1" }
+ - match: { hits.hits.0._score: 1000.0 }
+ - match: { hits.hits.1._id: "2" }
+ - match: { hits.hits.1._score: 0.0 }
+
+---
+"constant_score clauses in must and should sum":
+ - do:
+ search:
+ index: cs_nested
+ body:
+ query:
+ bool:
+ must: [ { constant_score: { filter: { match: { t: alpha } }, boost: 7 } } ]
+ should: [ { constant_score: { filter: { match: { t: beta } }, boost: 2 } } ]
+ - match: { hits.total.value: 2 }
+ - match: { hits.hits.0._id: "1" }
+ - match: { hits.hits.0._score: 9.0 }
+ - match: { hits.hits.1._id: "2" }
+ - match: { hits.hits.1._score: 7.0 }