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(engine): make multi_match hit sets flush-invariant (#218)
xerj-org7d7c040c31d8
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex c5c5b1a9f..c8b25f3f3 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -28392,6 +28392,11 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {.map(str::to_string).collect();let is_cross = matches!(match_type, xerj_query::ast::MultiMatchType::CrossFields);+ let is_phrase = matches!(+ match_type,+ xerj_query::ast::MultiMatchType::Phrase+ | xerj_query::ast::MultiMatchType::PhrasePrefix+ );let is_and = matches!(operator, Some(xerj_query::ast::BoolOperator::And));let field_texts: Vec<String> = fields.iter()@@ -28451,8 +28456,35 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {.collect();tokens.iter().all(|t| ft_tokens.contains(t.as_str()))})- } else {+ } else if is_phrase || tokens.is_empty() {+ // phrase / phrase_prefix: the whole query must appear+ // contiguously — substring approximation of phrase+ // matching, shared with the segment path (whose FTS+ // projection declines these types, so BOTH states evaluate+ // this predicate and the hit set is flush-invariant). Also+ // the fallback when the query has no alphanumeric tokens.field_texts.iter().any(|ft| ft.contains(&q_lower))+ } else {+ // best_fields / most_fields with the default operator (OR,+ // issue #218): ANY query token equal to ANY token of a+ // single field admits the hit — ES's default `operator: or`,+ // and exactly what the segment path executes (a per-field+ // OR-bool over tokens; the same Occur::Should convention as+ // tantivy's `new_multiterms_query`,+ // tantivy/src/query/boolean_query/boolean_query.rs:244).+ // Token EQUALITY, not substring: `jump` must not match+ // "jumparound" (the segment term path never did).+ //+ // Pre-fix this branch was `ft.contains(&q_lower)` — whole-+ // query substring containment, requiring every token+ // adjacent and in order — so a multi-token query missed+ // memtable docs the segment path matched, and the hit set+ // changed at _flush.+ field_texts.iter().any(|ft| {+ ft.split(|c: char| !c.is_alphanumeric())+ .filter(|t| !t.is_empty())+ .any(|ft_tok| tokens.iter().any(|qt| qt == ft_tok))+ })}}@@ -30114,18 +30146,72 @@ fn score_query_against_doc(q: &QueryNode, source: &Value) -> f32 {query,boost,match_type,+ operator,..} => {let q_lower = query.to_lowercase();let outer_boost = boost.unwrap_or(1.0);let is_cross = matches!(match_type, xerj_query::ast::MultiMatchType::CrossFields);+ let is_phrase = matches!(+ match_type,+ xerj_query::ast::MultiMatchType::Phrase+ | xerj_query::ast::MultiMatchType::PhrasePrefix+ );+ let is_and = matches!(operator, Some(xerj_query::ast::BoolOperator::And));+ // Per-field hit test mirroring `doc_matches_query` (issue #218):+ // token-level OR by default / AND on request; phrase types keep+ // whole-query substring containment. Pre-fix this arm tested+ // `contains(whole query)`, so a memtable doc admitted by the+ // membership check could still score 0.0 and be dropped by+ // scored paths / rescore.+ let q_tokens: Vec<String> = q_lower+ .split(|c: char| !c.is_alphanumeric())+ .filter(|t| !t.is_empty())+ .map(str::to_string)+ .collect();+ let field_hit = |text_lc: &str| -> bool {+ if is_phrase || q_tokens.is_empty() {+ return text_lc.contains(&q_lower);+ }+ let ft_tokens: std::collections::HashSet<&str> = text_lc+ .split(|c: char| !c.is_alphanumeric())+ .filter(|t| !t.is_empty())+ .collect();+ if is_and {+ q_tokens.iter().all(|t| ft_tokens.contains(t.as_str()))+ } else {+ q_tokens.iter().any(|t| ft_tokens.contains(t.as_str()))+ }+ };let mut sum_score = 0.0f32;let mut max_score = 0.0f32;let mut matched = false;for field_spec in fields {let (field, field_boost) = parse_field_boost(field_spec);- if let Some(Value::String(s)) = get_field_value(source, field) {- if s.to_lowercase().contains(&q_lower) {+ // Same per-field text extraction as `doc_matches_query`:+ // strings, arrays (joined), and other scalars — an array-+ // valued field admitted by membership must not score 0.0.+ let text_lc: Option<String> = match get_field_value(source, field) {+ Some(Value::String(s)) => Some(s.to_lowercase()),+ Some(Value::Array(arr)) => {+ let joined: Vec<String> = arr+ .iter()+ .map(|v| match v {+ Value::String(s) => s.to_lowercase(),+ other => other.to_string(),+ })+ .collect();+ if joined.is_empty() {+ None+ } else {+ Some(joined.join(" "))+ }+ }+ Some(other) => Some(other.to_string().to_lowercase()),+ None => None,+ };+ if let Some(text) = text_lc {+ if field_hit(&text) {sum_score += field_boost;if field_boost > max_score {max_score = field_boost;@@ -32454,6 +32540,24 @@ fn query_node_to_fts(boost,..} => {+ // The memtable evaluator (`doc_matches_query`) gives phrase /+ // phrase_prefix multi_match whole-query-containment semantics,+ // which is not expressible as this per-field token bool —+ // projecting them as an OR over tokens made the segment path+ // OVER-match (the reverse of issue #218's memtable under-match:+ // a reversed phrase started matching at _flush).+ // Decline the projection instead; the stored-doc scan then+ // evaluates the same `doc_matches_query` predicate the memtable+ // uses, keeping the matched set flush-invariant.+ // (cross_fields + `operator: and` is declined too — see the+ // `is_and` guard below, which needs the analyzed token count.)+ if matches!(+ match_type,+ xerj_query::ast::MultiMatchType::Phrase+ | xerj_query::ast::MultiMatchType::PhrasePrefix+ ) {+ return None;+ }let registry = AnalyzerRegistry::default();let analyzer = registry.get_analyzer("standard")?;let tokens = analyzer.analyze(query);@@ -32503,7 +32607,12 @@ fn query_node_to_fts(// the stored-doc scan, whose cross_fields arm implements the// combined-text semantics. Without this, dropping an unmapped// field would FLIP an `operator: and` query from the scan's- // AND semantics onto the FTS OR path, over-matching.+ // AND semantics onto the FTS OR path, over-matching (#217) —+ // and the segment path would admit docs missing an AND token+ // that the memtable rejected, so the hit set changed at _flush+ // (#218). A SINGLE analyzed token needs no decline: "the token+ // is in at least one field" is what the per-field clauses OR'd+ // together already mean, so that shape keeps the postings path.let is_and = matches!(operator, Some(xerj_query::ast::BoolOperator::And));if is_and&& tokens.len() > 1@@ -32549,8 +32658,12 @@ fn query_node_to_fts(*fb,)));} else {- // `operator: and` → per-field must (all tokens in this- // field), same as the Match arm; default → per-field OR.+ // Honour the operator like the Match arm above: AND →+ // every token must match in the SAME field (`must`); OR+ // (the ES default) → any token (`should`). Pre-fix the+ // operator was dropped here, so `operator: and` OR'd its+ // tokens on segments while the memtable required every+ // one — the hit set changed at _flush (issue #218).let mut field_bool = FtsBool::new().boost(*fb);for token in &tokens {let term = FtsQuery::Term(FtsTerm::new(field.as_str(), &token.text));diff --git a/engine/crates/xerj-engine/tests/multi_match_flush_parity.rs b/engine/crates/xerj-engine/tests/multi_match_flush_parity.rsnew file mode 100644index 000000000..591974906--- /dev/null+++ b/engine/crates/xerj-engine/tests/multi_match_flush_parity.rs@@ -0,0 +1,311 @@+//! Regression tests for issue #218: the matched SET of a multi-token+//! `match`/`multi_match` must be identical before and after `flush()`.+//!+//! Pre-fix, the memtable membership test for `multi_match` (best_fields /+//! most_fields, default operator) was `field_text.contains(whole_query)` —+//! whole-query substring containment, i.e. every token adjacent and in+//! order — while the segment path lowered the same query to a per-field+//! OR-bool over tokens (ES default `operator: or`). A doc containing only+//! SOME of the query tokens was therefore invisible until `_flush`, and+//! the hit set changed with flush timing. The reverse divergence existed+//! for `operator: and` and the phrase types: the segment FTS projection+//! ignored them and OR'd the tokens, so post-flush over-matched.+//!+//! Every test seeds one index, runs ALL its queries against the memtable+//! (pre-flush), flushes ONCE, re-runs the same queries against the segment+//! (post-flush), and asserts each query's matched id set is the expected+//! one in BOTH states — i.e. flush timing never changes the hit set.++use std::collections::BTreeSet;++use serde_json::{json, Value};+use tempfile::TempDir;+use xerj_common::config::Config;+use xerj_common::types::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")+}++async fn ids(idx: &Index, q: &Value) -> BTreeSet<String> {+ idx.search(&req(q.clone()))+ .await+ .unwrap()+ .hits+ .iter()+ .map(|h| h.id.clone())+ .collect()+}++/// Run every (query, expected-ids, label) case against the memtable,+/// flush once, run every case again against the segment, and assert the+/// hit set is the expected one in both states.+async fn assert_flush_parity(idx: &std::sync::Arc<Index>, cases: &[(Value, &[&str], &str)]) {+ let expected: Vec<BTreeSet<String>> = cases+ .iter()+ .map(|(_, exp, _)| exp.iter().map(|s| s.to_string()).collect())+ .collect();+ for ((q, _, label), exp) in cases.iter().zip(&expected) {+ let pre = ids(idx, q).await;+ assert_eq!(+ &pre, exp,+ "{label}: PRE-flush (memtable) hit set wrong for {q}"+ );+ }+ idx.flush().await.unwrap();+ for ((q, _, label), exp) in cases.iter().zip(&expected) {+ let post = ids(idx, q).await;+ assert_eq!(+ &post, exp,+ "{label}: POST-flush (segment) hit set wrong for {q}"+ );+ }+}++/// One index, two docs. Doc 1 is the reproducer from issue #218; doc 2 is+/// a control that must never match any query in these tests.+async fn seed(engine: &Engine, name: &str) -> std::sync::Arc<Index> {+ engine.create_index(name, Schema::empty()).unwrap();+ let idx = engine.get_index(name).unwrap();+ idx.index_document(+ Some("1".into()),+ json!({+ "body": "the log merge policy groups segments into size buckets",+ "title": "merge policy"+ }),+ )+ .await+ .unwrap();+ idx.index_document(+ Some("2".into()),+ json!({"body": "quick brown fox", "title": "animals"}),+ )+ .await+ .unwrap();+ idx+}++/// Issue #218 reproducer: multi-token multi_match with the default+/// operator (OR) — one token present, one absent. ES returns the doc in+/// both states; pre-fix the memtable returned 0 hits.+#[tokio::test]+async fn multi_token_or_default_hit_set_stable_across_flush() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ let idx = seed(&engine, "mmp_or").await;++ assert_flush_parity(+ &idx,+ &[+ (+ json!({"multi_match": {"query": "merge zzzznotpresent", "fields": ["body"]}}),+ &["1"],+ "single-field OR",+ ),+ (+ json!({"multi_match": {"query": "merge zzzznotpresent",+ "fields": ["body", "title"]}}),+ &["1"],+ "multi-field OR",+ ),+ (+ json!({"multi_match": {"query": "merge zzzznotpresent",+ "fields": ["body", "title"], "type": "most_fields"}}),+ &["1"],+ "most_fields OR",+ ),+ // `match` on the same field must agree with multi_match(["field"]).+ (+ json!({"match": {"body": "merge zzzznotpresent"}}),+ &["1"],+ "match OR",+ ),+ ],+ )+ .await;+}++/// The memtable hit must also carry a non-zero score: pre-fix,+/// `score_query_against_doc` used the same whole-query substring test, so+/// a doc admitted by the (fixed) membership check would still score 0.0+/// and be dropped by scored paths / rescore.+#[tokio::test]+async fn memtable_multi_match_or_hit_scores_nonzero() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ let idx = seed(&engine, "mmp_score").await;++ let r = idx+ .search(&req(json!({+ "multi_match": {"query": "merge zzzznotpresent", "fields": ["body", "title"]}+ })))+ .await+ .unwrap();+ assert_eq!(r.total.value, 1, "memtable OR hit count");+ assert!(+ r.hits[0].score > 0.0,+ "memtable multi_match OR hit scored {} (expected > 0)",+ r.hits[0].score+ );+}++/// Explicit `operator: and` requires EVERY token — in both states.+/// Pre-fix the segment FTS projection dropped the operator and OR'd the+/// tokens, so the absent-token query matched post-flush.+#[tokio::test]+async fn operator_and_hit_set_stable_across_flush() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ let idx = seed(&engine, "mmp_and").await;++ assert_flush_parity(+ &idx,+ &[+ // One token absent → no match, before AND after flush.+ (+ json!({"multi_match": {"query": "merge zzzznotpresent", "fields": ["body"],+ "operator": "and"}}),+ &[],+ "AND absent token",+ ),+ // All tokens present (non-adjacent, out of order) → match in both.+ (+ json!({"multi_match": {"query": "buckets merge", "fields": ["body"],+ "operator": "and"}}),+ &["1"],+ "AND all tokens present",+ ),+ ],+ )+ .await;+}++/// cross_fields + operator:and pools tokens ACROSS fields: doc 1 has+/// "policy" only in `title` and "buckets" only in `body`, so no single+/// field holds both tokens but the pooled view does. Pre-fix the segment+/// path OR'd the tokens (over-matching the absent-token query below).+#[tokio::test]+async fn cross_fields_and_hit_set_stable_across_flush() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("mmp_cross", Schema::empty()).unwrap();+ let idx = engine.get_index("mmp_cross").unwrap();+ idx.index_document(+ Some("1".into()),+ json!({"body": "groups segments into size buckets", "title": "merge policy"}),+ )+ .await+ .unwrap();+ idx.index_document(+ Some("2".into()),+ json!({"body": "quick brown fox", "title": "animals"}),+ )+ .await+ .unwrap();++ assert_flush_parity(+ &idx,+ &[+ // Tokens scattered across fields → pooled AND matches.+ (+ json!({"multi_match": {"query": "policy buckets", "fields": ["body", "title"],+ "type": "cross_fields", "operator": "and"}}),+ &["1"],+ "cross AND pooled",+ ),+ // One token absent anywhere → no match in either state.+ (+ json!({"multi_match": {"query": "policy zzzznotpresent",+ "fields": ["body", "title"],+ "type": "cross_fields", "operator": "and"}}),+ &[],+ "cross AND absent token",+ ),+ // SINGLE-token cross_fields + AND keeps the FTS projection (the+ // decline is gated on >1 analyzed token): with one token,+ // "present in the pooled text" and "present in at least one+ // field" — what the OR'd per-field clauses mean — are the same+ // predicate. Both states must agree anyway.+ (+ json!({"multi_match": {"query": "policy", "fields": ["body", "title"],+ "type": "cross_fields", "operator": "and"}}),+ &["1"],+ "cross AND single token present",+ ),+ (+ json!({"multi_match": {"query": "zzzznotpresent", "fields": ["body", "title"],+ "type": "cross_fields", "operator": "and"}}),+ &[],+ "cross AND single token absent",+ ),+ ],+ )+ .await;+}++/// `type: phrase` requires the tokens contiguous and in order — in both+/// states. Pre-fix the segment projection OR'd the tokens, so a reversed+/// phrase matched post-flush.+#[tokio::test]+async fn phrase_type_hit_set_stable_across_flush() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ let idx = seed(&engine, "mmp_phrase").await;++ assert_flush_parity(+ &idx,+ &[+ // In-order contiguous phrase → matches in both states.+ (+ json!({"multi_match": {"query": "merge policy", "fields": ["body", "title"],+ "type": "phrase"}}),+ &["1"],+ "phrase in order",+ ),+ // Reversed order → no match in either state.+ (+ json!({"multi_match": {"query": "policy merge", "fields": ["body", "title"],+ "type": "phrase"}}),+ &[],+ "phrase reversed",+ ),+ ],+ )+ .await;+}++/// Guard for the token-equality tightening: a single-token multi_match+/// must NOT substring-match inside a longer word (`jump` vs+/// "jumparound") — the segment term path never did; pre-fix the memtable+/// substring path did.+#[tokio::test]+async fn single_token_multi_match_is_token_equality_not_substring() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("mmp_tok", Schema::empty()).unwrap();+ let idx = engine.get_index("mmp_tok").unwrap();+ idx.index_document(Some("1".into()), json!({"body": "jumparound artist"}))+ .await+ .unwrap();+ idx.index_document(Some("2".into()), json!({"body": "big jump today"}))+ .await+ .unwrap();++ assert_flush_parity(+ &idx,+ &[(+ json!({"multi_match": {"query": "jump", "fields": ["body"]}}),+ &["2"],+ "single token equality",+ )],+ )+ .await;+}