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): keep filter and must_not non-scoring before a flush (#2403)
Jacob Elbirta21899a47662
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 883132225..22cf1ee90 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- A `filter` or `must_not` clause no longer changes `_score` before a flush+ (#2403). `bool{must:[match], filter:[term]}` scored buffered documents with+ an IDF-less `1 + ln(1 + tf)`, so on the issue's repro the top hit scored+ 2.609438 and three hits tied at 1.6931472, while the bare `match` scored+ 0.6979745, 0.60089254, 0.5022658 and 0.2530558; the ranking changed at+ flush. The `must` match now takes the same BM25 path as the bare `match`+ and the non-scoring clauses only remove hits. On an index with flushed and+ buffered documents, the shared BM25 statistics also count the buffered+ documents for this shape, so flushed hits score as they do under the bare+ `match`. Covers one `must` match (without its own `analyzer`) plus any+ `filter` or `must_not` clauses with no `should`; other `bool` shapes keep+ their current route.+## [1.0.0-rc.100] - 2026-10-26**rc.100: faster autoindex and search, shaped by your field reports.** Thisdiff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex e07c1149e..4fdc4e843 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -24244,6 +24244,58 @@ impl Index {uncollected,)}+ } else if let Some((bf_field, bf_text, bf_must, bf_gate)) =+ bool_filter_mem_fts_must(query)+ {+ // #2403: `bool{must:[match], filter|must_not:[..]}` used to+ // fall through to the stored-doc scan, which scored every+ // buffered match with the IDF-less `1 + ln(1 + tf)` while the+ // bare `match` took the BM25 arm below, so the ranking changed+ // at flush. `filter` and `must_not` are non-scoring+ // (`BooleanClause.isScoring()`, BooleanClause.java:84-87), so+ // score the `must` clause through the SAME memtable BM25 path+ // the bare `match` takes, then keep only the hits the gate+ // admits. UNCAPPED: the gate runs after scoring, so a capped+ // list could drop a hit the gate would keep, and the consume+ // arm's ghost-window liveness filter needs every hit anyway.+ let mut field_boosts: std::collections::HashMap<String, f32> =+ std::collections::HashMap::new();+ collect_field_boosts(bf_must, &mut field_boosts);+ let mem_stats = collection_stats();+ let (hits, _) = mem.search_text_boosted_with_total_using(+ bf_text,+ &[bf_field],+ usize::MAX,+ &field_boosts,+ mem_stats.as_deref(),+ );+ // Same conservative `_id` detection as the doc-scan arm: only+ // a gate that can read `_id` pays for injecting it.+ let gate_may_read_id: bool = serde_json::to_string(&bf_gate)+ .map(|s| s.contains("_id") || s.contains("Ids") || s.contains("ids"))+ .unwrap_or(true);+ let kept: Vec<(String, f32)> = hits+ .into_iter()+ .filter(|h| {+ let Some(source) = mem.get_doc_source_arc(&h.doc_id) else {+ return false;+ };+ if !gate_may_read_id || source.get("_id").is_some() {+ return doc_matches_query_typed(&bf_gate, &source, &dmq_schema);+ }+ let mut with_id = (*source).clone();+ if let Some(obj) = with_id.as_object_mut() {+ obj.insert("_id".to_string(), Value::String(h.doc_id.clone()));+ }+ doc_matches_query_typed(&bf_gate, &with_id, &dmq_schema)+ })+ .map(|h| (h.doc_id, h.score))+ .collect();+ if kept.is_empty() {+ MemSnapshot::Empty+ } else {+ MemSnapshot::FtsHits(kept, 0)+ }} else if is_doc_scan_query(query) {// count_only + Term/Range short-circuits BEFORE// `try_doc_values_query` because the DV-term path walks@@ -31983,9 +32035,16 @@ impl Index {// 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.+ // A filtered `bool` (#2403) has no query text of its own, but its+ // memtable arm scores the one `must` match: count that clause, or a+ // mixed index scores its segment hits against a union that left the+ // unflushed docs out.+ let mem_text = match bool_filter_mem_fts_must(query) {+ Some((_, text, _, _)) => Some(text.to_string()),+ None => extract_query_text(query),+ };let mem_stats: Option<xerj_fts::CollectionStats> = if mem_doc_count > 0 {- extract_query_text(query)- .and_then(|text| self.memtable.collection_stats(&text, &field_refs))+ mem_text.and_then(|text| self.memtable.collection_stats(&text, &field_refs))} else {None};@@ -49692,6 +49751,57 @@ fn dis_max_mem_fts_subs(q: &QueryNode) -> Option<(Vec<(&str, &str, f32)>, f32)>}}+/// The lone `must` match's `(field, query)` and the non-scoring gate of a+/// `bool{must:[match], filter:[..], must_not:[..]}` whose `must` clause would+/// take the standalone-`Match` memtable FTS arm on its own (#2403): same+/// carve-outs as that arm (`is_doc_scan_query` and `extract_query_text`), no+/// per-query `analyzer`, no `should`, no `minimum_should_match`, and at least+/// one `filter` or `must_not` clause (a lone `must` is already erased by+/// `unwrap_single_clause_bool`). The gate is a `bool` holding only the+/// `filter` and `must_not` clauses, evaluated per hit by the stored-doc+/// matcher, so membership stays what the doc-scan route enforced. Any other+/// shape answers `None` and keeps its existing route.+fn bool_filter_mem_fts_must(q: &QueryNode) -> Option<(&str, &str, &QueryNode, QueryNode)> {+ let QueryNode::Bool {+ must,+ should,+ must_not,+ filter,+ minimum_should_match: None,+ } = q+ else {+ return None;+ };+ if must.len() != 1 || !should.is_empty() || (filter.is_empty() && must_not.is_empty()) {+ return None;+ }+ let clause = &must[0];+ // A per-query `analyzer` declines: the memtable FTS path tokenizes with+ // the index default, while the stored-doc matcher and the segment+ // projection honour it, so taking this arm would change the hit set at+ // flush.+ let QueryNode::Match {+ field,+ query,+ analyzer: None,+ ..+ } = clause+ else {+ return None;+ };+ if is_doc_scan_query(clause) || extract_query_text(clause).is_none() {+ return None;+ }+ let gate = QueryNode::Bool {+ must: Vec::new(),+ should: Vec::new(),+ must_not: must_not.clone(),+ filter: filter.clone(),+ minimum_should_match: None,+ };+ Some((field.as_str(), query.as_str(), clause, gate))+}+/// Erase `bool` wrappers whose only clause is a single SCORING clause.////// `{"bool":{"must":[X]}}` and bare `X` are the same query and ES gives themdiff --git a/engine/crates/xerj-engine/tests/bool_filter_memtable_scoring.rs b/engine/crates/xerj-engine/tests/bool_filter_memtable_scoring.rsnew file mode 100644index 000000000..31caa521d--- /dev/null+++ b/engine/crates/xerj-engine/tests/bool_filter_memtable_scoring.rs@@ -0,0 +1,239 @@+//! Issue #2403: `bool{must:[match], filter:[...]}` scored buffered documents+//! with the IDF-less brute scorer (`score_query_against_doc`:+//! `1 + ln(1 + tf)`), while the identical `must` clause on its own took the+//! memtable BM25 arm. Before `_flush` the filtered query ranked a one-word+//! document level with an eight-word one, and every score moved at flush.+//!+//! A `filter` or `must_not` clause is non-scoring (`BooleanClause.isScoring()`,+//! BooleanClause.java:84-87), so the contract is the one #361 pinned for the+//! segment path, now held in every phase: each hit scores exactly what the+//! `must` clause scores alone, in the same phase, and the hit set is the+//! `must` hits the filter keeps. `bool_filter_is_non_scoring.rs` covers the+//! flushed shapes; this file covers the memtable and the mixed index.+//!+//! Elasticsearch is referenced for wire semantics only; no ES code is here.++use std::collections::{BTreeSet, 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::executor::SearchResult;+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": 100 })).expect("parse_request")+}++async fn search(idx: &Index, q: &Value) -> SearchResult {+ idx.search(&req(q)).await.unwrap()+}++/// `alpha` appears in most bodies with varying frequency and body length, so+/// BM25 and the brute scorer disagree on order; `tag` splits the corpus.+fn doc(i: usize) -> Value {+ let body = match i % 4 {+ 0 => "alpha alpha alpha alpha".to_string(),+ 1 => "alpha".to_string(),+ 2 => "alpha beta gamma delta epsilon zeta eta theta".to_string(),+ _ => format!("beta gamma {i}"),+ };+ json!({ "body": body, "tag": if i.is_multiple_of(3) { "y" } else { "x" } })+}++async fn seed(name: &str, dir: &TempDir) -> std::sync::Arc<Index> {+ let engine = make_engine(dir);+ let mut schema = Schema::empty();+ schema+ .fields+ .push(FieldConfig::new("body", FieldType::Text));+ schema+ .fields+ .push(FieldConfig::new("tag", FieldType::Keyword));+ engine.create_index(name, schema).unwrap();+ engine.get_index(name).unwrap()+}++async fn index_range(idx: &Index, range: std::ops::Range<usize>) {+ for i in range {+ idx.index_document(Some(format!("d{i:02}")), doc(i))+ .await+ .unwrap();+ }+}++/// Every hit of `filtered` scores what `bare` scores for the same `_id`,+/// the order is `bare`'s order restricted to the kept set, the kept set is+/// `want`, and `hits.total` counts exactly the kept set.+async fn assert_scores_like_bare(+ idx: &Index,+ bare: &Value,+ filtered: &Value,+ want: &BTreeSet<String>,+ phase: &str,+) {+ let reference = search(idx, bare).await;+ let actual = search(idx, filtered).await;+ let got: BTreeSet<String> = actual.hits.iter().map(|h| h.id.clone()).collect();+ assert_eq!(&got, want, "{phase}: hit set of {filtered}");+ assert_eq!(+ actual.total.value as usize,+ want.len(),+ "{phase}: hits.total of {filtered}"+ );+ let reference_scores: HashMap<&str, f32> = reference+ .hits+ .iter()+ .map(|h| (h.id.as_str(), h.score))+ .collect();+ for hit in &actual.hits {+ let expected = reference_scores[hit.id.as_str()];+ assert!(+ (hit.score - expected).abs() < 1e-4,+ "{phase}: {} scores {} under {filtered} but {expected} under the bare \+ must clause; a non-scoring clause changed _score (#2403)",+ hit.id,+ hit.score+ );+ }+ let order: Vec<&str> = reference+ .hits+ .iter()+ .map(|h| h.id.as_str())+ .filter(|id| got.contains(*id))+ .collect();+ let actual_order: Vec<&str> = actual.hits.iter().map(|h| h.id.as_str()).collect();+ assert_eq!(actual_order, order, "{phase}: order of {filtered} (#2403)");+}++/// The docs among `0..n` whose body holds `alpha` and that `keep` admits.+fn alpha_docs(n: usize, keep: impl Fn(usize) -> bool) -> BTreeSet<String> {+ (0..n)+ .filter(|i| i % 4 != 3 && keep(*i))+ .map(|i| format!("d{i:02}"))+ .collect()+}++async fn assert_phase(idx: &Index, n: usize, phase: &str) {+ let bare = json!({ "match": { "body": "alpha" } });+ let tag_x = |i: usize| !i.is_multiple_of(3);++ let filter = json!({ "bool": {+ "must": [ { "match": { "body": "alpha" } } ],+ "filter": [ { "term": { "tag": "x" } } ],+ }});+ assert_scores_like_bare(idx, &bare, &filter, &alpha_docs(n, tag_x), phase).await;++ let must_not = json!({ "bool": {+ "must": [ { "match": { "body": "alpha" } } ],+ "must_not": [ { "term": { "tag": "y" } } ],+ }});+ assert_scores_like_bare(idx, &bare, &must_not, &alpha_docs(n, tag_x), phase).await;++ // A filter that reads `_id`: the stored-doc matcher needs it injected.+ let ids_filter = json!({ "bool": {+ "must": [ { "match": { "body": "alpha" } } ],+ "filter": [ { "ids": { "values": ["d00", "d01", "d03"] } } ],+ }});+ let want: BTreeSet<String> = ["d00", "d01"].iter().map(|s| s.to_string()).collect();+ assert_scores_like_bare(idx, &bare, &ids_filter, &want, phase).await;++ // A boost on the must clause reaches the score the same way it does bare.+ let boosted_bare = json!({ "match": { "body": { "query": "alpha", "boost": 3.0 } } });+ let boosted = json!({ "bool": {+ "must": [ { "match": { "body": { "query": "alpha", "boost": 3.0 } } } ],+ "filter": [ { "term": { "tag": "x" } } ],+ }});+ assert_scores_like_bare(idx, &boosted_bare, &boosted, &alpha_docs(n, tag_x), phase).await;+}++#[tokio::test]+async fn filtered_match_scores_like_the_bare_match_before_and_after_flush() {+ let dir = TempDir::new().unwrap();+ let idx = seed("bfmem", &dir).await;+ index_range(&idx, 0..24).await;++ assert_phase(&idx, 24, "pre-flush").await;+ idx.flush().await.unwrap();+ assert_phase(&idx, 24, "post-flush").await;+}++#[tokio::test]+async fn filtered_match_scores_like_the_bare_match_on_a_mixed_index() {+ let dir = TempDir::new().unwrap();+ let idx = seed("bfmix", &dir).await;+ index_range(&idx, 0..12).await;+ idx.flush().await.unwrap();+ index_range(&idx, 12..24).await;++ assert_phase(&idx, 24, "mixed").await;+}++/// Shapes the memtable BM25 path cannot serve (`operator: and` needs the+/// per-token doc-scan) keep their existing route; the hit set is asserted+/// in both phases.+#[tokio::test]+async fn operator_and_must_keeps_its_hit_set() {+ let dir = TempDir::new().unwrap();+ let idx = seed("bfand", &dir).await;+ index_range(&idx, 0..24).await;++ let q = json!({ "bool": {+ "must": [ { "match": { "body": { "query": "alpha beta", "operator": "and" } } } ],+ "filter": [ { "term": { "tag": "x" } } ],+ }});+ let want: BTreeSet<String> = (0..24)+ .filter(|i| i % 4 == 2 && i % 3 != 0)+ .map(|i| format!("d{i:02}"))+ .collect();+ for phase in ["pre-flush", "post-flush"] {+ let got: BTreeSet<String> = search(&idx, &q)+ .await+ .hits+ .iter()+ .map(|h| h.id.clone())+ .collect();+ assert_eq!(got, want, "{phase}: operator:and hit set");+ if phase == "pre-flush" {+ idx.flush().await.unwrap();+ }+ }+}++/// A per-query `analyzer` keeps the existing route too: the memtable BM25+/// path tokenizes with the index default and would lowercase `ALPHA`, while+/// `whitespace` keeps its case, so the hit set would change at flush.+#[tokio::test]+async fn match_with_an_analyzer_keeps_its_hit_set() {+ let dir = TempDir::new().unwrap();+ let idx = seed("bfanalyzer", &dir).await;+ index_range(&idx, 0..24).await;++ let q = json!({ "bool": {+ "must": [ { "match": { "body": { "query": "ALPHA", "analyzer": "whitespace" } } } ],+ "filter": [ { "term": { "tag": "x" } } ],+ }});+ for phase in ["pre-flush", "post-flush"] {+ let got: BTreeSet<String> = search(&idx, &q)+ .await+ .hits+ .iter()+ .map(|h| h.id.clone())+ .collect();+ assert!(+ got.is_empty(),+ "{phase}: whitespace analyzer kept case, got {got:?}"+ );+ if phase == "pre-flush" {+ idx.flush().await.unwrap();+ }+ }+}diff --git a/engine/tests/es-compat-yaml/yaml/search/790_bool_filter_is_non_scoring.yml b/engine/tests/es-compat-yaml/yaml/search/790_bool_filter_is_non_scoring.ymlnew file mode 100644index 000000000..6c30f5673--- /dev/null+++ b/engine/tests/es-compat-yaml/yaml/search/790_bool_filter_is_non_scoring.yml@@ -0,0 +1,108 @@+---+setup:+ - do:+ indices.create:+ index: bool_filter_scoring+ body:+ settings:+ number_of_shards: 1+ mappings:+ properties:+ tag:+ type: keyword+ body:+ type: text+ - do:+ bulk:+ refresh: true+ body:+ - '{"index": {"_index": "bool_filter_scoring", "_id": "1"}}'+ - '{"tag": "x", "body": "alpha alpha alpha alpha"}'+ - '{"index": {"_index": "bool_filter_scoring", "_id": "2"}}'+ - '{"tag": "x", "body": "alpha"}'+ - '{"index": {"_index": "bool_filter_scoring", "_id": "3"}}'+ - '{"tag": "x", "body": "alpha beta gamma delta epsilon zeta eta theta"}'+ - '{"index": {"_index": "bool_filter_scoring", "_id": "4"}}'+ - '{"tag": "x", "body": "beta"}'+ - '{"index": {"_index": "bool_filter_scoring", "_id": "5"}}'+ - '{"tag": "x", "body": "gamma"}'+ - '{"index": {"_index": "bool_filter_scoring", "_id": "6"}}'+ - '{"tag": "y", "body": "alpha beta"}'++---+"filter removes hits without changing the must clause's scores":+ # The bare match fixes the reference scores: 1, 2, 6, 3 by BM25. It runs+ # in each test, not in setup: the runner keeps no stash across them.+ - do:+ search:+ rest_total_hits_as_int: true+ index: bool_filter_scoring+ body:+ query: { match: { body: alpha } }++ - match: { hits.total: 4 }+ - match: { hits.hits.0._id: "1" }+ - match: { hits.hits.1._id: "2" }+ - match: { hits.hits.2._id: "6" }+ - match: { hits.hits.3._id: "3" }+ - set: { hits.hits.0._score: score_1 }+ - set: { hits.hits.1._score: score_2 }+ - set: { hits.hits.3._score: score_3 }++ # #2403: before a flush, a filter clause switched scoring to an IDF-less+ # tf heuristic, so 2 and 3 tied and the order changed at flush.+ - do:+ search:+ rest_total_hits_as_int: true+ index: bool_filter_scoring+ body:+ query:+ bool:+ must: [ { match: { body: alpha } } ]+ filter: [ { term: { tag: x } } ]++ - match: { hits.total: 3 }+ - match: { hits.hits.0._id: "1" }+ - match: { hits.hits.0._score: $score_1 }+ - match: { hits.hits.1._id: "2" }+ - match: { hits.hits.1._score: $score_2 }+ - match: { hits.hits.2._id: "3" }+ - match: { hits.hits.2._score: $score_3 }++---+"must_not removes hits without changing the must clause's scores":+ # The bare match fixes the reference scores: 1, 2, 6, 3 by BM25. It runs+ # in each test, not in setup: the runner keeps no stash across them.+ - do:+ search:+ rest_total_hits_as_int: true+ index: bool_filter_scoring+ body:+ query: { match: { body: alpha } }++ - match: { hits.total: 4 }+ - match: { hits.hits.0._id: "1" }+ - match: { hits.hits.1._id: "2" }+ - match: { hits.hits.2._id: "6" }+ - match: { hits.hits.3._id: "3" }+ - set: { hits.hits.0._score: score_1 }+ - set: { hits.hits.1._score: score_2 }+ - set: { hits.hits.3._score: score_3 }++ - do:+ search:+ rest_total_hits_as_int: true+ index: bool_filter_scoring+ body:+ query:+ bool:+ must: [ { match: { body: alpha } } ]+ must_not: [ { term: { tag: y } } ]++ - match: { hits.total: 3 }+ - match: { hits.hits.0._id: "1" }+ - match: { hits.hits.0._score: $score_1 }+ - match: { hits.hits.1._id: "2" }+ - match: { hits.hits.1._score: $score_2 }+ - match: { hits.hits.2._id: "3" }+ - match: { hits.hits.2._score: $score_3 }