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): judge columnar coverage per segment, not across the set (#143) (#151)

xerj-org42ed9f7fb8c8
diff --git a/engine/crates/xerj-engine/src/fast_aggs.rs b/engine/crates/xerj-engine/src/fast_aggs.rs
index d4d2cf822..df4308674 100644
--- a/engine/crates/xerj-engine/src/fast_aggs.rs
+++ b/engine/crates/xerj-engine/src/fast_aggs.rs
@@ -278,12 +278,16 @@ fn dotted_suffix_diverges_from_brute(cols: &super::DocValueMap, field: &str) ->
false
}
-/// True when `field` is a name fast_aggs cannot resolve to any column at any
-/// depth — neither the exact name nor its `.keyword`-stripped form (see
-/// `SegEntry::col`) in any segment — yet brute's `get_field_value` still
-/// resolves it, so answering it columnarly would report empty where brute
-/// reports data. A free function (not a `FastCtx` method) so it's testable
-/// without constructing a full `FastCtx`, which needs a real `&Index`.
+/// True when `field` is a name fast_aggs cannot resolve to a column —
+/// neither the exact name nor its `.keyword`-stripped form (see
+/// `SegEntry::col`) — in EVERY flushed segment, yet brute's
+/// `get_field_value` still resolves it, so answering it columnarly would
+/// drop data brute reports. Coverage is judged per segment (#143): the
+/// executors `continue` past a column-less segment, so a single segment
+/// missing the column already loses that segment's docs even when every
+/// other segment carries it. A free function (not a `FastCtx` method) so
+/// it's testable without constructing a full `FastCtx`, which needs a real
+/// `&Index`.
///
/// Three ways brute out-resolves the columnar path, all bailed here:
///
@@ -300,7 +304,11 @@ fn dotted_suffix_diverges_from_brute(cols: &super::DocValueMap, field: &str) ->
/// (`tags` / `tags.raw`): `build_doc_value_columns` ships NO column for an
/// array-poisoned field, so brute reads the `_source` array while the
/// columnar path sees no column — indistinguishable at the column level
-/// from a genuine absence, hence the schema check below.
+/// from a genuine absence, hence the schema check below. Suppression is
+/// decided per segment, so the same field can be covered in one segment
+/// and suppressed in the next (scalar docs flushed first, array docs
+/// later); partial coverage must bail exactly like total absence, which
+/// is why the coverage check demands ALL segments, not ANY.
///
/// `mapped_fields` — see `FastCtx::mapped_fields` — is the schema signal that
/// separates those last two (present-but-uncolumned) from a genuine absence:
@@ -317,15 +325,25 @@ fn field_needs_brute_fallback(
{
return true;
}
- if segs.iter().any(|s| s.col(field).is_some()) {
+ // Column coverage must be judged PER SEGMENT (#143): array-suppression
+ // in `build_doc_value_columns` drops a column for exactly the segments
+ // whose docs hold arrays under the field, so one scalar-only segment
+ // carrying the column proves nothing about the others — the executors
+ // `continue` past a column-less segment, silently dropping its docs.
+ // Only full coverage keeps the fast path; the earlier "ANY segment has
+ // it" check was the undercount.
+ if !segs.is_empty() && segs.iter().all(|s| s.col(field).is_some()) {
return false;
}
- // No column at any depth in any segment. Bail iff brute would still
- // resolve it — i.e. the exact name (a suppressed top-level array such as
- // `tags`, or a flat dotted field name) or, for a dotted path, its
- // top-level root (`geo` for `geo.city`, `tags` for `tags.raw`) is a
- // field the schema maps. A name whose root is unmapped is genuinely
- // absent and stays on the fast path as a real empty result.
+ // The column is missing from at least one segment. Bail iff brute would
+ // still resolve the name — i.e. the exact name (a suppressed top-level
+ // array such as `tags`, or a flat dotted field name) or, for a dotted
+ // path, its top-level root (`geo` for `geo.city`, `tags` for `tags.raw`)
+ // is a field the schema maps: at the column level a per-segment
+ // suppression is indistinguishable from the field being absent from that
+ // segment's docs, and only the suppressed case has data for brute to
+ // find. A name whose root is unmapped is genuinely absent everywhere and
+ // stays on the fast path as a real empty result.
let root = field.split_once('.').map_or(field, |(r, _)| r);
mapped_fields.contains(field) || mapped_fields.contains(root)
}
@@ -814,20 +832,25 @@ 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.
+ /// `Err` is also returned for any name [`field_needs_brute_fallback`]
+ /// flags — a multi-field suffix a brute resolver strips, a nested-object
+ /// leaf, or a mapped field whose column is missing from one or more
+ /// segments (per-segment array suppression, #143). 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`, the
+ /// sub-metric fold) rather than bailing, which is how an aggregation
+ /// target silently under-returned. That matters for the field names
+ /// `exec_agg`'s own `params["field"]` gate never sees: sub-metric fields
+ /// (`plan_subs`), `top_hits` sort fields, `matrix_stats` `fields` and
+ /// composite `sources` all reach columns only through here.
fn seg_field_kind(&self, field: &str) -> std::result::Result<Option<ColKind>, ()> {
+ if field_needs_brute_fallback(field, &self.segs, self.mapped_fields) {
+ return Err(());
+ }
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,
@@ -6048,6 +6071,86 @@ mod range_kw_tests {
));
}
+ /// #143: array suppression is PER-SEGMENT — `build_doc_value_columns`
+ /// drops the column for exactly the segments whose docs hold arrays under
+ /// the field — so a scalar-only segment carrying the column proves
+ /// nothing about the others. The executors `continue` past a column-less
+ /// segment, so anything short of FULL coverage must bail: the old
+ /// "ANY segment has it" check silently dropped the suppressed segment's
+ /// docs from terms buckets, predicates and metric folds.
+ #[test]
+ fn mixed_segment_suppressed_field_needs_fallback() {
+ let covered = || {
+ let mut cols = std::collections::BTreeMap::new();
+ cols.insert(
+ "tags".to_string(),
+ Column::Keyword(KeywordColumn::from_iter(vec![Some("a".to_string())]).unwrap()),
+ );
+ cols.insert(
+ "score".to_string(),
+ Column::Numeric(NumericColumn::from_iter(vec![Some(
+ 5.0_f64.to_bits() as i64
+ )])),
+ );
+ seg_with_cols(cols)
+ };
+ let suppressed = || seg_with_cols(std::collections::BTreeMap::new());
+ let mapped = mapped_fields(&["tags", "score"]);
+ // `tags.keyword` resolves through `dv_col`'s parent fallback in the
+ // covered segment but not in the suppressed one, so it must bail the
+ // same way the flat name does; `score` is the numeric-metric analogue.
+ for field in ["tags", "tags.keyword", "score"] {
+ assert!(
+ field_needs_brute_fallback(field, &[covered(), suppressed()], &mapped),
+ "`{field}` has no column in ONE segment while that segment's \
+ docs still exist — a single covered segment must not veto \
+ the bail"
+ );
+ }
+ // Controls, both sides of the line:
+ // full coverage stays fast — this is the common all-scalar corpus and
+ // the perf-preserving half of the fix;
+ assert!(
+ !field_needs_brute_fallback("tags", &[covered(), covered()], &mapped),
+ "a column present in EVERY segment needs no fallback"
+ );
+ // and an UNMAPPED name missing from a segment is a genuine absence
+ // (never indexed — dynamic mapping would have mapped it), so it stays
+ // on the fast path as a real empty result rather than paying brute.
+ assert!(
+ !field_needs_brute_fallback("unmapped", &[covered(), suppressed()], &mapped),
+ "an unmapped name is genuinely absent — partial coverage of OTHER \
+ fields must not send it to brute"
+ );
+ }
+
+ /// The predicate half of #143: resolving a term predicate against the
+ /// SUPPRESSED segment's columns must bail the request (`None`), not
+ /// assert `SegPred::Never` — that segment's `_source` arrays hold rows
+ /// brute matches.
+ #[test]
+ fn mixed_segment_suppressed_predicate_bails_instead_of_matching_nothing() {
+ let mut cols = std::collections::BTreeMap::new();
+ cols.insert(
+ "tags".to_string(),
+ Column::Keyword(KeywordColumn::from_iter(vec![Some("a".to_string())]).unwrap()),
+ );
+ let segs = vec![
+ seg_with_cols(cols),
+ seg_with_cols(std::collections::BTreeMap::new()),
+ ];
+ let mapped = mapped_fields(&["tags"]);
+ let pred = Pred::TermKw {
+ field: "tags".into(),
+ value: "b".into(),
+ };
+ assert!(
+ resolve_pred(&segs[1].cols, &pred, &segs, &mapped).is_none(),
+ "the suppressed segment's rows can match `tags:b` — the miss must \
+ bail to brute, not resolve to Never"
+ );
+ }
+
/// The already-fixed `.keyword` multi-field case (`extension.keyword`)
/// must NOT be flagged — `SegEntry::col` already resolves it via the
/// `.keyword`-stripped fallback (the physical-column check short-circuits
diff --git a/engine/crates/xerj-engine/tests/fast_aggs_mixed_segment_suppression.rs b/engine/crates/xerj-engine/tests/fast_aggs_mixed_segment_suppression.rs
new file mode 100644
index 000000000..9e35c7cb7
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/fast_aggs_mixed_segment_suppression.rs
@@ -0,0 +1,268 @@
+//! Regression (#143): doc-value array-suppression is PER-SEGMENT, but the
+//! columnar fast path's bail predicate treated it as whole-index.
+//!
+//! `build_doc_value_columns` drops a field's column for a segment when ANY
+//! doc of THAT segment holds an array under the field — no column beats a
+//! lying one — while the segment's docs still exist. The fast path's
+//! `field_needs_brute_fallback` only bailed when NO segment carried the
+//! column: one scalar-only segment vetoed the bail for the whole set, and
+//! every executor then did `let Some(col) = seg.col(field) else { continue }`
+//! — silently SKIPPING the suppressed segment's docs. A terms agg lost
+//! whole buckets, a term predicate resolved to "matches nothing" for rows
+//! that match, and numeric metrics folded only the scalar segment.
+//!
+//! The shape is completely ordinary: index scalar docs, flush, then index
+//! docs where the same field is an array — the first segment has the column,
+//! the second doesn't, and the second's docs vanish from every columnar
+//! answer while `hits.total` still counts 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;
+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")
+}
+
+/// 11 000 scalar docs flushed as one segment, then 1 000 array docs flushed
+/// as a second — past `FAST_AGG_MIN_DOCS` (10 000), so the columnar path is
+/// the one under test. Segment 1's docs are scalar everywhere, so it KEEPS
+/// its `tags`/`score` columns; segment 2's docs hold arrays under both, so
+/// its columns are suppressed at build time. `group` stays scalar in every
+/// doc of both segments — a fully-covered column, so a `terms` parent on it
+/// still runs columnar and its sub-metrics are the ones on trial.
+async fn seed(idx: &std::sync::Arc<xerj_engine::Index>) {
+ for i in 0..11_000u32 {
+ idx.index_document(
+ Some(i.to_string()),
+ json!({
+ "tags": "a",
+ "score": 5,
+ "group": if i % 2 == 0 { "g1" } else { "g2" },
+ "i": i,
+ }),
+ )
+ .await
+ .unwrap();
+ }
+ idx.flush().await.unwrap();
+ for i in 11_000..12_000u32 {
+ idx.index_document(
+ Some(i.to_string()),
+ json!({
+ "tags": ["b", "c"],
+ "score": [1, 2],
+ "group": if i % 2 == 0 { "g1" } else { "g2" },
+ "i": i,
+ }),
+ )
+ .await
+ .unwrap();
+ }
+ idx.flush().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.
+async fn force_brute(idx: &std::sync::Arc<xerj_engine::Index>) {
+ idx.index_document(
+ Some("0".to_string()),
+ json!({ "tags": "a", "score": 5, "group": "g1", "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
+}
+
+/// Terms agg TARGETING the mixed-suppression field: the executor skipped
+/// the suppressed segment, so the `b`/`c` buckets vanished entirely and
+/// `a` was the only bucket left.
+#[tokio::test]
+async fn fast_and_brute_agree_on_mixed_segment_terms_agg() {
+ let brute = agree(
+ "mixterms",
+ || {
+ json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": { "by_tag": { "terms": { "field": "tags", "size": 10 } } }
+ })
+ },
+ "columnar fast path disagrees with the brute reference on a `terms` \
+ agg over a field whose column is suppressed in ONE segment only",
+ )
+ .await;
+ let buckets = brute["aggs"]["by_tag"]["buckets"].as_array().unwrap();
+ assert_eq!(buckets.len(), 3, "a, b and c must all bucket");
+ let count = |key: &str| {
+ buckets
+ .iter()
+ .find(|b| b["key"] == key)
+ .unwrap_or_else(|| panic!("{key} bucket"))["doc_count"]
+ .clone()
+ };
+ assert_eq!(count("a"), 11_000);
+ assert_eq!(count("b"), 1_000);
+ assert_eq!(count("c"), 1_000);
+}
+
+/// Top-level `term` query on a value that lives ONLY in the suppressed
+/// segment: the predicate resolved the column miss to "this segment matches
+/// nothing", so `hits.total` read 0 where brute reads 1 000.
+#[tokio::test]
+async fn fast_and_brute_agree_on_mixed_segment_term_query() {
+ let brute = agree(
+ "mixquery",
+ || {
+ json!({
+ "query": { "term": { "tags": "b" } },
+ "size": 0,
+ "aggs": { "n": { "value_count": { "field": "i" } } }
+ })
+ },
+ "columnar fast path disagrees with the brute reference on a top-level \
+ `term` query hitting only the suppressed segment's rows",
+ )
+ .await;
+ assert_eq!(brute["total"], 1_000);
+}
+
+/// The same predicate via a `filters` agg leaf — the other resolve_pred
+/// consumer, where the miscount hid inside a bucket instead of `hits.total`.
+#[tokio::test]
+async fn fast_and_brute_agree_on_mixed_segment_filters_predicate() {
+ let brute = agree(
+ "mixfilters",
+ || {
+ json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": {
+ "split": {
+ "filters": {
+ "filters": {
+ "b": { "term": { "tags": "b" } },
+ "a": { "term": { "tags": "a" } }
+ }
+ }
+ }
+ }
+ })
+ },
+ "columnar fast path disagrees with the brute reference on a `filters` \
+ agg leaf hitting only the suppressed segment's rows",
+ )
+ .await;
+ assert_eq!(brute["aggs"]["split"]["buckets"]["b"]["doc_count"], 1_000);
+ assert_eq!(brute["aggs"]["split"]["buckets"]["a"]["doc_count"], 11_000);
+}
+
+/// Numeric metrics TARGETING the mixed-suppression field: the fold skipped
+/// the suppressed segment, so avg/sum/value_count reported the scalar
+/// segment's statistics as the whole index's.
+#[tokio::test]
+async fn fast_and_brute_agree_on_mixed_segment_numeric_metrics() {
+ let brute = agree(
+ "mixmetrics",
+ || {
+ json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": {
+ "s": { "sum": { "field": "score" } },
+ "a": { "avg": { "field": "score" } },
+ "n": { "value_count": { "field": "score" } }
+ }
+ })
+ },
+ "columnar fast path disagrees with the brute reference on numeric \
+ metrics over a field whose column is suppressed in ONE segment only",
+ )
+ .await;
+ // The reference is the BRUTE path, asserted as it actually behaves, not
+ // as ES would: its sum/avg resolvers fold ONE value per doc (the array's
+ // first element), while value_count counts every element. So sum is
+ // 11 000 × 5 + 1 000 × 1, avg divides by the 12 000 docs, and
+ // value_count sees all 13 000 values. What this test pins is the
+ // fast/brute AGREEMENT above; brute's own array-metric semantics are a
+ // separate (pre-existing) question.
+ assert_eq!(brute["aggs"]["s"]["value"], 56_000.0);
+ assert_eq!(brute["aggs"]["n"]["value"], 13_000);
+ assert_eq!(brute["aggs"]["a"]["value"], 56_000.0 / 12_000.0);
+}
+
+/// The same metric as a SUB-agg under a fully-covered `terms` parent:
+/// sub-metric fields are planned in `plan_subs` via `seg_field_kind`, a
+/// different gate from the top-level `exec_agg` one, and the per-row fold
+/// skipped the suppressed segment the same way.
+#[tokio::test]
+async fn fast_and_brute_agree_on_mixed_segment_sub_metric() {
+ let brute = agree(
+ "mixsubmetric",
+ || {
+ json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": {
+ "by_group": {
+ "terms": { "field": "group", "size": 10 },
+ "aggs": { "s": { "sum": { "field": "score" } } }
+ }
+ }
+ })
+ },
+ "columnar fast path disagrees with the brute reference on a SUB-agg \
+ `sum` over a field whose column is suppressed in ONE segment only",
+ )
+ .await;
+ let buckets = brute["aggs"]["by_group"]["buckets"].as_array().unwrap();
+ assert_eq!(buckets.len(), 2);
+ for b in buckets {
+ // Each group: 5 500 scalar docs × 5 + 500 array docs × 1 (brute's
+ // sum folds one value per doc — see the metrics test above).
+ assert_eq!(b["doc_count"], 6_000);
+ assert_eq!(b["s"]["value"], 28_000.0);
+ }
+}