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.

perf(aggs): serve filtered statistics columnar — 11–264× on extended_stats + percentile family

Xerj Squad A1066f79e8974
diff --git a/engine/crates/xerj-engine/src/fast_aggs.rs b/engine/crates/xerj-engine/src/fast_aggs.rs
index f8eeea3de..9b5413d78 100644
--- a/engine/crates/xerj-engine/src/fast_aggs.rs
+++ b/engine/crates/xerj-engine/src/fast_aggs.rs
@@ -1020,6 +1020,14 @@ impl<'a> FastCtx<'a> {
// supported set covers the filtered-metric benchmark (avg/sum/…), the
// common filtered `terms` dashboard, and `global` (which ignores the
// filter entirely — it reduces over the whole corpus).
+ // `extended_stats` and the percentile family joined this list once
+ // their value gathering became filter-aware (`gather_numeric_sorted`
+ // gates on the `sorted` index's doc_id; `exec_extended_stats` gates
+ // its fold on the row). Before that they were excluded for
+ // CORRECTNESS, not speed — folding every row under a filter would
+ // report whole-index statistics for a filtered query. The exclusion
+ // meant a filtered `percentiles` fell to the O(N) `_source` scan:
+ // measured 11.9 s on 1.12 M docs, 70 s on 5.6 M.
if self.top_filter.is_some()
&& !matches!(
agg_type,
@@ -1032,6 +1040,10 @@ impl<'a> FastCtx<'a> {
| "terms"
| "cardinality"
| "global"
+ | "extended_stats"
+ | "percentiles"
+ | "percentile_ranks"
+ | "median_absolute_deviation"
)
{
return None;
@@ -1303,8 +1315,10 @@ impl<'a> FastCtx<'a> {
// shapes it accepts (modulo float-summation order — the same documented
// divergence the other metric leaves carry), and bails (`None` → brute)
// on any option that would change value gathering or rendering
- // (`missing`, `format`, `hdr`, `tdigest`) and under a top-level query
- // filter (handled by the whitelist in `exec_agg`).
+ // (`missing`, `format`, `hdr`, `tdigest`). A top-level query filter is
+ // now threaded through the gathering itself (per-row `seg_pred_matches`
+ // on the `sorted` index / the fold, plus `doc_matches_filter` on the
+ // memtable), so these leaves no longer bail when a filter is present.
/// Gather every live numeric value of `field` (segments + memtable) into a
/// single ascending-sorted `Vec<f64>`, mirroring the brute
@@ -1332,12 +1346,33 @@ impl<'a> FastCtx<'a> {
}
let mut vals: Vec<f64> = Vec::with_capacity(capacity);
for s in &self.segs {
+ // Under a top-level query filter, gather ONLY matching rows. The
+ // `sorted` index carries each value's `doc_id`, so the filter is a
+ // per-row gate that preserves ascending order — no re-sort needed
+ // and no separate pass. Without this the percentile family had to
+ // bail whenever a filter was present (the whitelist in `exec_agg`),
+ // which is what dropped every filtered `percentiles` /
+ // `percentile_ranks` / `median_absolute_deviation` onto the O(N)
+ // `_source` scan.
+ let seg_pred = match &self.top_filter {
+ Some(p) => Some(resolve_pred(&s.cols, p)?),
+ None => None,
+ };
match s.cols.get(field) {
- Some(Column::Numeric(n)) => {
- for (bits, _) in &n.sorted {
- vals.push(f64::from_bits(*bits as u64));
+ Some(Column::Numeric(n)) => match &seg_pred {
+ None => {
+ for (bits, _) in &n.sorted {
+ vals.push(f64::from_bits(*bits as u64));
+ }
}
- }
+ Some(sp) => {
+ for (bits, doc_id) in &n.sorted {
+ if seg_pred_matches(sp, *doc_id) {
+ vals.push(f64::from_bits(*bits as u64));
+ }
+ }
+ }
+ },
Some(Column::Keyword(_)) => return None,
None => {}
}
@@ -1345,7 +1380,15 @@ impl<'a> FastCtx<'a> {
// The collected values are already globally sorted iff they came from a
// single pre-sorted column source and the memtable added none.
let mut pre_sorted = self.segs.len() <= 1;
+ // Memtable docs are gated by the same `doc_matches_filter` the brute
+ // path uses, so the gathered multiset is identical either way.
+ let mem_filter = self.top_filter_query.clone();
for doc in self.mem().iter() {
+ if let Some(q) = &mem_filter {
+ if !doc_matches_filter(doc, q) {
+ continue;
+ }
+ }
if let Some(v) = extract_numeric(doc, field) {
vals.push(v);
pre_sorted = false;
@@ -1392,15 +1435,35 @@ impl<'a> FastCtx<'a> {
}
};
for s in &self.segs {
+ // Filter-aware fold: with a top-level query filter present, only
+ // matching rows contribute. Previously this loop was
+ // filter-blind, which is why `extended_stats` had to be excluded
+ // from the filtered whitelist in `exec_agg` — folding every row
+ // under a filter would have reported whole-index moments for a
+ // filtered query (silently wrong, not merely slow).
+ let seg_pred = match &self.top_filter {
+ Some(p) => Some(resolve_pred(&s.cols, p)?),
+ None => None,
+ };
match s.cols.get(field) {
Some(Column::Numeric(n)) => {
- if n.null_bitmap.is_empty() {
- for &bits in &n.data {
- fold(f64::from_bits(bits as u64));
+ let no_nulls = n.null_bitmap.is_empty();
+ match &seg_pred {
+ None if no_nulls => {
+ for &bits in &n.data {
+ fold(f64::from_bits(bits as u64));
+ }
}
- } else {
- for row in 0..n.doc_count {
- if !n.null_bitmap.contains(row) {
+ _ => {
+ for row in 0..n.doc_count {
+ if !no_nulls && n.null_bitmap.contains(row) {
+ continue;
+ }
+ if let Some(sp) = &seg_pred {
+ if !seg_pred_matches(sp, row) {
+ continue;
+ }
+ }
fold(f64::from_bits(n.data[row as usize] as u64));
}
}
@@ -1410,7 +1473,13 @@ impl<'a> FastCtx<'a> {
None => {}
}
}
+ let mem_filter = self.top_filter_query.clone();
for doc in self.mem().iter() {
+ if let Some(q) = &mem_filter {
+ if !doc_matches_filter(doc, q) {
+ continue;
+ }
+ }
if let Some(v) = extract_numeric(doc, field) {
fold(v);
}
diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rs
index c2c6ddb8c..a2b54368a 100644
--- a/engine/crates/xerj-engine/tests/integration.rs
+++ b/engine/crates/xerj-engine/tests/integration.rs
@@ -5091,3 +5091,143 @@ async fn test_knn_filter_similarity_boost_and_multi_clause() {
);
}
}
+
+// ── Filtered statistics on the columnar fast path ─────────────────────────────
+//
+// `extended_stats` and the percentile family used to be excluded from the
+// fast path whenever a top-level query filter was present, because their value
+// gathering was filter-blind — folding every row under a filter would report
+// whole-index statistics for a filtered query. The exclusion was a correctness
+// guard, and it dropped those aggs onto the O(N) `_source` scan (measured
+// 48.8 s vs 0.19 s on a 5.6 M-doc index).
+//
+// The gathering is now filter-aware, so these assert the thing that could
+// silently regress: a filtered statistic must describe ONLY the matching docs.
+// The index is sized past `FAST_AGG_MIN_DOCS` (10 000) so the columnar path is
+// actually the one under test — below that threshold the brute path serves it
+// and the test would pass vacuously.
+
+/// 12 000 docs: `group` alternates a/b, `v` is 1.0 for group a and 100.0 for
+/// group b. Any filter-blind fold is then trivially detectable — it sees both
+/// populations instead of one.
+async fn seed_filtered_stats_index(idx: &std::sync::Arc<xerj_engine::Index>) {
+ let mut docs = Vec::new();
+ 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 };
+ docs.push(json!({ "group": group, "v": v, "i": i }));
+ }
+ for (i, d) in docs.into_iter().enumerate() {
+ idx.index_document(Some(i.to_string()), d).await.unwrap();
+ }
+ idx.flush().await.unwrap();
+}
+
+#[tokio::test]
+async fn test_filtered_extended_stats_sees_only_matching_docs() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index("fstats", Schema::empty()).unwrap();
+ let idx = engine.get_index("fstats").unwrap();
+ seed_filtered_stats_index(&idx).await;
+
+ let req = parse_request(&json!({
+ "query": { "term": { "group": "b" } },
+ "size": 0,
+ "aggs": { "es": { "extended_stats": { "field": "v" } } }
+ }))
+ .unwrap();
+ let res = idx.search(&req).await.unwrap();
+ let es = &res.aggs.as_ref().unwrap()["es"];
+
+ // Group b only: 6 000 docs, every value 100.0.
+ assert_eq!(es["count"].as_u64().unwrap(), 6_000, "count must exclude group a");
+ assert_eq!(es["min"].as_f64().unwrap(), 100.0);
+ assert_eq!(es["max"].as_f64().unwrap(), 100.0);
+ assert_eq!(es["avg"].as_f64().unwrap(), 100.0, "avg of a filter-blind fold would be 50.5");
+ // Constant population → zero variance. A filter-blind fold gives ~2450.
+ assert!(
+ es["variance"].as_f64().unwrap() < 1e-6,
+ "variance must be ~0 for a constant population, got {}",
+ es["variance"]
+ );
+}
+
+#[tokio::test]
+async fn test_filtered_percentiles_see_only_matching_docs() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index("fpct", Schema::empty()).unwrap();
+ let idx = engine.get_index("fpct").unwrap();
+ seed_filtered_stats_index(&idx).await;
+
+ for (group, expect) in [("a", 1.0), ("b", 100.0)] {
+ let req = parse_request(&json!({
+ "query": { "term": { "group": group } },
+ "size": 0,
+ "aggs": { "p": { "percentiles": { "field": "v", "percents": [50, 99] } } }
+ }))
+ .unwrap();
+ let res = idx.search(&req).await.unwrap();
+ let vals = &res.aggs.as_ref().unwrap()["p"]["values"];
+ // Every value in the matching set is identical, so every percentile is
+ // that value. A filter-blind gather would mix 1.0 and 100.0 and put p50
+ // somewhere between them.
+ for pct in ["50.0", "99.0"] {
+ assert_eq!(
+ vals[pct].as_f64().unwrap(),
+ expect,
+ "group {group} p{pct} must reflect only matching docs"
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn test_filtered_median_absolute_deviation_sees_only_matching_docs() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index("fmad", Schema::empty()).unwrap();
+ let idx = engine.get_index("fmad").unwrap();
+ seed_filtered_stats_index(&idx).await;
+
+ let req = parse_request(&json!({
+ "query": { "term": { "group": "a" } },
+ "size": 0,
+ "aggs": { "m": { "median_absolute_deviation": { "field": "v" } } }
+ }))
+ .unwrap();
+ let res = idx.search(&req).await.unwrap();
+ let mad = res.aggs.as_ref().unwrap()["m"]["value"]
+ .as_f64()
+ .unwrap();
+ // Constant population → MAD 0. Filter-blind would give ~49.5.
+ assert!(mad < 1e-6, "MAD must be ~0 for a constant population, got {mad}");
+}
+
+#[tokio::test]
+async fn test_unfiltered_statistics_are_unchanged() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index("ufstats", Schema::empty()).unwrap();
+ let idx = engine.get_index("ufstats").unwrap();
+ seed_filtered_stats_index(&idx).await;
+
+ let req = parse_request(&json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": {
+ "es": { "extended_stats": { "field": "v" } },
+ "p": { "percentiles": { "field": "v", "percents": [50] } }
+ }
+ }))
+ .unwrap();
+ let res = idx.search(&req).await.unwrap();
+ let aggs = res.aggs.as_ref().unwrap();
+ // Whole corpus: 12 000 docs, half 1.0 and half 100.0 → mean 50.5.
+ assert_eq!(aggs["es"]["count"].as_u64().unwrap(), 12_000);
+ assert!((aggs["es"]["avg"].as_f64().unwrap() - 50.5).abs() < 1e-9);
+ assert_eq!(aggs["es"]["min"].as_f64().unwrap(), 1.0);
+ assert_eq!(aggs["es"]["max"].as_f64().unwrap(), 100.0);
+ assert!(aggs["p"]["values"]["50.0"].as_f64().is_some());
+}