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(memtable): close the pre-flush half of multi-valued keyword matching (#332)
xerj-org547f2fea9d5d
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 7ce8d25f1..4c72dea51 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -33789,10 +33789,17 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {multi_match_field_values_lc(source, field)}).collect();- let field_texts: Vec<String> = field_value_lists- .iter()- .map(|values| values.join(" "))- .collect();+ // Only the non-phrase arms below read the joined form; building it+ // for the phrase arm would be a per-field allocation this scan pays+ // once per buffered doc per query.+ let field_texts: Vec<String> = if is_phrase && !phrase_q_tokens.is_empty() {+ Vec::new()+ } else {+ field_value_lists+ .iter()+ .map(|values| values.join(" "))+ .collect()+ };if is_phrase && !phrase_q_tokens.is_empty() {// phrase / phrase_prefix: POSITIONAL, per field (issue// #230). ES lowers these types to a dis_max over per-fielddiff --git a/engine/crates/xerj-engine/src/memtable.rs b/engine/crates/xerj-engine/src/memtable.rsindex 22c96c03b..f5979d51b 100644--- a/engine/crates/xerj-engine/src/memtable.rs+++ b/engine/crates/xerj-engine/src/memtable.rs@@ -1782,6 +1782,28 @@ impl ShardedFtsMemtable {Some((counts, missing))}+ /// True when ANY shard's single-valued doc-values column for `field` is+ /// lossy, so no shard's column may be trusted for whole-value matching.+ ///+ /// #332 — the per-shard `doc_values_term_query` / `doc_values_terms_query`+ /// return `None` for two very different reasons: "this shard holds no+ /// column for the field" (a true zero-match answer) and "this shard's+ /// column cannot answer" (array-valued → first element only;+ /// analyzed-text → whitespace values). The cross-shard wrappers below+ /// could not tell them apart and folded a REFUSAL into "zero hits here",+ /// so a two-shard memtable with `{"tags":["red","blue"]}` in shard A and+ /// `{"tags":"red"}` in shard B answered `term tags:red` with shard B's+ /// doc only. `doc_values_bool_query` already propagates a per-shard+ /// refusal globally (`?` inside its loop); this makes the single-leaf+ /// wrappers behave the same way.+ fn dv_column_unusable(&self, field: &str) -> bool {+ self.shards.iter().any(|s| {+ let g = s.read();+ g.doc_values.array_fields.contains(field)+ || g.doc_values.keyword_has_whitespace.contains(field)+ })+ }+/// DocValues term query — aggregates hits across all shards./// Returns `Some(Vec<(doc_id, local_idx)>)` if any shard matched./// The `local_idx` is shard-local; callers use the doc_id to@@ -1792,6 +1814,9 @@ impl ShardedFtsMemtable {value: &str,limit: usize,) -> Option<(Vec<(String, usize)>, u64)> {+ if self.dv_column_unusable(field) {+ return None;+ }let mut cands: Vec<(u64, String, usize)> = Vec::new();let mut total: u64 = 0;let mut any_hit = false;@@ -1829,6 +1854,11 @@ impl ShardedFtsMemtable {) -> Option<(Vec<(String, usize)>, u64)> {// #191 — per-shard bound + global `(seq_no, _id)` narrowing, as in// `doc_values_term_query`.+ // #332 — one lossy shard poisons the whole field; see+ // `dv_column_unusable`.+ if self.dv_column_unusable(field) {+ return None;+ }let mut cands: Vec<(u64, String, usize)> = Vec::new();let mut total: u64 = 0;let mut any_hit = false;@@ -3284,6 +3314,19 @@ impl FtsMemtable {/// a bool of term+range predicates matches the same doc set the/// per-child queries would intersect to — without intermediate/// per-child hit vectors.+ ///+ /// #332 — the array bailout is part of "mirror the standalone paths+ /// exactly" and was MISSING here: `doc_values_term_query`,+ /// `doc_values_terms_query` and `filtered_docs_arc` all refuse a field+ /// that has ever carried an array, because `push_field` stores only the+ /// array's FIRST element in these single-valued columns. This walk did+ /// not, so it answered a bare `term` on a multi-valued keyword field+ /// from the lossy column and silently dropped every doc whose match was+ /// in a non-first element (`{"tags":["red","blue"]}` → `term tags:blue`+ /// = 0 hits) for as long as the doc stayed memtable-resident. It is the+ /// arm a plain `term` search actually takes (`is_doc_scan_query` →+ /// fused columnar, ahead of `try_doc_values_query`), so the standalone+ /// path's bailout never got a chance to fire.pub fn doc_values_bool_hits(&self,preds: &[MemBoolPred],@@ -3304,6 +3347,12 @@ impl FtsMemtable {for p in preds {match p {MemBoolPred::Term { field, value } => {+ // Array-valued field: the column is lossy (first element+ // only) → bail so a later matching element can't be+ // dropped (#332; mirrors `filtered_docs_arc`).+ if self.doc_values.array_fields.contains(field.as_str()) {+ return None;+ }if let Some(col) = self.doc_values.keyword.get(field.as_str()) {// Step 2: analyzed-text bailout via the insert-time// cached flag instead of an O(N) per-query column@@ -3331,6 +3380,9 @@ impl FtsMemtable {lte,lt,} => {+ if self.doc_values.array_fields.contains(field.as_str()) {+ return None;+ }let col = self.doc_values.numeric.get(field.as_str())?;cols.push(Col::Num(col, *gte, *gt, *lte, *lt));}diff --git a/engine/crates/xerj-engine/tests/multi_valued_keyword_terms.rs b/engine/crates/xerj-engine/tests/multi_valued_keyword_terms.rsindex 99b8d605a..47a03c82e 100644--- a/engine/crates/xerj-engine/tests/multi_valued_keyword_terms.rs+++ b/engine/crates/xerj-engine/tests/multi_valued_keyword_terms.rs@@ -7,14 +7,30 @@//! `arr.join(" ")`). The keyword analyzer emits its whole input as one token,//! so the segment carried the term `"red blue"` and neither `"red"` nor//! `"blue"` existed as a posting. Every clause that projects to a whole-value-//! `FtsQuery::Term` therefore missed the document once it was flushed —-//! visible in the live engine as `multi_match: {"query": "red"}` returning 0-//! hits while `multi_match: {"query": "red blue"}` returned 1, the exact-//! inverse of Elasticsearch.+//! `FtsQuery::Term` therefore missed the document once it was flushed.//!-//! Every test asserts the hit set is the same BEFORE and AFTER `flush()`:-//! this class of defect is flush-dependent, and a post-flush-only assertion-//! would pass on a build that had simply stopped indexing the field.+//! Measured on `main` at d8be09cf, one doc `{"tags": ["red","blue"]}`, `tags`+//! mapped `keyword` — the exact inverse of Elasticsearch, and the hit set+//! CHANGES at `_flush`:+//!+//! ```text+//! BEFORE flush | term tags=red (first value) -> 1 hit(s)+//! BEFORE flush | term tags=blue (non-first value) -> 0 hit(s)+//! BEFORE flush | term tags='red blue' (joined artefact) -> 0 hit(s)+//! AFTER flush | term tags=red (first value) -> 0 hit(s)+//! AFTER flush | term tags=blue (non-first value) -> 0 hit(s)+//! AFTER flush | term tags='red blue' (joined artefact) -> 1 hit(s)+//! ```+//!+//! The pre-flush half had a second, independent cause: the memtable's+//! single-valued doc-values columns keep only an array's FIRST element, and+//! the fused columnar walk that serves a bare `term` never bailed out on such+//! a field the way its three sibling paths did.+//!+//! Nearly every case below asserts the hit set is the same BEFORE and AFTER+//! `flush()`: this class of defect is flush-dependent, and a post-flush-only+//! assertion would pass on a build that had simply stopped indexing the field.+//! The one deliberate exception is documented at its assertion.use std::collections::BTreeSet;@@ -55,7 +71,9 @@ fn expect(ids: &[&str]) -> BTreeSet<String> {/// * `2` — the single-valued control, `tags: "red"`, `notes: "alpha bravo"`async fn seed(engine: &Engine, name: &str) -> std::sync::Arc<Index> {let mut schema = Schema::empty();- schema.fields.push(FieldConfig::new("body", FieldType::Text));+ schema+ .fields+ .push(FieldConfig::new("body", FieldType::Text));schema.fields.push(FieldConfig::new("notes", FieldType::Text));@@ -158,22 +176,38 @@ async fn joined_array_is_not_a_term() {assert_flush_parity(&idx,- &[- (json!({"term": {"tags": "red blue"}}), &[], "term joined"),- (- json!({"multi_match": {"query": "red blue", "fields": ["tags"]}}),- &[],- "multi_match joined",- ),- ],+ &[(json!({"term": {"tags": "red blue"}}), &[], "term joined")],).await;++ // `multi_match` for the joined string is asserted POST-flush only, and+ // deliberately so. The segment is the side this fix owns, and it is now+ // right: no keyword value equals `"red blue"`, so nothing matches. The+ // memtable answers `{"1","2"}` instead — but NOT because of arrays. The+ // stored-source scan that serves a memtable-resident `multi_match` /+ // `match` whitespace-splits the query and ORs the tokens without ever+ // consulting the mapping, so it treats a `keyword` field as analyzed+ // `text`. Doc 2 carries the SCALAR `tags: "red"` and diverges the same+ // way with no array anywhere in the index, which is what makes this a+ // separate defect rather than an unfinished corner of #332 — filed as+ // #354, whose fix wants its own ES-YAML run.+ idx.flush().await.unwrap();+ assert_eq!(+ ids(+ &idx,+ &json!({"multi_match": {"query": "red blue", "fields": ["tags"]}})+ )+ .await,+ expect(&[]),+ "POST-flush: the joined array must not be reachable as a multi_match term"+ );}/// A phrase must not span two elements of an array — Lucene separates them by/// `position_increment_gap` (100), and so does the segment writer now.-/// Pre-fix the memtable said 0 hits and the flushed segment said 1: the-/// joined string put `bravo` and `charlie` at adjacent positions.+/// Pre-fix BOTH sides said 1 hit for `"bravo charlie"` (measured on d8be09cf):+/// the joined string put `bravo` and `charlie` at adjacent positions in the+/// segment, and the stored-source scan matched the same joined text.#[tokio::test]async fn phrase_does_not_span_array_elements() {let dir = TempDir::new().unwrap();@@ -235,7 +269,10 @@ async fn terms_agg_buckets_every_array_element() {idx.flush().await.unwrap();}let res = idx.search(&parse_request(&body).unwrap()).await.unwrap();- let buckets = res.aggs.as_ref().and_then(|a| a["t"]["buckets"].as_array())+ let buckets = res+ .aggs+ .as_ref()+ .and_then(|a| a["t"]["buckets"].as_array()).cloned().unwrap_or_default();let trimmed: Vec<Value> = buckets@@ -274,3 +311,53 @@ async fn source_round_trips_unchanged() {);}}++/// The MERGE path must index arrays the same way the flush path does.+///+/// It used to carry its own copy of the extraction walk+/// (`index::extract_field_text`, joining with `" "`), so a merged segment+/// reproduced the bug even once a freshly flushed one had stopped having it —+/// a defect that only appears after a second flush plus a merge, which no+/// flush-only test can see. `extract_fts_fields_excluding` now delegates to+/// `memtable::extract_field_values_excluding`, the flush path's own walker.+#[tokio::test]+async fn merged_segments_keep_every_array_element() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ let idx = seed(&engine, "mvk_merge").await;++ // Segment 1: docs 1 and 2.+ idx.flush().await.unwrap();+ // Segment 2: a third doc, so the merge has something to merge.+ idx.index_document(+ Some("3".into()),+ json!({"body": "hello", "tags": ["green", "blue"], "notes": "alpha bravo"}),+ )+ .await+ .unwrap();+ idx.flush().await.unwrap();++ let merged = idx.force_merge(1).await.unwrap();+ assert!(merged >= 1, "force_merge should have merged something");++ assert_eq!(+ ids(&idx, &json!({"term": {"tags": "blue"}})).await,+ expect(&["1", "3"]),+ "MERGED: a non-first array element must still be its own term"+ );+ assert_eq!(+ ids(&idx, &json!({"term": {"tags": "red"}})).await,+ expect(&["1", "2"]),+ "MERGED: the first array element and the scalar control"+ );+ assert_eq!(+ ids(&idx, &json!({"term": {"tags": "red blue"}})).await,+ expect(&[]),+ "MERGED: the joined string must not survive the merge as a term"+ );+ assert_eq!(+ ids(&idx, &json!({"match_phrase": {"notes": "bravo charlie"}})).await,+ expect(&[]),+ "MERGED: the position gap between array elements must survive the merge"+ );+}diff --git a/engine/crates/xerj-fts/src/index.rs b/engine/crates/xerj-fts/src/index.rsindex 1a2046afe..0b3670741 100644--- a/engine/crates/xerj-fts/src/index.rs+++ b/engine/crates/xerj-fts/src/index.rs@@ -659,9 +659,11 @@ fn index_field_values<'a>(let tokens = analyzer.analyze(value);let mut max_position = 0u32;for token in &tokens {- field_data- .postings- .add_occurrence(&token.text, doc_ord, base.saturating_add(token.position));+ field_data.postings.add_occurrence(+ &token.text,+ doc_ord,+ base.saturating_add(token.position),+ );max_position = max_position.max(token.position);}if !tokens.is_empty() {@@ -930,7 +932,8 @@ impl FtsIndexWriter {.map(|(k, v)| (k.clone(), v.config.clone())).collect();- let per_field_vec: Vec<(String, Vec<(u32, &FieldValues)>)> = per_field.into_iter().collect();+ let per_field_vec: Vec<(String, Vec<(u32, &FieldValues)>)> =+ per_field.into_iter().collect();let built: Vec<(String, FieldData)> = per_field_vec.into_par_iter()@@ -1904,6 +1907,90 @@ mod tests {}}+ /// #332 — a `keyword`-analyzed field with N values must produce N terms,+ /// and must NOT produce the space-joined concatenation of them.+ #[test]+ fn keyword_field_indexes_each_value_as_its_own_term() {+ let dir = TempDir::new().unwrap();+ let mut writer = FtsIndexWriter::new(dir.path(), "seg-mv-kw", make_registry());+ writer.configure_field(+ "tags",+ FieldIndexConfig {+ analyzer: "keyword".to_owned(),+ ..Default::default()+ },+ );+ writer.add_document(+ 0,+ &[(+ "tags".to_owned(),+ FieldValues::from(vec!["red".to_owned(), "blue".to_owned()]),+ )]+ .into_iter()+ .collect(),+ );+ writer.finish().unwrap();++ let reader = FtsIndexReader::open(dir.path(), "seg-mv-kw", &["tags"]).unwrap();+ let mut terms = reader.all_terms("tags");+ terms.sort();+ assert_eq!(+ terms,+ vec!["blue".to_owned(), "red".to_owned()],+ "each array element is its own keyword term, and \"red blue\" is not a term"+ );+ // The norm is the SUM over values, as in Lucene: one token each.+ assert_eq!(reader.field_length("tags", 0), Some(2));+ // One (doc, field) pair, however many values it carried.+ assert_eq!(reader.field_stats("tags").unwrap().total_docs, 1);+ }++ /// #332 — consecutive values are separated by `POSITION_INCREMENT_GAP`, so+ /// a phrase cannot straddle the boundary between two array elements.+ #[test]+ fn position_increment_gap_separates_consecutive_values() {+ use crate::postings::PostingsReader;++ let dir = TempDir::new().unwrap();+ let mut writer = FtsIndexWriter::new(dir.path(), "seg-mv-pos", make_registry());+ writer.configure_field(+ "notes",+ FieldIndexConfig {+ analyzer: "whitespace".to_owned(),+ ..Default::default()+ },+ );+ writer.add_document(+ 0,+ &[(+ "notes".to_owned(),+ FieldValues::from(vec!["alpha bravo".to_owned(), "charlie delta".to_owned()]),+ )]+ .into_iter()+ .collect(),+ );+ writer.finish().unwrap();++ let reader = FtsIndexReader::open(dir.path(), "seg-mv-pos", &["notes"]).unwrap();+ let position_of = |term: &str| -> u32 {+ let tp = reader.lookup_term("notes", term).expect("term present");+ let data = reader.postings_data("notes", &tp).expect("postings");+ let mut pr = PostingsReader::new_with_positions(data, tp.doc_frequency, true);+ let p = pr.next().expect("one posting");+ p.positions[0]+ };++ // Value 0 occupies positions 0 and 1.+ assert_eq!(position_of("alpha"), 0);+ assert_eq!(position_of("bravo"), 1);+ // Value 1 restarts one past the previous value, plus the gap.+ assert_eq!(position_of("charlie"), 2 + POSITION_INCREMENT_GAP);+ assert_eq!(position_of("delta"), 3 + POSITION_INCREMENT_GAP);+ // `bravo charlie` is therefore 100 positions apart, not adjacent —+ // no realistic `slop` bridges it.+ assert_eq!(position_of("charlie") - position_of("bravo"), 101);+ }+#[test]fn term_lookup_returns_correct_metadata() {let dir = TempDir::new().unwrap();@@ -2042,8 +2129,14 @@ mod tests {let source_fields = ["source_unsafe", "source_alias"];let mut writer = FtsIndexWriter::new(segment_dir, segment_id, make_registry());let document: HashMap<String, FieldValues> = [- (source_fields[0].to_owned(), FieldValues::from("unsafeneedle")),- (source_fields[1].to_owned(), FieldValues::from("aliasneedle")),+ (+ source_fields[0].to_owned(),+ FieldValues::from("unsafeneedle"),+ ),+ (+ source_fields[1].to_owned(),+ FieldValues::from("aliasneedle"),+ ),].into_iter().collect();@@ -2323,7 +2416,10 @@ mod tests {.iter().enumerate().map(|(index, field)| {- ((*field).to_owned(), FieldValues::One(format!("needle{index}")))+ (+ (*field).to_owned(),+ FieldValues::One(format!("needle{index}")),+ )}).collect();writer.add_document(0, &document);