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): resolve `<field>.keyword` predicates against the parent column (#114)
xerj-org676e9c6824f7
diff --git a/engine/crates/xerj-engine/src/fast_aggs.rs b/engine/crates/xerj-engine/src/fast_aggs.rsindex b990eafb4..c81643406 100644--- a/engine/crates/xerj-engine/src/fast_aggs.rs+++ b/engine/crates/xerj-engine/src/fast_aggs.rs@@ -174,22 +174,31 @@ struct SegEntry {docs: u32,}+/// Look up a doc-value column for `field`, falling back to the `.keyword`+/// multi-field's parent name when the exact field has no column of its own.+/// A text field's auto-created `.keyword` multi-field shares the *same*+/// physical column, stored under the parent's name — this mirrors the+/// identical `.keyword` fallback the brute-force path applies when walking+/// `_source` directly (`flatten_to_strings` in `aggs.rs`). Without it, every+/// fast-path reference to `<field>.keyword` silently sees no column at all,+/// even though the data is right there under `<field>`.+///+/// EVERY column lookup on the fast path goes through here — both agg+/// *targets* (`SegEntry::col`) and query/filter *predicates*+/// (`resolve_pred`). Keeping one implementation is the point: the two used+/// to resolve names differently, and the predicate side failed CLOSED+/// (missing column ⇒ "this segment matches nothing"), so a filtered panel+/// on `<field>.keyword` returned a small plausible number instead of an+/// error while the unfiltered one next to it was correct.+fn dv_col<'a>(cols: &'a super::DocValueMap, field: &str) -> Option<&'a Column> {+ cols.get(field)+ .or_else(|| field.strip_suffix(".keyword").and_then(|p| cols.get(p)))+}+impl SegEntry {- /// Look up this segment's doc-value column for `field`, falling back to- /// the `.keyword` multi-field's parent name when the exact field has no- /// column of its own. A text field's auto-created `.keyword` multi-field- /// shares the *same* physical column, stored under the parent's name —- /// mirrors the identical `.keyword` fallback the brute-force path- /// applies when walking `_source` directly (`flatten_to_strings` in- /// `aggs.rs`). Without this, every fast-path aggregation on a- /// `<field>.keyword` reference silently sees no column at all and- /// returns empty, even though the data is right there under `<field>`.+ /// This segment's doc-value column for `field` — see [`dv_col`].fn col(&self, field: &str) -> Option<&Column> {- self.cols.get(field).or_else(|| {- field- .strip_suffix(".keyword")- .and_then(|p| self.cols.get(p))- })+ dv_col(&self.cols, field)}}@@ -5039,13 +5048,18 @@ enum SegPred<'a> {And(Vec<SegPred<'a>>),}-fn resolve_pred<'a>(- cols: &'a std::collections::BTreeMap<String, Column>,- pred: &Pred,-) -> Option<SegPred<'a>> {+/// Columnarise `pred` against one segment's doc-values.+///+/// `None` means "this shape is not reproducible columnarly" and bails the+/// whole request to the exact brute path. A resolved `SegPred::Never`, by+/// contrast, is an assertion that the segment genuinely holds no matching+/// row — so every column lookup here MUST use [`dv_col`]'s `.keyword`+/// fallback. Resolving the name differently from the agg targets is what+/// turned a `<field>.keyword` filter into a silent segment-wide `Never`.+fn resolve_pred<'a>(cols: &'a super::DocValueMap, pred: &Pred) -> Option<SegPred<'a>> {Some(match pred {Pred::MatchAll => SegPred::Always,- Pred::TermKw { field, value } => match cols.get(field) {+ Pred::TermKw { field, value } => match dv_col(cols, field) {Some(Column::Keyword(k)) => match k.ord_for_term(value) {Some(ord) => SegPred::KwEq(k, ord, k.null_bitmap.is_empty()),None => SegPred::Never,@@ -5053,7 +5067,7 @@ fn resolve_pred<'a>(Some(Column::Numeric(_)) => return None,None => SegPred::Never,},- Pred::TermsKw { field, values } => match cols.get(field) {+ Pred::TermsKw { field, values } => match dv_col(cols, field) {Some(Column::Keyword(k)) => {let ords: Vec<u32> = values.iter().filter_map(|v| k.ord_for_term(v)).collect();if ords.is_empty() {@@ -5071,7 +5085,7 @@ fn resolve_pred<'a>(lo_incl,hi,hi_incl,- } => match cols.get(field) {+ } => match dv_col(cols, field) {Some(Column::Keyword(k)) => {let terms = &k.terms;if terms.is_empty() {@@ -5131,7 +5145,7 @@ fn resolve_pred<'a>(lo_incl,hi,hi_incl,- } => match cols.get(field) {+ } => match dv_col(cols, field) {Some(Column::Numeric(n)) => {SegPred::Num(n, *lo, *lo_incl, *hi, *hi_incl, n.null_bitmap.is_empty())}@@ -5734,4 +5748,135 @@ mod range_kw_tests {let p = rng(Some(&ts(2, 0)), true, None, true);assert!(resolve_pred(&m, &p).is_none());}++ /// Regression: the *predicate* resolver must apply the same `.keyword`+ /// fallback as the agg targets do.+ ///+ /// `SegEntry::col` gained the fallback while the four lookups inside+ /// `resolve_pred` kept a raw map probe, and a miss there resolves to+ /// `SegPred::Never` — an assertion that the segment holds no matching+ /// row. So a filter on `<field>.keyword` matched nothing in any flushed+ /// segment while the memtable arm matched correctly: not an error, just+ /// a small wrong number (measured: `filters` on `extension.keyword`+ /// reported the 200 memtable docs out of 3 200, and a top-level+ /// `term group.keyword=b` query reported 0 hits out of 6 000).+ ///+ /// Every predicate variant that carries a field name is covered, since+ /// each one owned its own copy of the lookup.+ #[test]+ fn resolve_pred_falls_back_to_keyword_multi_field_parent() {+ use xerj_storage::doc_values::NumericColumn;+ let mut m = std::collections::BTreeMap::new();+ // Two docs under the parent name `extension` — exactly how a+ // flushed segment stores a text field's `.keyword` multi-field.+ m.insert(+ "extension".to_string(),+ Column::Keyword(+ // Equal-width terms: `Pred::RangeKw` refuses a ragged+ // dictionary outright (see `ragged_dictionary_bails_to_brute`),+ // and this fixture must reach the lookup, not that gate.+ KeywordColumn::from_iter(vec![Some("css".to_string()), Some("zip".to_string())])+ .expect("build column"),+ ),+ );+ m.insert(+ "v".to_string(),+ Column::Numeric(NumericColumn::from_iter(+ [1.0f64, 2.0].iter().map(|f| Some(f.to_bits() as i64)),+ )),+ );++ let cases: Vec<(&str, Pred, Pred, u64)> = vec![+ (+ "term",+ Pred::TermKw {+ field: "extension".into(),+ value: "css".into(),+ },+ Pred::TermKw {+ field: "extension.keyword".into(),+ value: "css".into(),+ },+ 1,+ ),+ (+ "terms",+ Pred::TermsKw {+ field: "extension".into(),+ values: vec!["css".into(), "zip".into()],+ },+ Pred::TermsKw {+ field: "extension.keyword".into(),+ values: vec!["css".into(), "zip".into()],+ },+ 2,+ ),+ (+ "keyword range",+ Pred::RangeKw {+ field: "extension".into(),+ lo: Some("css".into()),+ lo_incl: true,+ hi: None,+ hi_incl: true,+ },+ Pred::RangeKw {+ field: "extension.keyword".into(),+ lo: Some("css".into()),+ lo_incl: true,+ hi: None,+ hi_incl: true,+ },+ 2,+ ),+ (+ "numeric range",+ Pred::RangeNum {+ field: "v".into(),+ lo: 2.0,+ lo_incl: true,+ hi: f64::INFINITY,+ hi_incl: true,+ },+ Pred::RangeNum {+ field: "v.keyword".into(),+ lo: 2.0,+ lo_incl: true,+ hi: f64::INFINITY,+ hi_incl: true,+ },+ 1,+ ),+ ];++ for (what, parent, suffixed, expect) in cases {+ assert_eq!(+ count(&parent, &m, 2),+ expect,+ "{what}: parent-name baseline"+ );+ assert_eq!(+ count(&suffixed, &m, 2),+ expect,+ "{what} on `<field>.keyword` must resolve against the parent's \+ column, not fail closed to `Never`"+ );+ }+ }++ /// The fallback must not paper over a genuinely absent field: a+ /// predicate on a column this segment simply does not have still+ /// resolves to `Never` (correct — no row can match).+ #[test]+ fn resolve_pred_still_never_matches_an_absent_field() {+ let c = cols();+ let p = Pred::TermKw {+ field: "nope.keyword".into(),+ value: "x".into(),+ };+ assert!(matches!(+ resolve_pred(&c, &p).expect("resolvable"),+ SegPred::Never+ ));+ }}diff --git a/engine/crates/xerj-engine/tests/fast_aggs_keyword_predicates.rs b/engine/crates/xerj-engine/tests/fast_aggs_keyword_predicates.rsnew file mode 100644index 000000000..1f5c198da--- /dev/null+++ b/engine/crates/xerj-engine/tests/fast_aggs_keyword_predicates.rs@@ -0,0 +1,161 @@+//! Regression: `<field>.keyword` predicates on the columnar fast path.+//!+//! A text field's auto-created `.keyword` multi-field shares the *same*+//! physical doc-values column, stored under the parent's unsuffixed name.+//! Aggregation *targets* learned to fall back from `x.keyword` to `x`, but+//! the predicate resolver did not: it looked the exact name up in the+//! column map and, on a miss, resolved the whole predicate to "matches+//! nothing in this segment". Failing closed like that is invisible — the+//! memtable arm resolves `.keyword` correctly, so a filtered panel returns+//! a small, plausible, wrong number instead of an error.+//!+//! The invariant under test is fast-path/brute-path agreement, not any+//! particular hardcoded count: the brute `_source` path is the reference+//! implementation for every agg shape.++use serde_json::json;+use tempfile::TempDir;+use xerj_common::config::Config;+use xerj_common::types::Schema;+use xerj_engine::Engine;+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")+}++/// 12 000 flushed docs + 200 still in the memtable — past+/// `FAST_AGG_MIN_DOCS` (10 000), so the columnar path is the one under+/// test, and split across both arms so a segment-only defect cannot hide+/// behind a correct memtable answer.+///+/// Flushed: `extension` cycles css/gz/zip/php (3 000 each), `group`+/// alternates a/b (6 000 each), `v` is 1.0 for a and 100.0 for b.+/// Memtable: 200 more css/a/1.0 docs, so the two arms disagree on every+/// bucket and any arm that silently contributes zero is visible.+async fn seed(idx: &std::sync::Arc<xerj_engine::Index>) {+ const EXTS: [&str; 4] = ["css", "gz", "zip", "php"];+ for i in 0..12_000u32 {+ let group = if i % 2 == 0 { "a" } else { "b" };+ let v = if i % 2 == 0 { 1.0 } else { 100.0 };+ idx.index_document(+ Some(i.to_string()),+ json!({ "extension": EXTS[(i % 4) as usize], "group": group, "v": v, "i": i }),+ )+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();+ for i in 12_000..12_200u32 {+ idx.index_document(+ Some(i.to_string()),+ json!({ "extension": "css", "group": "a", "v": 1.0, "i": i }),+ )+ .await+ .unwrap();+ }+}++/// Force every subsequent agg request onto the brute `_source` path+/// WITHOUT changing a single live value: re-index one existing doc with a+/// byte-identical body. That records an overwrite in the version map, and+/// `ghost_events() > 0` is exactly the gate `try_fast_aggs` bails on. The+/// live corpus is unchanged, so the brute answer is the reference answer+/// for the same data the fast path just aggregated.+///+/// (The `XERJ_DISABLE_FAST_AGGS=1` kill switch is memoised in a process-wide+/// `OnceLock`, so it cannot be flipped mid-process to get the same effect.)+async fn force_brute(idx: &std::sync::Arc<xerj_engine::Index>) {+ idx.index_document(+ Some("0".to_string()),+ json!({ "extension": "css", "group": "a", "v": 1.0, "i": 0 }),+ )+ .await+ .unwrap();+}++async fn run(+ idx: &std::sync::Arc<xerj_engine::Index>,+ body: serde_json::Value,+) -> serde_json::Value {+ let req = parse_request(&body).unwrap();+ let res = idx.search(&req).await.unwrap();+ json!({+ "total": res.total.value,+ "aggs": res.aggs.clone().unwrap_or(json!(null)),+ })+}++fn filters_on_keyword() -> serde_json::Value {+ json!({+ "query": { "match_all": {} },+ "size": 0,+ "aggs": {+ "by_ext": {+ "filters": {+ "filters": {+ "css": { "term": { "extension.keyword": "css" } },+ "gz": { "term": { "extension.keyword": "gz" } }+ }+ }+ }+ }+ })+}++fn query_term_on_keyword() -> serde_json::Value {+ json!({+ "query": { "term": { "group.keyword": "b" } },+ "size": 0,+ "aggs": { "total_v": { "sum": { "field": "v" } } }+ })+}++#[tokio::test]+async fn fast_and_brute_agree_on_keyword_filters_agg() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("kwfilters", Schema::empty()).unwrap();+ let idx = engine.get_index("kwfilters").unwrap();+ seed(&idx).await;++ let fast = run(&idx, filters_on_keyword()).await;+ force_brute(&idx).await;+ let brute = run(&idx, filters_on_keyword()).await;++ assert_eq!(+ fast, brute,+ "columnar fast path disagrees with the brute reference on a \+ `filters` agg keyed by `<field>.keyword`"+ );+ // Sanity: the fixture must actually exercise both arms, so a future+ // change that makes BOTH paths return zero cannot pass this test.+ assert_eq!(+ brute["aggs"]["by_ext"]["buckets"]["css"]["doc_count"],+ 3_200+ );+ assert_eq!(brute["aggs"]["by_ext"]["buckets"]["gz"]["doc_count"], 3_000);+}++#[tokio::test]+async fn fast_and_brute_agree_on_keyword_query_filter() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("kwquery", Schema::empty()).unwrap();+ let idx = engine.get_index("kwquery").unwrap();+ seed(&idx).await;++ let fast = run(&idx, query_term_on_keyword()).await;+ force_brute(&idx).await;+ let brute = run(&idx, query_term_on_keyword()).await;++ assert_eq!(+ fast, brute,+ "columnar fast path disagrees with the brute reference on a \+ top-level `term` query against `<field>.keyword`"+ );+ assert_eq!(brute["total"], 6_000);+ assert_eq!(brute["aggs"]["total_v"]["value"], 600_000.0);+}