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): doc-values term prefilters decline analyzed text
Tong-bit-arte589827c3610
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex a880cd5bb..292e888d8 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -23727,6 +23727,13 @@ impl Index {}match &sort_cand {Some(sc) => Some(Arc::new(PrefilterSet::from_set(sc.set.clone()))),+ // An analyzed `text` field's column holds raw+ // values, not tokens: its term set is not a+ // superset of the scan's matches, so decline+ // (`None` → full stored scan, which answers per+ // the pre-flush hit set — see+ // `field_is_analyzed_text`).+ None if field_is_analyzed_text(&dmq_schema, field) => None,None => self.build_term_prefilter_cached(&segments_dir,&seg_id,@@ -23753,6 +23760,10 @@ impl Index {}match &sort_cand {Some(sc) => Some(Arc::new(PrefilterSet::from_set(sc.set.clone()))),+ // Same analyzed-`text` decline as the Term arm+ // above: the column stores raw values, so a set+ // built from it would drop every token-only match.+ None if field_is_analyzed_text(&dmq_schema, field) => None,None => self.build_term_prefilter_cached(&segments_dir,&seg_id,@@ -23778,7 +23789,16 @@ impl Index {// Pure-conjunction bool: parse only the most-selective// conjunct's docs; `doc_matches_query` re-tests the full// bool per admitted doc (superset filter).- self.build_bool_prefilter_cached(&segments_dir, &seg_id, query)+ //+ // A bool carrying a term/terms leaf on an analyzed+ // `text` field has no valid doc-values anchor at all+ // (see `field_is_analyzed_text`) — decline the whole+ // prefilter, the stored scan answers.+ if has_analyzed_text_term_leaf(query, &dmq_schema) {+ None+ } else {+ self.build_bool_prefilter_cached(&segments_dir, &seg_id, query)+ }} else if is_match_all && !deletes_present {// Sorted-DV candidate pruning for field-sorted// match_all: the segment's sorted numeric@@ -27505,6 +27525,17 @@ impl Index {QueryNode::Constant { query, .. } | QueryNode::Boosted { query, .. } => query.as_ref(),_ => query,};+ // Analyzed-text leaves first: every count below is built from+ // doc-values columns, and those are exact only where the column holds+ // what `_search` matches. For a `text` field with doc-values the+ // column holds RAW values while the scan matches TOKENS, so any count+ // derived from it (the Term/Terms arms and the Bool arm's resolver)+ // would drop exactly the token-only matches the pre-flush answer has.+ // Decline the whole shortcut and let the counting scan answer — the+ // same `None` route a field with no column already takes.+ if has_analyzed_text_term_leaf(query, schema) {+ return None;+ }// Bool intersection shortcut — for `bool { must: [Term, Range] }`// (the most common production filter shape) compute the matching// doc-id set per segment via doc-values intersection, no scan.@@ -41430,6 +41461,68 @@ fn declared_field<'a>(schema: &'a Schema, field: &str) -> Option<&'a FieldConfigfind(&schema.fields, &field.split('.').collect::<Vec<_>>())}+/// Is `field` an ANALYZED `text` field in `schema`?+///+/// Such a field's doc-values column — when its mapping asks for one (ES's+/// `mapper.text.doc_values`) — holds the RAW `_source` values, while `_search`+/// resolves a `term`/`terms` leaf against the analyzed token stream+/// (`tokens_contain` in `doc_matches_query_typed` — the answer the memtable+/// gives before any flush). A set built from the column is therefore NOT a+/// superset of the segment's matches, and every consumer that treats it as one+/// (the term/terms prefilters, the doc-values count shortcuts) silently drops+/// the token-only matches once the document flushes. Those paths must decline+/// and let the stored scan answer.+fn field_is_analyzed_text(schema: &Schema, field: &str) -> bool {+ declared_field(schema, field).is_some_and(|f| matches!(f.field_type, FieldType::Text))+}++/// Does `q` carry a `term`/`terms` leaf naming an analyzed `text` field?+///+/// The doc-values shapes [`field_is_analyzed_text`] cannot resolve are+/// declined as a whole when this is true. Mirrors the composite arms of+/// `unsearchable_query_field` so every position a leaf can sit in is walked.+fn has_analyzed_text_term_leaf(q: &QueryNode, schema: &Schema) -> bool {+ match q {+ QueryNode::Term { field, .. } | QueryNode::Terms { field, .. } => {+ field_is_analyzed_text(schema, field)+ }+ QueryNode::Bool {+ must,+ should,+ must_not,+ filter,+ ..+ } => must+ .iter()+ .chain(should)+ .chain(must_not)+ .chain(filter)+ .any(|c| has_analyzed_text_term_leaf(c, schema)),+ QueryNode::Constant { query, .. }+ | QueryNode::Boosted { query, .. }+ | QueryNode::Named { query, .. }+ | QueryNode::Nested { query, .. }+ | QueryNode::FunctionScore { query, .. } => has_analyzed_text_term_leaf(query, schema),+ QueryNode::Pinned { organic, .. } => has_analyzed_text_term_leaf(organic, schema),+ QueryNode::Boosting {+ positive, negative, ..+ } => {+ has_analyzed_text_term_leaf(positive, schema)+ || has_analyzed_text_term_leaf(negative, schema)+ }+ QueryNode::DisMax { queries, .. } => queries+ .iter()+ .any(|c| has_analyzed_text_term_leaf(c, schema)),+ QueryNode::Hybrid { queries, .. } => queries+ .iter()+ .any(|wq| has_analyzed_text_term_leaf(&wq.query, schema)),+ QueryNode::Knn { filter, .. } | QueryNode::SemanticSearch { filter, .. } => filter+ .as_ref()+ .is_some_and(|f| has_analyzed_text_term_leaf(f, schema)),+ _ => false,+ }+}+/// The first field in `q` that the mapping has made completely unsearchable.////// A field is unsearchable when its mapping declares BOTH `"index": false`diff --git a/engine/crates/xerj-engine/tests/text_doc_values_terms_flush_parity.rs b/engine/crates/xerj-engine/tests/text_doc_values_terms_flush_parity.rsnew file mode 100644index 000000000..e68f15cba--- /dev/null+++ b/engine/crates/xerj-engine/tests/text_doc_values_terms_flush_parity.rs@@ -0,0 +1,133 @@+//! Regression tests: `term`/`terms` on an analyzed `text` field whose mapping+//! asks for doc-values (the ES `mapper.text.doc_values` shape) must answer the+//! same question before and after the flush.+//!+//! The memtable scan matches the analyzed token stream+//! (`doc_matches_query_typed`'s `tokens_contain`): `terms {text: ["brown"]}`+//! over "quick brown fox" matches. The flushed segment used to read the+//! doc-values column — which stores the RAW "quick brown fox" — through the+//! term/terms prefilters and the doc-values count shortcut, so the same query+//! returned nothing after `_refresh`, and the count agreed with the wrong+//! answer. A column-derived set is not a superset of token matching, so those+//! paths now decline for analyzed text fields (`field_is_analyzed_text`) and+//! the stored scan answers on both sides.++use std::collections::BTreeSet;+use std::sync::Arc;++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;++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")+}++async fn search(idx: &Index, q: &Value) -> (u64, BTreeSet<String>) {+ let req = parse_request(&json!({ "query": q, "size": 50 })).expect("parse_request");+ let r = idx.search(&req).await.unwrap();+ (r.total.value, r.hits.iter().map(|h| h.id.clone()).collect())+}++async fn count_total(idx: &Index, q: &Value) -> u64 {+ let req = parse_request(&json!({ "query": q, "size": 0, "from": 0 })).expect("parse_request");+ idx.search(&req).await.unwrap().total.value+}++fn set(ids: &[&str]) -> BTreeSet<String> {+ ids.iter().map(|s| s.to_string()).collect()+}++/// The shape the ES `mapper.text.doc_values` preview maps: an analyzed field+/// that also carries doc-values.+fn doc_values_text_schema() -> Schema {+ let mut schema = Schema::empty();+ let mut text = FieldConfig::new("text", FieldType::Text);+ text.options.doc_values = true;+ schema.fields.push(text);+ schema+}++#[tokio::test]+async fn terms_on_text_with_doc_values_is_flush_invariant() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("dvt", doc_values_text_schema()).unwrap();+ let idx: Arc<Index> = engine.get_index("dvt").unwrap();+ for (id, t) in [+ ("d1", "quick brown fox"),+ ("d2", "quick brown fox"),+ ("d3", "lazy dog"),+ ] {+ idx.index_document(Some(id.into()), json!({"text": t}))+ .await+ .unwrap();+ }++ // The token query the memtable answers.+ let token_q = json!({"terms": {"text": ["brown"]}});+ let (pre_total, pre_hits) = search(&idx, &token_q).await;+ assert_eq!(+ pre_hits,+ set(&["d1", "d2"]),+ "pre-flush (memtable) token match"+ );+ assert_eq!(pre_total, 2);+ assert_eq!(count_total(&idx, &token_q).await, 2, "count before flush");++ // The whole-value query both sides agree on.+ let whole_q = json!({"terms": {"text": ["quick brown fox"]}});+ assert_eq!(search(&idx, &whole_q).await.1, set(&["d1", "d2"]));++ idx.flush().await.unwrap();++ // The segment really carries the doc-values column this test is about.+ let seg_dir = dir.path().join("dvt").join("segments");+ let dv_files = std::fs::read_dir(&seg_dir)+ .unwrap()+ .filter_map(|e| e.ok())+ .filter(|e| e.path().extension().is_some_and(|x| x == "dv"))+ .count();+ assert!(+ dv_files >= 1,+ "the mapping must have produced a .dv sidecar for the field"+ );++ let (post_total, post_hits) = search(&idx, &token_q).await;+ assert_eq!(+ post_hits,+ set(&["d1", "d2"]),+ "token match must survive the flush"+ );+ assert_eq!(post_total, pre_total, "hit total changed at flush");+ assert_eq!(+ count_total(&idx, &token_q).await,+ 2,+ "count must not change at flush"+ );+ assert_eq!(+ search(&idx, &whole_q).await,+ (2, set(&["d1", "d2"])),+ "whole-value match must stay"+ );++ // The conjunction lane (bool prefilter) and the `term` shape, which+ // answers by whole value on both sides by design.+ let filtered = json!({"bool": {+ "must": [{"terms": {"text": ["brown"]}}],+ "filter": [{"term": {"text": "quick brown fox"}}],+ }});+ assert_eq!(search(&idx, &filtered).await.1, set(&["d1", "d2"]));+ assert_eq!(count_total(&idx, &filtered).await, 2);+ let term_q = json!({"term": {"text": "brown"}});+ assert_eq!(+ search(&idx, &term_q).await,+ (0, set(&[])),+ "term on text stays whole-value"+ );+}diff --git a/engine/tests/es-compat-yaml/yaml/search/760_text_doc_values_terms_after_refresh.yml b/engine/tests/es-compat-yaml/yaml/search/760_text_doc_values_terms_after_refresh.ymlnew file mode 100644index 000000000..4b89770e0--- /dev/null+++ b/engine/tests/es-compat-yaml/yaml/search/760_text_doc_values_terms_after_refresh.yml@@ -0,0 +1,32 @@+setup:+ - do:+ indices.create:+ index: text_dv_terms+ body:+ mappings:+ properties:+ text:+ type: text+ doc_values: true+ - do:+ bulk:+ refresh: true+ body:+ - '{"index": {"_index": "text_dv_terms", "_id": "1"}}'+ - '{"text": "quick brown fox"}'++---+"terms on an analyzed text field with doc_values matches analyzed tokens after refresh":+ - do:+ search:+ index: text_dv_terms+ body: { query: { terms: { text: [ "brown" ] } } }+ - match: { hits.total.value: 1 }++---+"terms on an analyzed text field with doc_values still matches the whole value":+ - do:+ search:+ index: text_dv_terms+ body: { query: { terms: { text: [ "quick brown fox" ] } } }+ - match: { hits.total.value: 1 }