Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

fix(engine): bail to brute for multi-field suffixes at ANY depth (#120) (#129)

xerj-org1f349f947ff1
diff --git a/engine/crates/xerj-engine/src/fast_aggs.rs b/engine/crates/xerj-engine/src/fast_aggs.rs
index 8348c05c2..94d569902 100644
--- a/engine/crates/xerj-engine/src/fast_aggs.rs
+++ b/engine/crates/xerj-engine/src/fast_aggs.rs
@@ -179,7 +179,8 @@ struct SegEntry {
/// 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
+/// `_source` directly (`extract_array_path_values` 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>`.
///
@@ -202,6 +203,83 @@ impl SegEntry {
}
}
+/// True when `field` is a dotted name this segment cannot resolve to a
+/// column of its own — not even through [`dv_col`]'s `.keyword` fallback —
+/// while some ANCESTOR of it (the name minus one or more trailing
+/// `.<segment>`s) does have a column. That is where the columnar path and
+/// the brute reference part company.
+///
+/// There is more than one brute resolver, and the one a request is actually
+/// measured against depends on which part of the request the name appears
+/// in. They do not agree with each other, so this reports the UNION of the
+/// names any of them resolves and callers BAIL, letting whichever resolver
+/// the request reaches answer it:
+///
+/// * a top-level query filter (and every other `_source` predicate) is
+/// evaluated by `doc_matches_query` → `index.rs::get_field_value`, whose
+/// multi-field fallback RECURSES on the parent
+/// (`get_field_value(source, &field[..idx])`). It therefore strips an
+/// UNBOUNDED number of trailing segments, provided the name it finally
+/// lands on holds a leaf value: `extension.raw.raw`,
+/// `extension.keyword.raw` and `extension.raw.raw.raw` all resolve to
+/// `extension`'s string. Measured, not read off the source — see
+/// `tests/fast_aggs_multifield_suffix.rs`, whose brute leg returns 3 200
+/// for a `term` query on every one of those names.
+/// * an aggregation target and a `filters`/`filter` sub-predicate are
+/// resolved by `aggs::get_nested_field`, which strips exactly ONE trailing
+/// segment, so it resolves `extension.raw` but not `extension.raw.raw`;
+/// * `extract_array_path_values` (aggs.rs, just before `get_nested_field`)
+/// strips `.keyword` only.
+///
+/// [`dv_col`] deliberately strips only `.keyword`, so all of these names
+/// find no column and the fast path treats the segment as holding no such
+/// data: agg targets contribute empty buckets / null metrics and predicates
+/// resolve to `SegPred::Never`, i.e. a filtered panel silently reports a
+/// small plausible number rather than an error.
+///
+/// Resolution is deliberately NOT widened to match any one of them (see the
+/// module contract: the fast path answers only shapes it can prove
+/// byte-identical, and there is no single brute behaviour to be identical
+/// TO). Bailing is correct against all three, because after a bail the
+/// request is answered by the very resolver it would have been measured
+/// against.
+///
+/// Ancestors are probed with a plain `cols.get` rather than [`dv_col`]: the
+/// loop already visits every prefix, so a `.keyword`-stripping probe would
+/// only re-test a prefix the next iteration reaches anyway.
+///
+/// Ancestors are probed against the doc-value columns, and those exist only
+/// for TOP-LEVEL scalar fields: `build_doc_value_columns` (index.rs) iterates
+/// only the top-level keys of `_source`, so a scalar leaf nested under an
+/// object has no column of its own either.
+///
+/// The consequence, stated honestly because an earlier draft of this comment
+/// got it wrong: this predicate closes the MULTI-FIELD-SUFFIX divergence,
+/// where the parent that owns a column is a real top-level field
+/// (`extension.raw.raw` -> `extension`). It does NOT close the general
+/// nested-OBJECT divergence: `geo.city`, a genuine nested value that brute's
+/// `get_field_value` resolves by recursing into the object, has no ancestor
+/// column at any depth, so this returns `false` and the fast path answers it
+/// as empty when brute would not. That is a separate, pre-existing divergence
+/// (it is identical before and after this change — measured `geo.city`
+/// predicate: fast 300 vs brute 11 300 on both), and it is tracked apart from
+/// the suffix problem this function is scoped to. A genuinely absent sub-path
+/// (`geo.missing`) is indistinguishable from a present one here for the same
+/// reason.
+fn dotted_suffix_diverges_from_brute(cols: &super::DocValueMap, field: &str) -> bool {
+ if dv_col(cols, field).is_some() {
+ return false;
+ }
+ let mut rest = field;
+ while let Some((ancestor, _)) = rest.rsplit_once('.') {
+ if cols.get(ancestor).is_some() {
+ return true;
+ }
+ rest = ancestor;
+ }
+ false
+}
+
/// True when `field` is a dotted JSON path (`geo.dest`, `machine.ram`,
/// `machine.os.keyword`) that fast_aggs cannot resolve to any column —
/// neither the exact name nor its `.keyword`-stripped form (see
@@ -219,11 +297,24 @@ impl SegEntry {
/// column for an object/nested field itself, only for its scalar leaves, so
/// "does the dotted path's root resolve as a column" is always false and
/// can't distinguish a genuinely nested path from a genuinely absent one).
+///
+/// It also covers the second, schema-independent case: a multi-field suffix
+/// (of any depth) other than `.keyword` that a brute resolver resolves by
+/// stripping and the columnar path does not — see
+/// [`dotted_suffix_diverges_from_brute`]. That check is per-segment and
+/// runs FIRST, because a name that resolves exactly in one segment but only
+/// via an ancestor in another still diverges on the second segment's rows.
fn field_needs_brute_fallback(
field: &str,
segs: &[SegEntry],
object_fields: &std::collections::HashSet<String>,
) -> bool {
+ if segs
+ .iter()
+ .any(|s| dotted_suffix_diverges_from_brute(&s.cols, field))
+ {
+ return true;
+ }
if segs.iter().any(|s| s.col(field).is_some()) {
return false;
}
@@ -710,9 +801,21 @@ impl<'a> FastCtx<'a> {
/// The column kind of `field` across all segments. `Ok(None)` = the
/// field appears in no segment. Mixed numeric/keyword → `Err` (bail).
+ ///
+ /// `Err` is also returned for a multi-field suffix, at any depth, that a
+ /// brute resolver resolves by stripping and the columnar path does not
+ /// ([`dotted_suffix_diverges_from_brute`]). Every caller already treats
+ /// `Err` as "bail to brute", and every executor that reads a column for
+ /// an agg TARGET gates on this first, so one check here closes the whole
+ /// target surface — including the sites that `continue` past a
+ /// column-less segment (`exec_terms`, `exec_date_histogram`) rather than
+ /// bailing, which is how an aggregation target silently under-returned.
fn seg_field_kind(&self, field: &str) -> std::result::Result<Option<ColKind>, ()> {
let mut kind: Option<ColKind> = None;
for s in &self.segs {
+ if dotted_suffix_diverges_from_brute(&s.cols, field) {
+ return Err(());
+ }
let k = match s.col(field) {
Some(Column::Numeric(_)) => ColKind::Numeric,
Some(Column::Keyword(_)) => ColKind::Keyword,
@@ -2252,6 +2355,13 @@ impl<'a> FastCtx<'a> {
return None;
}
let field = params.get("field").and_then(Value::as_str)?;
+ // Exact-name schema lookup, deliberately (#120): `<bool>.keyword`
+ // resolves its column through `dv_col`'s parent fallback but is NOT
+ // in `bool_fields`, so `is_bool` is false and the `Numeric` arm below
+ // does not match — the request bails to brute. That is a missed
+ // optimisation, not a wrong answer: the keys can only be rendered
+ // "false"/"true" on the arm this gate refuses to take. Normalising
+ // the name here would ADD the wrong-rendering risk, not remove it.
let is_bool = self.bool_fields.contains(field);
match self.seg_field_kind(field) {
Ok(Some(ColKind::Keyword)) | Ok(None) => {}
@@ -2571,6 +2681,13 @@ impl<'a> FastCtx<'a> {
// what licenses rendering them back as "false"/"true" term keys
// (`typed_term_key` then emits key 0/1 + key_as_string, exactly
// like the brute path does for `Value::Bool`).
+ //
+ // The lookup is by EXACT name on purpose (#120): a bool field asked
+ // for as `<field>.keyword` resolves its numeric column via `dv_col`
+ // but is absent from `bool_fields`, so `is_bool` is false, the
+ // `Numeric` arm below does not match, and the request bails to
+ // brute. Slower, never wrong — the "keys render as strings" failure
+ // needs the arm this gate refuses.
let is_bool = self.bool_fields.contains(field);
match self.seg_field_kind(field) {
Ok(Some(ColKind::Keyword)) | Ok(None) => {}
@@ -5084,6 +5201,25 @@ fn compile_pred(filter: &Value) -> Option<Pred> {
}
}
+/// What a missing column means for a predicate on `field`.
+///
+/// `Some(SegPred::Never)` is an ASSERTION that the segment genuinely holds
+/// no matching row. That assertion only holds when EVERY brute resolver
+/// would also find nothing under this name. For a multi-field suffix one
+/// of them resolves by stripping it is false — and the widest of them,
+/// `index.rs::get_field_value` behind a top-level query filter, strips
+/// trailing segments recursively, so `<field>.raw.raw` counts too.
+/// Returning `Never` there is how a `filters`/`filter`/top-level-query
+/// predicate reported a small plausible count instead of the real one.
+/// `None` bails the whole request to the exact brute path.
+fn miss_is_genuinely_empty<'a>(cols: &super::DocValueMap, field: &str) -> Option<SegPred<'a>> {
+ if dotted_suffix_diverges_from_brute(cols, field) {
+ None
+ } else {
+ Some(SegPred::Never)
+ }
+}
+
enum SegPred<'a> {
Never,
Always,
@@ -5106,6 +5242,9 @@ enum SegPred<'a> {
/// 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`.
+///
+/// A miss on a name the brute reference WOULD resolve is therefore not a
+/// `Never` at all — see [`miss_is_genuinely_empty`].
fn resolve_pred<'a>(cols: &'a super::DocValueMap, pred: &Pred) -> Option<SegPred<'a>> {
Some(match pred {
Pred::MatchAll => SegPred::Always,
@@ -5115,7 +5254,7 @@ fn resolve_pred<'a>(cols: &'a super::DocValueMap, pred: &Pred) -> Option<SegPred
None => SegPred::Never,
},
Some(Column::Numeric(_)) => return None,
- None => SegPred::Never,
+ None => miss_is_genuinely_empty(cols, field)?,
},
Pred::TermsKw { field, values } => match dv_col(cols, field) {
Some(Column::Keyword(k)) => {
@@ -5127,7 +5266,7 @@ fn resolve_pred<'a>(cols: &'a super::DocValueMap, pred: &Pred) -> Option<SegPred
}
}
Some(Column::Numeric(_)) => return None,
- None => SegPred::Never,
+ None => miss_is_genuinely_empty(cols, field)?,
},
Pred::RangeKw {
field,
@@ -5187,7 +5326,7 @@ fn resolve_pred<'a>(cols: &'a super::DocValueMap, pred: &Pred) -> Option<SegPred
}
}
Some(Column::Numeric(_)) => return None,
- None => SegPred::Never,
+ None => miss_is_genuinely_empty(cols, field)?,
},
Pred::RangeNum {
field,
@@ -5200,7 +5339,7 @@ fn resolve_pred<'a>(cols: &'a super::DocValueMap, pred: &Pred) -> Option<SegPred
SegPred::Num(n, *lo, *lo_incl, *hi, *hi_incl, n.null_bitmap.is_empty())
}
Some(Column::Keyword(_)) => return None,
- None => SegPred::Never,
+ None => miss_is_genuinely_empty(cols, field)?,
},
Pred::And(subs) => {
let mut resolved: Vec<SegPred<'a>> = Vec::with_capacity(subs.len());
@@ -5566,12 +5705,161 @@ mod range_kw_tests {
seg.col("extension.keyword").is_some(),
"must fall back to the parent column when the exact `.keyword` name has none"
);
+ // Resolution stays narrow on purpose (#120). Widening `dv_col` would
+ // make the fast path CLAIM shapes it cannot prove byte-identical —
+ // key typing, bool rendering and composite key kinds all key off the
+ // requested name — and there is no single brute behaviour to widen
+ // TO: `index.rs::get_field_value` (top-level query filters) strips
+ // trailing segments RECURSIVELY, `aggs::get_nested_field` (agg
+ // targets, `filters` leaves) strips exactly one, and
+ // `extract_array_path_values` (just before it) strips `.keyword`
+ // only. So the
+ // contract is: resolve exactly, and BAIL to brute for anything else,
+ // which is right against all three because after a bail the request
+ // is answered by whichever of them it would have been measured
+ // against. `dotted_suffix_diverges_from_brute` is the other half —
+ // see `multi_field_suffixes_diverge_from_brute_at_any_depth` below.
assert!(
seg.col("extension.nonsense").is_none(),
"must not fall back for suffixes other than `.keyword`"
);
}
+ /// #120: a multi-field suffix resolves on a brute path but not on the
+ /// columnar one, and NOT only at one level of suffixing.
+ /// `index.rs::get_field_value` — the resolver a top-level query filter
+ /// is measured against — recurses on the parent, so it strips trailing
+ /// segments until something leaf-valued answers: `extension.raw.raw`,
+ /// `extension.keyword.raw` and `extension.raw.raw.raw` all read
+ /// `extension`'s string. Every one of those must be reported so callers
+ /// bail, instead of being read as "this segment holds no such data".
+ #[test]
+ fn multi_field_suffixes_diverge_from_brute_at_any_depth() {
+ let k = KeywordColumn::from_iter(vec![Some("css".to_string()), Some("gz".to_string())])
+ .expect("build column");
+ let mut m = std::collections::BTreeMap::new();
+ m.insert("extension".to_string(), Column::Keyword(k));
+ for field in [
+ "extension.raw",
+ "extension.sort",
+ "extension.en",
+ // Doubly and triply suffixed: `get_field_value`'s fallback is
+ // `get_field_value(source, &field[..idx])`, i.e. recursive, so a
+ // bail keyed on the IMMEDIATE parent alone still failed closed
+ // here — the blocker this test exists for.
+ "extension.raw.raw",
+ "extension.keyword.raw",
+ "extension.raw.keyword",
+ "extension.keyword.keyword",
+ "extension.raw.raw.raw",
+ ] {
+ assert!(
+ dotted_suffix_diverges_from_brute(&m, field),
+ "brute resolves `{field}` to the `extension` column; the fast \
+ path cannot, so it must bail rather than report an empty segment"
+ );
+ }
+ assert!(
+ !dotted_suffix_diverges_from_brute(&m, "extension"),
+ "the exact name resolves — nothing to bail for"
+ );
+ assert!(
+ !dotted_suffix_diverges_from_brute(&m, "extension.keyword"),
+ "`.keyword` already resolves through `dv_col`'s parent fallback"
+ );
+ assert!(
+ !dotted_suffix_diverges_from_brute(&m, "group"),
+ "an undotted absent field is a genuine absence"
+ );
+ // The control that stops the fix degenerating into "every dotted
+ // field goes brute". These names are GENUINELY ABSENT — no `nosuchfield`
+ // or `a` value exists — so brute's `get_field_value` recursion finds
+ // nothing too and the fast path's empty answer is correct. This is the
+ // one case where "no ancestor column" and "brute finds nothing" line
+ // up; a PRESENT nested-object value (`geo.city`) also has no ancestor
+ // column but brute DOES resolve it, which is the separate divergence
+ // called out on `dotted_suffix_diverges_from_brute` and not covered
+ // here.
+ for field in ["nosuchfield.raw", "nosuchfield.raw.raw", "a.b.c.d"] {
+ assert!(
+ !dotted_suffix_diverges_from_brute(&m, field),
+ "`{field}` is genuinely absent — brute finds nothing too, so \
+ an empty answer is correct and bailing would be wasted work"
+ );
+ }
+ }
+
+ /// The predicate half: a miss that a brute path WOULD resolve is not a
+ /// `SegPred::Never` (an assertion that the segment matches nothing) but a
+ /// bail. `filters`/`filter`/top-level-query predicates all route through
+ /// `resolve_pred`, so this one gate covers every predicate site.
+ #[test]
+ fn suffixed_predicate_bails_instead_of_matching_nothing() {
+ let k = KeywordColumn::from_iter(vec![Some("css".to_string()), Some("gz".to_string())])
+ .expect("build column");
+ let mut m = std::collections::BTreeMap::new();
+ m.insert("extension".to_string(), Column::Keyword(k));
+ for field in [
+ "extension.raw",
+ "extension.raw.raw",
+ "extension.keyword.raw",
+ "extension.raw.keyword",
+ "extension.raw.raw.raw",
+ ] {
+ let pred = Pred::TermKw {
+ field: field.into(),
+ value: "css".into(),
+ };
+ assert!(
+ resolve_pred(&m, &pred).is_none(),
+ "`{field}` must bail the request to brute, not resolve to Never"
+ );
+ }
+ // Still `Never` (not a bail) where brute genuinely finds nothing.
+ let absent = Pred::TermKw {
+ field: "nosuchfield.raw".into(),
+ value: "css".into(),
+ };
+ assert!(
+ matches!(resolve_pred(&m, &absent), Some(SegPred::Never)),
+ "a genuinely absent dotted field must stay on the fast path as Never"
+ );
+ }
+
+ /// Agg TARGETS bail through `field_needs_brute_fallback` / the
+ /// `seg_field_kind` gate rather than skipping the segment. This asserts
+ /// the first of those; the integration suite
+ /// (`tests/fast_aggs_multifield_suffix.rs`) covers the executors.
+ #[test]
+ fn suffixed_agg_target_needs_brute_fallback() {
+ let build = || {
+ let mut cols = std::collections::BTreeMap::new();
+ cols.insert(
+ "extension".to_string(),
+ Column::Keyword(KeywordColumn::from_iter(vec![Some("css".to_string())]).unwrap()),
+ );
+ seg_with_cols(cols)
+ };
+ for field in [
+ "extension.raw",
+ "extension.raw.raw",
+ "extension.keyword.raw",
+ "extension.raw.raw.raw",
+ ] {
+ assert!(
+ field_needs_brute_fallback(field, &[build()], &object_fields(&[])),
+ "a `terms`/metric target on `{field}` must bail to brute — the \
+ executors `continue` past a column-less segment, so it would \
+ otherwise be built from the memtable alone"
+ );
+ }
+ assert!(
+ !field_needs_brute_fallback("nosuchfield.raw", &[build()], &object_fields(&[])),
+ "a dotted field with no ancestor column anywhere is a genuine \
+ absence and must stay on the fast path"
+ );
+ }
+
fn seg_with_cols(cols: std::collections::BTreeMap<String, Column>) -> SegEntry {
SegEntry {
id: "seg1".to_string(),
diff --git a/engine/crates/xerj-engine/src/graph.rs b/engine/crates/xerj-engine/src/graph.rs
index 386ed7c8e..4ed07d1d3 100644
--- a/engine/crates/xerj-engine/src/graph.rs
+++ b/engine/crates/xerj-engine/src/graph.rs
@@ -150,6 +150,14 @@ pub struct GraphExpandResult {
/// Get a keyword column by name, or `None` when absent or numeric-typed
/// (numeric-typed = a writer violated the §2.2 type discipline; the segment is
/// treated as column-less rather than guessed at).
+///
+/// Raw `cols.get`, with none of `fast_aggs::dv_col`'s multi-field fallback,
+/// on purpose: every call site passes a LITERAL §2.2 envelope name (`src`,
+/// `dst`, `edge_id`, `type`, `weight`, `valid_at`, `invalid_at`). No
+/// user-supplied or mapping-derived field name reaches these lookups, so a
+/// `<field>.keyword` / `<field>.raw` multi-field suffix cannot occur here and
+/// #120's brute-vs-columnar resolution gap does not apply. A miss is also
+/// reported (`segments_without_columns`) rather than silently dropped.
fn kw_col<'a>(cols: &'a super::DocValueMap, name: &str) -> Option<&'a KeywordColumn> {
match cols.get(name) {
Some(Column::Keyword(k)) => Some(k),
diff --git a/engine/crates/xerj-engine/tests/fast_aggs_multifield_suffix.rs b/engine/crates/xerj-engine/tests/fast_aggs_multifield_suffix.rs
new file mode 100644
index 000000000..e2219886b
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/fast_aggs_multifield_suffix.rs
@@ -0,0 +1,550 @@
+//! Regression: multi-field suffixes OTHER than `.keyword` on the columnar
+//! fast path (`<field>.raw`, the classic Logstash multi-field) — at EVERY
+//! depth of suffixing, not just one.
+//!
+//! There is no single "the brute path". Which resolver a name is measured
+//! against depends on where in the request it appears, and they disagree:
+//!
+//! * a top-level query filter runs through `index.rs::get_field_value`,
+//! whose multi-field fallback is RECURSIVE
+//! (`get_field_value(source, &field[..idx])`), so it strips an unbounded
+//! number of trailing segments — `extension.raw.raw`,
+//! `extension.keyword.raw` and `extension.raw.raw.raw` all read
+//! `extension`'s string;
+//! * an agg TARGET and a `filters`/`filter` leaf run through
+//! `aggs::get_nested_field`, which strips exactly ONE segment, so it reads
+//! `extension.raw` but genuinely finds nothing for `extension.raw.raw`.
+//!
+//! Both facts are asserted below against the brute leg itself, not read off
+//! the source. `fast_aggs::dv_col` strips only `.keyword`, so every one of
+//! these names found no column and the columnar path treated the segment as
+//! holding no such data. That is invisible in the response: predicates
+//! resolved to "this segment matches nothing" and aggregation targets simply
+//! skipped the segment, so a panel returned a small plausible number built
+//! from the memtable alone.
+//!
+//! The fix keeps resolution narrow — widening it would make the fast path
+//! claim shapes it cannot prove byte-identical, and per the above there is
+//! no single behaviour to widen TO — and instead BAILS to the brute path
+//! whenever a dotted name misses while ANY ancestor of it has a column.
+//! After a bail the request is answered by whichever resolver it would have
+//! been measured against, so bailing is right against all of them.
+//!
+//! The invariant under test is fast-path/brute-path agreement, not any
+//! particular hardcoded count; the absolute assertions exist only so a
+//! future change that makes BOTH paths return nothing cannot pass.
+
+use serde_json::{json, Value};
+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, `ok` is
+/// the boolean mirror of `group == "a"`.
+/// Memtable: 200 more css/a/1.0/true 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 a = i % 2 == 0;
+ let group = if a { "a" } else { "b" };
+ let v = if a { 1.0 } else { 100.0 };
+ idx.index_document(
+ Some(i.to_string()),
+ json!({
+ "extension": EXTS[(i % 4) as usize],
+ "group": group,
+ "v": v,
+ "ok": a,
+ "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, "ok": true, "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, "ok": true, "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)),
+ })
+}
+
+/// Run `body` twice against an identical corpus — once with the columnar
+/// path live, once with it disabled — and return the brute answer after
+/// asserting the two agree.
+async fn agree(name: &str, body: fn() -> serde_json::Value, why: &str) -> serde_json::Value {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index(name, Schema::empty()).unwrap();
+ let idx = engine.get_index(name).unwrap();
+ seed(&idx).await;
+
+ let fast = run(&idx, body()).await;
+ force_brute(&idx).await;
+ let brute = run(&idx, body()).await;
+
+ assert_eq!(fast, brute, "{why}");
+ brute
+}
+
+fn filters_term_on_raw() -> serde_json::Value {
+ json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": {
+ "by_ext": {
+ "filters": {
+ "filters": {
+ "css": { "term": { "extension.raw": "css" } },
+ "gz": { "term": { "extension.raw": "gz" } }
+ }
+ }
+ }
+ }
+ })
+}
+
+fn filter_terms_on_raw() -> serde_json::Value {
+ json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": {
+ "css_or_gz": {
+ "filter": { "terms": { "extension.raw": ["css", "gz"] } }
+ }
+ }
+ })
+}
+
+fn query_term_on_raw() -> serde_json::Value {
+ json!({
+ "query": { "term": { "group.raw": "b" } },
+ "size": 0,
+ "aggs": { "total_v": { "sum": { "field": "v" } } }
+ })
+}
+
+fn terms_target_on_raw() -> serde_json::Value {
+ json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": { "exts": { "terms": { "field": "extension.raw", "size": 10 } } }
+ })
+}
+
+fn metric_target_on_raw() -> serde_json::Value {
+ json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": { "sum_v": { "sum": { "field": "v.raw" } } }
+ })
+}
+
+fn nested_sub_metric_on_raw() -> serde_json::Value {
+ json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": {
+ "by_group": {
+ "terms": { "field": "group", "size": 10 },
+ "aggs": { "sum_v": { "sum": { "field": "v.raw" } } }
+ }
+ }
+ })
+}
+
+/// `filters` sub-agg whose leaf is a `term` on `<field>.raw` — the
+/// predicate resolver's fail-closed path.
+#[tokio::test]
+async fn fast_and_brute_agree_on_raw_filters_agg() {
+ let brute = agree(
+ "rawfilters",
+ filters_term_on_raw,
+ "columnar fast path disagrees with the brute reference on a \
+ `filters` agg keyed by `<field>.raw`",
+ )
+ .await;
+ assert_eq!(
+ brute["aggs"]["by_ext"]["buckets"]["css"]["doc_count"],
+ 3_200
+ );
+ assert_eq!(brute["aggs"]["by_ext"]["buckets"]["gz"]["doc_count"], 3_000);
+}
+
+/// Single `filter` agg with a `terms` leaf on `<field>.raw`.
+#[tokio::test]
+async fn fast_and_brute_agree_on_raw_filter_terms_agg() {
+ let brute = agree(
+ "rawfilterterms",
+ filter_terms_on_raw,
+ "columnar fast path disagrees with the brute reference on a \
+ `filter` agg with a `terms` leaf on `<field>.raw`",
+ )
+ .await;
+ assert_eq!(brute["aggs"]["css_or_gz"]["doc_count"], 6_200);
+}
+
+/// Top-level query `term` on `<field>.raw` — this one moves `hits.total`,
+/// not just a bucket count.
+#[tokio::test]
+async fn fast_and_brute_agree_on_raw_query_filter() {
+ let brute = agree(
+ "rawquery",
+ query_term_on_raw,
+ "columnar fast path disagrees with the brute reference on a \
+ top-level `term` query against `<field>.raw`",
+ )
+ .await;
+ assert_eq!(brute["total"], 6_000);
+ assert_eq!(brute["aggs"]["total_v"]["value"], 600_000.0);
+}
+
+/// Aggregation TARGET on `<field>.raw`. Broader than the predicate case:
+/// the executors `continue` past a column-less segment instead of bailing,
+/// so the buckets were built from the memtable alone.
+#[tokio::test]
+async fn fast_and_brute_agree_on_raw_terms_target() {
+ let brute = agree(
+ "rawterms",
+ terms_target_on_raw,
+ "columnar fast path disagrees with the brute reference on a \
+ `terms` aggregation TARGETING `<field>.raw`",
+ )
+ .await;
+ let buckets = brute["aggs"]["exts"]["buckets"].as_array().unwrap().clone();
+ let css = buckets
+ .iter()
+ .find(|b| b["key"] == "css")
+ .expect("css bucket");
+ assert_eq!(css["doc_count"], 3_200);
+ assert_eq!(buckets.len(), 4);
+}
+
+/// Numeric metric TARGET on `<field>.raw` — the parent column is
+/// `Column::Numeric`, so this exercises the `RangeNum`/metric side of the
+/// same resolution gap.
+#[tokio::test]
+async fn fast_and_brute_agree_on_raw_metric_target() {
+ let brute = agree(
+ "rawmetric",
+ metric_target_on_raw,
+ "columnar fast path disagrees with the brute reference on a \
+ `sum` metric TARGETING `<field>.raw`",
+ )
+ .await;
+ // 6 000 × 1.0 + 6 000 × 100.0 + 200 × 1.0
+ assert_eq!(brute["aggs"]["sum_v"]["value"], 606_200.0);
+}
+
+/// The same `.raw` metric as a SUB-agg under a columnar `terms` parent:
+/// sub-metric fields are planned in `plan_subs`, a different gate from the
+/// top-level `exec_agg` one.
+#[tokio::test]
+async fn fast_and_brute_agree_on_raw_sub_metric() {
+ let brute = agree(
+ "rawsubmetric",
+ nested_sub_metric_on_raw,
+ "columnar fast path disagrees with the brute reference on a \
+ SUB-agg `sum` metric TARGETING `<field>.raw`",
+ )
+ .await;
+ let buckets = brute["aggs"]["by_group"]["buckets"]
+ .as_array()
+ .unwrap()
+ .clone();
+ let a = buckets.iter().find(|b| b["key"] == "a").expect("a bucket");
+ let b = buckets.iter().find(|b| b["key"] == "b").expect("b bucket");
+ assert_eq!(a["sum_v"]["value"], 6_200.0);
+ assert_eq!(b["sum_v"]["value"], 600_000.0);
+}
+
+/// The related exact-name lookup called out alongside #120:
+/// `FastCtx::bool_fields` is keyed by the schema name, so a boolean field
+/// asked for as `<field>.keyword` resolves its column through `dv_col`'s
+/// parent fallback but is NOT recognised as boolean. It is left exact on
+/// purpose — the numeric-column arm it gates is the only one that could
+/// render `0`/`1` where the brute path renders `false`/`true`, so failing
+/// the gate bails to brute instead. This asserts that outcome directly:
+/// same keys, same `key_as_string`, same counts as the reference.
+#[tokio::test]
+async fn fast_and_brute_agree_on_bool_field_via_keyword_suffix() {
+ let brute = agree(
+ "boolkw",
+ || {
+ json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": { "by_ok": { "terms": { "field": "ok.keyword", "size": 10 } } }
+ })
+ },
+ "columnar fast path disagrees with the brute reference on a `terms` \
+ aggregation over a BOOLEAN field named as `<field>.keyword`",
+ )
+ .await;
+ // Boolean term keys are the numeric 0/1 ordinal plus `key_as_string` —
+ // asserting the exact shape is what proves the field really is
+ // boolean-mapped here, so the agreement above is not vacuous.
+ assert_eq!(
+ brute["aggs"]["by_ok"]["buckets"],
+ json!([
+ { "key": 1, "doc_count": 6_200, "key_as_string": "true" },
+ { "key": 0, "doc_count": 6_000, "key_as_string": "false" },
+ ])
+ );
+}
+
+/// The narrow-resolution half of the contract: a dotted name whose parent
+/// has NO column either is a genuine absence, and both paths must agree it
+/// is empty WITHOUT the fast path bailing. This is what stops the fix from
+/// degenerating into "every dotted field goes brute".
+#[tokio::test]
+async fn genuinely_absent_dotted_field_is_empty_on_both_paths() {
+ let brute = agree(
+ "rawabsent",
+ || {
+ json!({
+ "query": { "term": { "nosuchfield.raw": "css" } },
+ "size": 0,
+ "aggs": { "n": { "value_count": { "field": "v" } } }
+ })
+ },
+ "a dotted field absent from the corpus must read empty on both paths",
+ )
+ .await;
+ assert_eq!(brute["total"], 0);
+}
+
+/// Every multi-field suffix SHAPE, not just the one-segment `.raw` the issue
+/// happened to name.
+///
+/// The resolver a top-level query filter is measured against is
+/// `index.rs::get_field_value`, and its multi-field fallback RECURSES
+/// (`get_field_value(source, &field[..idx])`), so it strips an unbounded
+/// number of trailing segments: `extension.raw.raw` and
+/// `extension.keyword.raw` both resolve to `extension`'s value on the brute
+/// path. A columnar bail keyed on the immediate parent alone therefore
+/// still failed closed for every doubly-suffixed name.
+///
+/// One corpus, one process: run every shape on the columnar path, flip the
+/// index onto the brute path without changing a live value, run them all
+/// again, and compare the two maps whole. Agreement is the invariant; the
+/// absolute assertions below exist only so a change that empties BOTH paths
+/// cannot pass.
+#[tokio::test]
+async fn fast_and_brute_agree_across_multi_field_suffix_shapes() {
+ /// `.raw`/`.sort`/`.en` are real Logstash/ES multi-field conventions;
+ /// the doubled and tripled forms are the shapes an unbounded-strip brute
+ /// resolver still walks and a one-level columnar bail still missed.
+ /// `nosuchfield.raw` is the control: no ancestor column anywhere, so
+ /// BOTH paths must read it as genuinely empty rather than falling back.
+ const SHAPES: [&str; 10] = [
+ "extension",
+ "extension.raw",
+ "extension.keyword",
+ "extension.sort",
+ "extension.en",
+ "extension.raw.raw",
+ "extension.keyword.raw",
+ "extension.raw.keyword",
+ "extension.raw.raw.raw",
+ "nosuchfield.raw",
+ ];
+
+ fn requests(shape: &str) -> Vec<(String, serde_json::Value)> {
+ vec![
+ (
+ format!("{shape}/query-term"),
+ json!({
+ "query": { "term": { shape: "css" } },
+ "size": 0,
+ "aggs": { "n": { "value_count": { "field": "i" } } }
+ }),
+ ),
+ (
+ format!("{shape}/terms-target"),
+ json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": { "by": { "terms": { "field": shape, "size": 10 } } }
+ }),
+ ),
+ (
+ format!("{shape}/filters-predicate"),
+ json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": {
+ "split": {
+ "filters": {
+ "filters": {
+ "css": { "term": { shape: "css" } },
+ "gz": { "terms": { shape: ["gz"] } }
+ }
+ }
+ }
+ }
+ }),
+ ),
+ ]
+ }
+
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine
+ .create_index("suffixshapes", Schema::empty())
+ .unwrap();
+ let idx = engine.get_index("suffixshapes").unwrap();
+ seed(&idx).await;
+
+ let mut fast = serde_json::Map::new();
+ for shape in SHAPES {
+ for (label, body) in requests(shape) {
+ fast.insert(label, run(&idx, body).await);
+ }
+ }
+
+ force_brute(&idx).await;
+
+ let mut brute = serde_json::Map::new();
+ for shape in SHAPES {
+ for (label, body) in requests(shape) {
+ brute.insert(label, run(&idx, body).await);
+ }
+ }
+
+ assert_eq!(
+ Value::Object(fast),
+ Value::Object(brute.clone()),
+ "columnar fast path disagrees with the brute reference on at least one \
+ multi-field suffix shape"
+ );
+
+ // ── Non-vacuity, and the two brute resolvers pinned apart ────────────
+ //
+ // Everything below is asserted against the BRUTE leg, so it is a
+ // measurement of what the reference actually does, not a restatement of
+ // what the fix assumes. Without it, "both paths returned nothing" would
+ // pass the agreement check above.
+
+ // 1. The top-level query filter resolves EVERY suffix depth, because
+ // `get_field_value`'s fallback recurses. 3 000 flushed `css` docs +
+ // 200 in the memtable. This is the assertion that fails on a fix
+ // keyed to the immediate parent only.
+ for shape in SHAPES {
+ if shape == "nosuchfield.raw" {
+ continue;
+ }
+ assert_eq!(
+ brute[&format!("{shape}/query-term")]["total"],
+ 3_200,
+ "the top-level-query resolver must reach `extension` from `{shape}`"
+ );
+ }
+
+ // 2. The agg-side resolver does NOT: `get_nested_field` strips exactly
+ // one segment, so a `filters` leaf or a `terms` target sees the value
+ // for a single suffix and nothing at all for a double one. The fast
+ // path has to match THIS here and the recursive one above, which is
+ // why the fix bails rather than picking one resolution rule.
+ for shape in [
+ "extension",
+ "extension.raw",
+ "extension.keyword",
+ "extension.sort",
+ "extension.en",
+ ] {
+ assert_eq!(
+ brute[&format!("{shape}/filters-predicate")]["aggs"]["split"]["buckets"]["css"]
+ ["doc_count"],
+ 3_200,
+ "the agg-side resolver strips one segment, so `{shape}` must resolve"
+ );
+ assert_eq!(
+ brute[&format!("{shape}/terms-target")]["aggs"]["by"]["buckets"]
+ .as_array()
+ .unwrap()
+ .len(),
+ 4,
+ "`{shape}` must bucket all four extensions on the agg side"
+ );
+ }
+ for shape in [
+ "extension.raw.raw",
+ "extension.keyword.raw",
+ "extension.raw.keyword",
+ "extension.raw.raw.raw",
+ ] {
+ assert_eq!(
+ brute[&format!("{shape}/filters-predicate")]["aggs"]["split"]["buckets"]["css"]
+ ["doc_count"],
+ 0,
+ "the agg-side resolver strips ONE segment only, so `{shape}` must \
+ find nothing there even though the query-filter resolver reaches it"
+ );
+ assert_eq!(
+ brute[&format!("{shape}/terms-target")]["aggs"]["by"]["buckets"],
+ json!([]),
+ "same, for an aggregation TARGET on `{shape}`"
+ );
+ }
+
+ // 3. The absent-field control: empty on both paths, and empty because
+ // nothing resolves it — not because something fell back.
+ assert_eq!(brute["nosuchfield.raw/query-term"]["total"], 0);
+ assert_eq!(
+ brute["nosuchfield.raw/terms-target"]["aggs"]["by"]["buckets"],
+ json!([])
+ );
+ assert_eq!(
+ brute["nosuchfield.raw/filters-predicate"]["aggs"]["split"]["buckets"]["css"]["doc_count"],
+ 0
+ );
+}