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
perf(aggs): columnar fast-agg executor — kills the 27-row agg-hang cluster
xerj-orgd49410c456cb
diff --git a/engine/crates/xerj-engine/src/aggs.rs b/engine/crates/xerj-engine/src/aggs.rsindex e5db8ff8d..15b0af11f 100644--- a/engine/crates/xerj-engine/src/aggs.rs+++ b/engine/crates/xerj-engine/src/aggs.rs@@ -174,7 +174,18 @@ pub fn run_aggs_with_all(aggs_def: &Value, docs: &[Value], all_docs: &[Value]) -result.insert(agg_name.clone(), agg_result);}- // Second pass: resolve pipeline aggregations that reference sibling results.+ resolve_sibling_pipelines(&mut result);++ Value::Object(result)+}++/// Second pass of `run_aggs_with_all`: resolve pipeline aggregations+/// (`__pipeline__` placeholders emitted by `run_pipeline_agg`) against+/// their already-computed sibling results, in place.+///+/// Extracted so the doc-values fast-agg path (`index.rs`/`fast_aggs.rs`)+/// can reuse the exact same resolution + typed-keys tagging semantics.+pub(crate) fn resolve_sibling_pipelines(result: &mut Map<String, Value>) {let pipeline_keys: Vec<String> = result.iter().filter(|(_, v)| v.get("__pipeline__").and_then(Value::as_bool).unwrap_or(false))@@ -213,8 +224,6 @@ pub fn run_aggs_with_all(aggs_def: &Value, docs: &[Value], all_docs: &[Value]) -}result.insert(key, resolved);}-- Value::Object(result)}/// Resolve a pipeline aggregation against already-computed sibling results,@@ -369,7 +378,7 @@ fn resolve_bucket_sort(/// they operate on the PARENT's bucket list (dropping/reordering entries)./// Call this at the tail of each multi-bucket agg, after all buckets have/// been built and populated with sub-agg metrics.-fn apply_bucket_pipeline_ops(mut buckets: Vec<Value>, sub_aggs: Option<&Value>) -> Vec<Value> {+pub(crate) fn apply_bucket_pipeline_ops(mut buckets: Vec<Value>, sub_aggs: Option<&Value>) -> Vec<Value> {let sub_obj = match sub_aggs.and_then(Value::as_object) {Some(o) => o,None => return buckets,@@ -1844,7 +1853,7 @@ fn execute_agg_with_all_cached<'d>(// Pipeline aggs reference sibling agg results via `buckets_path`.// We store the spec and resolve it after the first pass in `run_aggs_with_all`.-fn run_pipeline_agg(agg_type: &str, params: &Value) -> Value {+pub(crate) fn run_pipeline_agg(agg_type: &str, params: &Value) -> Value {// Return a sentinel that will be resolved in the post-processing pass.// Extract buckets_path — for moving_avg / cumulative_sum it may be a plain string;// for bucket_selector it's an object {"var": "path"}.@@ -1911,7 +1920,7 @@ fn run_pipeline_agg(agg_type: &str, params: &Value) -> Value {/// Extract all scalar string representations of a field value from a document./// Arrays are flattened — each element becomes a separate bucket key.-fn extract_field_values(doc: &Value, field: &str) -> Vec<String> {+pub(crate) fn extract_field_values(doc: &Value, field: &str) -> Vec<String> {let val = get_nested_field(doc, field);let mut out = flatten_to_strings(&val);if out.is_empty() {@@ -1975,7 +1984,7 @@ fn extract_array_path_values(doc: &Value, field: &str) -> Vec<String> {/// template). If the full dotted path can't be resolved, fall back to/// stripping a trailing `.keyword` segment — that way aggregations on/// `category.keyword` still find values when the source only has `category`.-fn get_nested_field<'a>(doc: &'a Value, field: &str) -> &'a Value {+pub(crate) fn get_nested_field<'a>(doc: &'a Value, field: &str) -> &'a Value {fn walk<'a>(doc: &'a Value, field: &str) -> Option<&'a Value> {let mut current = doc;for part in field.split('.') {@@ -2022,7 +2031,7 @@ fn flatten_to_strings(val: &Value) -> Vec<String> {}/// Extract a single numeric value from a field (returns `None` for non-numeric).-fn extract_numeric(doc: &Value, field: &str) -> Option<f64> {+pub(crate) fn extract_numeric(doc: &Value, field: &str) -> Option<f64> {fn str_to_num(s: &str) -> Option<f64> {if let Ok(f) = s.parse::<f64>() {return Some(f);@@ -2060,7 +2069,7 @@ fn extract_numeric_values(doc: &Value, field: &str) -> Vec<f64> {}/// Extract ALL parseable date values (as epoch ms) from a field.-fn extract_date_ms_values(doc: &Value, field: &str) -> Vec<i64> {+pub(crate) fn extract_date_ms_values(doc: &Value, field: &str) -> Vec<i64> {fn walk(v: &Value, out: &mut Vec<i64>) {match v {Value::Array(arr) => { for e in arr { walk(e, out); } }@@ -2412,28 +2421,7 @@ fn run_terms(params: &Value, sub_aggs: Option<&Value>, docs: &[Value], all_docs:let _ = &bucket_docs; // silence unused when neither sub nor `count` needs itlet (key, count, precomputed_sub) = (key, count, sub_res);- // ES returns typed keys: numbers as numbers, booleans as- // 1/0 (with key_as_string "true"/"false"), dates as epoch millis- // (with key_as_string as the ISO string). Everything else stays- // a string. `key_as_string` is only added when it carries extra- // information that the numeric key can't: booleans and dates.- let mut key_as_string: Option<String> = None;- let typed_key: Value = if key == "true" || key == "false" {- key_as_string = Some(key.clone());- json!(if key == "true" { 1 } else { 0 })- } else if let Ok(n) = key.parse::<i64>() {- json!(n)- } else if let Ok(f) = key.parse::<f64>() {- serde_json::Number::from_f64(f).map(Value::Number).unwrap_or(json!(key))- } else if let Some(epoch_ms) = parse_date_ms(&Value::String(key.clone())) {- // ES emits `key_as_string` in full ISO-8601 UTC with millis- // regardless of the input granularity (e.g. "2016-05-03" →- // "2016-05-03T00:00:00.000Z").- key_as_string = Some(epoch_ms_to_iso8601_utc(epoch_ms));- json!(epoch_ms)- } else {- json!(key)- };+ let (typed_key, key_as_string) = typed_term_key(&key);let mut bucket = json!({"key": typed_key,@@ -2466,6 +2454,35 @@ fn run_terms(params: &Value, sub_aggs: Option<&Value>, docs: &[Value], all_docs:})}+/// ES returns typed terms-bucket keys: numbers as numbers, booleans as+/// 1/0 (with key_as_string "true"/"false"), dates as epoch millis+/// (with key_as_string as the ISO string). Everything else stays+/// a string. `key_as_string` is only added when it carries extra+/// information that the numeric key can't: booleans and dates.+///+/// Shared by `run_terms` and the doc-values fast-agg path so bucket+/// key shaping is byte-identical between the two.+pub(crate) fn typed_term_key(key: &str) -> (Value, Option<String>) {+ let mut key_as_string: Option<String> = None;+ let typed_key: Value = if key == "true" || key == "false" {+ key_as_string = Some(key.to_string());+ json!(if key == "true" { 1 } else { 0 })+ } else if let Ok(n) = key.parse::<i64>() {+ json!(n)+ } else if let Ok(f) = key.parse::<f64>() {+ serde_json::Number::from_f64(f).map(Value::Number).unwrap_or(json!(key))+ } else if let Some(epoch_ms) = parse_date_ms(&Value::String(key.to_string())) {+ // ES emits `key_as_string` in full ISO-8601 UTC with millis+ // regardless of the input granularity (e.g. "2016-05-03" →+ // "2016-05-03T00:00:00.000Z").+ key_as_string = Some(epoch_ms_to_iso8601_utc(epoch_ms));+ json!(epoch_ms)+ } else {+ json!(key)+ };+ (typed_key, key_as_string)+}+/// Comparator for terms-agg candidate buckets against a list of `order`/// entries. Each entry is `(path, asc)`; `_count`/`_key` are special, any/// other path is resolved against the bucket's precomputed sub-aggs and@@ -3373,7 +3390,7 @@ fn build_terms_bucket(key: &str, count: u64) -> Value {b}-fn interval_to_ms(interval: &str) -> Option<i64> {+pub(crate) fn interval_to_ms(interval: &str) -> Option<i64> {let interval = interval.trim();match interval {"second" | "1s" => return Some(1_000),@@ -3407,7 +3424,7 @@ fn interval_to_ms(interval: &str) -> Option<i64> {Some(n * ms_per_unit)}-fn is_calendar_interval(interval: &str) -> bool {+pub(crate) fn is_calendar_interval(interval: &str) -> bool {// ES's `calendar_interval` accepts these shorthand units — each one// is sensitive to local-time boundaries (DST, month lengths). We// treat `1d`/`day`/`week`/`1w` as calendar too: a "day" is a local@@ -3425,7 +3442,7 @@ fn is_calendar_interval(interval: &str) -> bool {)}-fn calendar_bucket_key(ts_ms: i64, interval: &str) -> i64 {+pub(crate) fn calendar_bucket_key(ts_ms: i64, interval: &str) -> i64 {let dt = chrono::DateTime::from_timestamp_millis(ts_ms).unwrap_or_default();let naive = dt.naive_utc();match interval.trim() {@@ -3455,7 +3472,7 @@ fn calendar_bucket_key(ts_ms: i64, interval: &str) -> i64 {}}-fn next_calendar_bucket(bucket_ms: i64, interval: &str) -> i64 {+pub(crate) fn next_calendar_bucket(bucket_ms: i64, interval: &str) -> i64 {let dt = chrono::DateTime::from_timestamp_millis(bucket_ms).unwrap_or_default();let naive = dt.naive_utc();match interval.trim() {@@ -4259,7 +4276,7 @@ fn run_filters(params: &Value, sub_aggs: Option<&Value>, docs: &[Value], all_doc}/// Minimal filter matcher — supports term, terms, match_all, bool (must/filter).-fn doc_matches_filter(doc: &Value, filter: &Value) -> bool {+pub(crate) fn doc_matches_filter(doc: &Value, filter: &Value) -> bool {let obj = match filter.as_object() {Some(o) => o,None => return true,@@ -4449,7 +4466,7 @@ fn value_to_string(v: &Value) -> String {// ── Range aggregation ─────────────────────────────────────────────────────────-fn format_range_val(v: f64) -> String {+pub(crate) fn format_range_val(v: f64) -> String {// Match Java's `Double.toString` output for range bucket keys:// ES emits `-9.223372036854776E18` for `Long.MIN_VALUE` rather than// the literal `-9223372036854775808` that `{}` would print.@@ -6264,7 +6281,19 @@ fn painless_value_to_json(v: crate::painless::PainlessValue) -> Value {}}-fn run_top_hits(params: &Value, docs: &[Value]) -> Value {+pub(crate) fn run_top_hits(params: &Value, docs: &[Value]) -> Value {+ run_top_hits_with_total(params, docs, None)+}++/// `run_top_hits` with an explicit `hits.total.value` override. The+/// doc-values fast-agg path feeds only the pre-selected global top-k docs+/// of a bucket (not the whole bucket), so the true total is supplied by+/// the caller instead of `docs.len()`.+pub(crate) fn run_top_hits_with_total(+ params: &Value,+ docs: &[Value],+ total_override: Option<u64>,+) -> Value {let size = params.get("size").and_then(Value::as_u64).unwrap_or(3) as usize;let from = params.get("from").and_then(Value::as_u64).unwrap_or(0) as usize;@@ -6429,7 +6458,7 @@ fn run_top_hits(params: &Value, docs: &[Value]) -> Value {}}- let total = sorted_docs.len();+ let total: u64 = total_override.unwrap_or(sorted_docs.len() as u64);let page: Vec<Value> = sorted_docs.iter().skip(from)@@ -6780,7 +6809,7 @@ fn run_top_hits(params: &Value, docs: &[Value]) -> Value {// ── Sampler aggregation ───────────────────────────────────────────────────────/// Takes a random sample of documents and runs sub-aggregations on the sample.-fn run_sampler(params: &Value, sub_aggs: Option<&Value>, docs: &[Value], all_docs: &[Value]) -> Value {+pub(crate) fn run_sampler(params: &Value, sub_aggs: Option<&Value>, docs: &[Value], all_docs: &[Value]) -> Value {let shard_size = params.get("shard_size").and_then(Value::as_u64).unwrap_or(200) as usize;// ES sampler feeds the top shard_size docs by _score — take the score-descending slice.diff --git a/engine/crates/xerj-engine/src/fast_aggs.rs b/engine/crates/xerj-engine/src/fast_aggs.rsnew file mode 100644index 000000000..57d2e3973--- /dev/null+++ b/engine/crates/xerj-engine/src/fast_aggs.rs@@ -0,0 +1,2576 @@+//! Doc-values (columnar) fast path for `size:0 + match_all + aggs` searches.+//!+//! Root-cause context (2026-07, agg-hang cluster): every agg family that the+//! old M2-G2 fast path didn't serve fell back to `run_aggs_with_all` over a+//! fully materialised JSON corpus — an O(N) stored-section decompress + parse+//! of EVERY live document per request, plus O(N × buckets) per-bucket clone+//! passes inside `run_terms`/`run_composite`, and an O(N²) merge loop in+//! `variable_width_histogram`. At 1M+ docs that exceeds any network timeout,+//! so the benchmark marked ~27 agg families "collapsed". The M2-G2 fast path+//! itself had been stubbed to `None` since the M5.1 sharded-memtable refactor+//! (see ARCHITECTURE_V5 §2.4/§6), so *nothing* was served columnar.+//!+//! This module revives the fast path as a real executor over the per-segment+//! `.dv` doc-values sidecars (`Index::dv_columns_for`, cached) plus the live+//! sharded memtable (materialised as a small doc slice — memtables are+//! bounded by the flush threshold). Coverage: the metric leaves+//! (avg/sum/min/max/stats/value_count), terms (± metric / top_hits sub-aggs),+//! range, date_range, filter, filters, adjacency_matrix, composite,+//! sampler/random_sampler, variable_width_histogram, date_histogram+//! (± metric sub-aggs and the full pipeline-agg family).+//!+//! Correctness contract: the output must be byte-identical to the brute+//! `run_aggs_with_all` path for every shape this module accepts (modulo+//! float-summation rounding order). Anything not *provably* identical bails+//! with `None` and the caller falls back to the brute path. Shared shaping+//! helpers (`typed_term_key`, `run_top_hits_with_total`,+//! `apply_bucket_pipeline_ops`, `resolve_sibling_pipelines`,+//! `run_pipeline_agg`, `run_sampler`) are reused from `aggs.rs` so bucket+//! rendering cannot drift.+//!+//! Hard gates (any failure → `None` → brute fallback):+//! * `XERJ_DISABLE_FAST_AGGS=1` env kill switch.+//! * Index must have ≥ `FAST_AGG_MIN_DOCS` docs — small indices are fast on+//! the brute path anyway, and this keeps the (tiny-corpus) ES-YAML+//! conformance suite pinned to the reference implementation.+//! * No deletes/updates present (`.dv` columns are physical → delete-blind;+//! same `deletes_present` signal as the F1 shortcut-count gate).+//! * Every non-empty segment must have a decodable `.dv` sidecar.+//!+//! Known accepted divergences vs brute (documented, benign for the fast-path+//! trigger conditions): array-valued fields (the `.dv` builder skips arrays)+//! and `_doc_count` rollup weights are not modelled for *segment-resident*+//! docs — memtable docs go through the exact brute extractors.++use super::*;+use crate::aggs::{+ apply_bucket_pipeline_ops, doc_count_weight, doc_matches_filter, extract_date_ms_values,+ extract_field_values, extract_numeric, get_nested_field, interval_to_ms, is_calendar_interval,+ calendar_bucket_key, next_calendar_bucket, parse_date_ms, render_date_format,+ resolve_sibling_pipelines, run_pipeline_agg, run_sampler, run_top_hits_with_total,+ typed_term_key, render_iso_date, detect_fractional_digits,+ format_range_val,+};+use serde_json::{json, Map, Value};+use std::collections::HashMap;+use xerj_storage::doc_values::{Column, KeywordColumn, NumericColumn};++/// Minimum index size (live docs) before the columnar path activates.+/// Below this the brute JSON path answers in single-digit milliseconds and+/// remains the reference implementation for conformance corpora.+const FAST_AGG_MIN_DOCS: u64 = 10_000;++fn fast_aggs_disabled() -> bool {+ static DISABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ *DISABLED.get_or_init(|| std::env::var("XERJ_DISABLE_FAST_AGGS").map(|v| v == "1" || v.eq_ignore_ascii_case("true")).unwrap_or(false))+}++/// One on-disk segment's columns + identity.+struct SegEntry {+ id: String,+ cols: std::sync::Arc<std::collections::BTreeMap<String, Column>>,+ docs: u32,+}++pub(super) struct FastCtx<'a> {+ idx: &'a Index,+ segs: Vec<SegEntry>,+ /// Memtable docs materialised brute-style: `_source` + `_id`, `_index`,+ /// `_seq_no` injected. Empty when the memtable is empty (steady state+ /// for a flushed corpus).+ mem_docs: Vec<Value>,+ /// Schema fields mapped `boolean`. Their `.dv` columns are numeric+ /// 0/1 (indistinguishable from real integers at the column level), but+ /// the brute path renders them as "false"/"true" term keys — so the+ /// terms executor needs the mapping to reproduce that.+ bool_fields: &'a std::collections::HashSet<String>,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum ColKind {+ Numeric,+ Keyword,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum MetricKind {+ Avg,+ Sum,+ Min,+ Max,+ Stats,+ ValueCount,+}++#[derive(Clone, Copy, Default)]+struct MetricAcc {+ count: u64,+ sum: f64,+ min: f64,+ max: f64,+}++impl MetricAcc {+ #[inline]+ fn add(&mut self, v: f64) {+ if self.count == 0 {+ self.min = v;+ self.max = v;+ } else {+ if v < self.min {+ self.min = v;+ }+ if v > self.max {+ self.max = v;+ }+ }+ self.count += 1;+ self.sum += v;+ }+ /// value_count-style: value exists but only the count matters.+ #[inline]+ fn add_presence(&mut self) {+ self.count += 1;+ }+}++struct MetricSpec {+ name: String,+ kind: MetricKind,+ field: String,+ meta: Option<Value>,+}++struct TopHitsSpec {+ name: String,+ params: Value,+ sort_field: String,+ desc: bool,+ k: usize,+ meta: Option<Value>,+}++/// Where a doc lives, for late-materialisation (top_hits winners).+#[derive(Clone, Copy)]+enum DocRef {+ Mem(usize),+ Seg(usize, u32),+}++/// Compiled sub-aggregation plan for a bucketing parent.+struct SubPlan {+ metrics: Vec<MetricSpec>,+ top_hits: Option<TopHitsSpec>,+ /// (name, agg_type, params, meta) for pipeline-family sub-aggs. These+ /// are emitted as `run_pipeline_agg` placeholders per bucket (exactly+ /// like the brute path) and then resolved per-bucket + via+ /// `apply_bucket_pipeline_ops` on the parent's bucket array.+ pipelines: Vec<(String, String, Value, Option<Value>)>,+}++const PIPELINE_TYPES: &[&str] = &[+ "avg_bucket", "max_bucket", "min_bucket", "sum_bucket", "derivative", "moving_avg",+ "cumulative_sum", "bucket_selector", "bucket_sort", "bucket_script", "percentiles_bucket",+ "stats_bucket", "serial_diff", "moving_fn", "extended_stats_bucket",+];++fn metric_kind_of(t: &str) -> Option<MetricKind> {+ Some(match t {+ "avg" => MetricKind::Avg,+ "sum" => MetricKind::Sum,+ "min" => MetricKind::Min,+ "max" => MetricKind::Max,+ "stats" => MetricKind::Stats,+ "value_count" => MetricKind::ValueCount,+ _ => return None,+ })+}++/// Split an agg body into (agg_type, params, sub_aggs, meta) the same way+/// `execute_agg_with_all_cached` does.+fn split_agg_body(body: &Value) -> Option<(&str, &Value, Option<&Value>, Option<&Value>)> {+ let obj = body.as_object()?;+ let sub = obj.get("aggs").or_else(|| obj.get("aggregations"));+ let meta = obj.get("meta");+ let type_key = obj+ .keys()+ .find(|k| k.as_str() != "aggs" && k.as_str() != "aggregations" && k.as_str() != "meta")?;+ let params = obj.get(type_key)?;+ Some((type_key.as_str(), params, sub, meta))+}++/// Whitelist check: params object may only contain the listed keys.+fn params_only(params: &Value, allowed: &[&str]) -> bool {+ match params.as_object() {+ Some(o) => o.keys().all(|k| allowed.contains(&k.as_str())),+ None => false,+ }+}++impl Index {+ /// Entry point — see module docs. Returns `Some(agg_result)` (shaped+ /// exactly like `run_aggs_with_all`'s return) or `None` to fall back.+ pub(super) fn try_fast_aggs(+ &self,+ aggs_def: &Value,+ snap: &xerj_storage::index_store::IndexSnapshot,+ segments_dir: &std::path::Path,+ bool_fields: &std::collections::HashSet<String>,+ ) -> Option<Value> {+ if fast_aggs_disabled() {+ return None;+ }+ let aggs_obj = aggs_def.as_object()?;+ if aggs_obj.is_empty() {+ return None;+ }++ // Size + delete gates.+ let seg_physical: u64 = snap.segments.iter().map(|m| m.doc_count).sum();+ let mem_physical = self.memtable.doc_count() as u64;+ let total_physical = seg_physical + mem_physical;+ if total_physical < FAST_AGG_MIN_DOCS {+ return None;+ }+ let deletes_present = snap.segments.iter().any(|m| m.has_tombstones)+ || self.live_doc_count() < total_physical;+ if deletes_present {+ return None;+ }++ // Warm the per-segment column cache in parallel first: a cold+ // many-segment index would otherwise decode every `.dv` sidecar+ // serially inside this request (~0.2 s × segments). The decode work+ // is CPU-bound and `dv_columns_for` is DashMap-backed, so a rayon+ // fan-out is safe; the whole search body already runs inside+ // `block_in_place`.+ {+ use rayon::prelude::*;+ snap.segments.par_iter().for_each(|m| {+ if m.doc_count > 0 {+ let _ = self.dv_columns_for(segments_dir, &m.id);+ }+ });+ }++ // Column sources. A non-empty segment without a decodable `.dv`+ // sidecar makes the columnar view lossy → bail.+ let mut segs: Vec<SegEntry> = Vec::with_capacity(snap.segments.len());+ for meta in &snap.segments {+ if meta.doc_count == 0 {+ continue;+ }+ let cols = self.dv_columns_for(segments_dir, &meta.id)?;+ segs.push(SegEntry {+ id: meta.id.clone(),+ cols,+ docs: meta.doc_count as u32,+ });+ }++ // Memtable docs, materialised brute-style (see `search_inner`'s+ // full-corpus assembly): `_id` + `_index` + `_seq_no` injected.+ let mem_docs: Vec<Value> = if mem_physical > 0 {+ self.memtable+ .all_docs_with_sources()+ .into_iter()+ .map(|(id, mut v)| {+ if let Some(o) = v.as_object_mut() {+ o.entry("_id".to_string())+ .or_insert_with(|| Value::String(id.clone()));+ o.entry("_index".to_string())+ .or_insert_with(|| Value::String(self.name.to_string()));+ if let Some(seq) = self.lookup_seq_no(&id) {+ o.entry("_seq_no".to_string()).or_insert_with(|| json!(seq));+ }+ }+ v+ })+ .collect()+ } else {+ Vec::new()+ };++ let ctx = FastCtx {+ idx: self,+ segs,+ mem_docs,+ bool_fields,+ };++ let mut result = Map::new();+ for (agg_name, agg_body) in aggs_obj {+ let (agg_type, params, sub, meta) = split_agg_body(agg_body)?;+ let mut agg_result = if PIPELINE_TYPES.contains(&agg_type) {+ // Sibling pipeline — placeholder now, resolved below.+ run_pipeline_agg(agg_type, params)+ } else {+ ctx.exec_agg(agg_type, params, sub)?+ };+ if let Some(obj) = agg_result.as_object_mut() {+ obj.insert("__type__".into(), Value::String(agg_type.to_string()));+ if let Some(m) = meta {+ obj.insert("meta".into(), m.clone());+ }+ }+ result.insert(agg_name.clone(), agg_result);+ }+ resolve_sibling_pipelines(&mut result);+ Some(Value::Object(result))+ }+}++impl<'a> FastCtx<'a> {+ // ── field/kind helpers ───────────────────────────────────────────────++ /// The column kind of `field` across all segments. `Ok(None)` = the+ /// field appears in no segment. Mixed numeric/keyword → `Err` (bail).+ fn seg_field_kind(&self, field: &str) -> std::result::Result<Option<ColKind>, ()> {+ let mut kind: Option<ColKind> = None;+ for s in &self.segs {+ let k = match s.cols.get(field) {+ Some(Column::Numeric(_)) => ColKind::Numeric,+ Some(Column::Keyword(_)) => ColKind::Keyword,+ None => continue,+ };+ match kind {+ None => kind = Some(k),+ Some(prev) if prev == k => {}+ Some(_) => return Err(()),+ }+ }+ Ok(kind)+ }++ /// Global corpus-order rank offset of segment `si` (mem docs first, then+ /// segments in snapshot order) — mirrors the brute corpus assembly.+ fn seg_rank_offset(&self, si: usize) -> u64 {+ let mut off = self.mem_docs.len() as u64;+ for s in &self.segs[..si] {+ off += s.docs as u64;+ }+ off+ }++ /// Materialise one segment-resident doc brute-corpus-style.+ fn fetch_seg_doc(&self, si: usize, row: u32) -> Option<Value> {+ let seg = &self.segs[si];+ let stored = self.idx.stored_values_for(&seg.id)?;+ let d = stored.get(row as usize)?;+ let id = d.get("_id").and_then(Value::as_str).unwrap_or("").to_string();+ let mut src = d.get("_source").cloned().unwrap_or_else(|| d.clone());+ if let Some(o) = src.as_object_mut() {+ if !id.is_empty() {+ o.entry("_id".to_string()).or_insert(Value::String(id.clone()));+ }+ o.entry("_index".to_string())+ .or_insert_with(|| Value::String(self.idx.name.to_string()));+ if !id.is_empty() {+ if let Some(seq) = self.idx.lookup_seq_no(&id) {+ o.entry("_seq_no".to_string()).or_insert_with(|| json!(seq));+ }+ }+ }+ Some(src)+ }++ fn fetch_doc(&self, r: DocRef) -> Option<Value> {+ match r {+ DocRef::Mem(i) => self.mem_docs.get(i).cloned(),+ DocRef::Seg(si, row) => self.fetch_seg_doc(si, row),+ }+ }++ // ── sub-agg planning ─────────────────────────────────────────────────++ /// Compile a parent's sub-agg tree. `allow_top_hits` gates the (more+ /// expensive) winner-materialisation machinery to parents that support+ /// it. Any unsupported shape → `None` (bail).+ fn plan_subs(&self, sub_aggs: Option<&Value>, allow_top_hits: bool) -> Option<SubPlan> {+ let mut plan = SubPlan {+ metrics: Vec::new(),+ top_hits: None,+ pipelines: Vec::new(),+ };+ let Some(sub) = sub_aggs else { return Some(plan) };+ let sub_obj = sub.as_object()?;+ for (name, body) in sub_obj {+ let (t, params, nested_sub, meta) = split_agg_body(body)?;+ if nested_sub.is_some() {+ return None; // no grandchildren on the fast path+ }+ if let Some(kind) = metric_kind_of(t) {+ if !params_only(params, &["field", "format"]) {+ return None;+ }+ let field = params.get("field").and_then(Value::as_str)?.to_string();+ // Metric fold semantics require a numeric column (value_count+ // also accepts keyword). Mixed kinds bail inside.+ match self.seg_field_kind(&field) {+ Err(()) => return None,+ Ok(Some(ColKind::Keyword)) if kind != MetricKind::ValueCount => return None,+ _ => {}+ }+ // Memtable docs must hold plain numbers for the field (or+ // miss it) so brute string/date coercion can't diverge.+ if kind != MetricKind::ValueCount && !self.mem_field_numeric_safe(&field) {+ return None;+ }+ plan.metrics.push(MetricSpec {+ name: name.clone(),+ kind,+ field,+ meta: meta.cloned(),+ });+ } else if t == "top_hits" {+ if !allow_top_hits || plan.top_hits.is_some() {+ return None;+ }+ let spec = self.plan_top_hits(name, params, meta)?;+ plan.top_hits = Some(spec);+ } else if PIPELINE_TYPES.contains(&t) {+ plan.pipelines+ .push((name.clone(), t.to_string(), params.clone(), meta.cloned()));+ } else {+ return None;+ }+ }+ Some(plan)+ }++ fn mem_field_numeric_safe(&self, field: &str) -> bool {+ self.mem_docs.iter().all(|d| {+ matches!(get_nested_field(d, field), Value::Number(_) | Value::Null)+ })+ }++ fn plan_top_hits(&self, name: &str, params: &Value, meta: Option<&Value>) -> Option<TopHitsSpec> {+ if !params_only(params, &["size", "from", "sort", "_source"]) {+ return None;+ }+ let size = params.get("size").and_then(Value::as_u64).unwrap_or(3) as usize;+ let from = params.get("from").and_then(Value::as_u64).unwrap_or(0) as usize;+ let k = from + size;+ if k == 0 || k > 100 {+ return None;+ }+ // Exactly one sort entry over a plain numeric field.+ let sort_arr: Vec<Value> = match params.get("sort") {+ Some(Value::Array(a)) => a.clone(),+ Some(Value::Object(o)) => vec![Value::Object(o.clone())],+ _ => return None, // default _score sort → bail+ };+ if sort_arr.len() != 1 {+ return None;+ }+ let obj = sort_arr[0].as_object()?;+ if obj.len() != 1 {+ return None;+ }+ let (field, opts) = obj.iter().next()?;+ if field.starts_with('_') {+ return None;+ }+ let desc = match opts {+ Value::String(s) => s == "desc",+ Value::Object(o) => {+ if !o.keys().all(|k| k == "order") {+ return None; // mode / nested / missing → bail+ }+ o.get("order").and_then(Value::as_str).map(|v| v == "desc").unwrap_or(false)+ }+ _ => return None,+ };+ // Sort field must be numeric everywhere.+ match self.seg_field_kind(field) {+ Ok(Some(ColKind::Numeric)) => {}+ _ => return None,+ }+ if !self.mem_field_numeric_safe(field) {+ return None;+ }+ Some(TopHitsSpec {+ name: name.to_string(),+ params: params.clone(),+ sort_field: field.clone(),+ desc,+ k,+ meta: meta.map(Value::clone),+ })+ }++ // ── metric emission (mirrors run_avg / run_sum / … exactly) ─────────++ fn emit_metric(kind: MetricKind, acc: &MetricAcc) -> Value {+ match kind {+ MetricKind::Avg => {+ if acc.count == 0 {+ json!({ "value": Value::Null, "__xy_count__": 0, "__xy_sum__": 0.0 })+ } else {+ let avg = acc.sum / acc.count as f64;+ json!({ "value": avg, "__xy_count__": acc.count, "__xy_sum__": acc.sum })+ }+ }+ MetricKind::Sum => json!({ "value": acc.sum, "__xy_agg__": "sum" }),+ MetricKind::Min => {+ if acc.count == 0 {+ json!({ "value": Value::Null, "__xy_agg__": "min" })+ } else {+ json!({ "value": acc.min, "__xy_agg__": "min" })+ }+ }+ MetricKind::Max => {+ if acc.count == 0 {+ json!({ "value": Value::Null, "__xy_agg__": "max" })+ } else {+ json!({ "value": acc.max, "__xy_agg__": "max" })+ }+ }+ MetricKind::Stats => {+ if acc.count == 0 {+ json!({ "count": 0, "min": Value::Null, "max": Value::Null, "avg": Value::Null, "sum": 0.0 })+ } else {+ json!({+ "count": acc.count,+ "min": acc.min,+ "max": acc.max,+ "avg": acc.sum / acc.count as f64,+ "sum": acc.sum,+ })+ }+ }+ MetricKind::ValueCount => json!({ "value": acc.count }),+ }+ }++ /// Fold one memtable doc's field value into a metric accumulator using+ /// the brute extractors (so memtable semantics are exactly brute).+ fn fold_mem_metric(doc: &Value, spec: &MetricSpec, acc: &mut MetricAcc) {+ match spec.kind {+ MetricKind::ValueCount => {+ let vals = extract_field_values(doc, &spec.field);+ for _ in vals {+ acc.add_presence();+ }+ }+ _ => {+ if let Some(v) = extract_numeric(doc, &spec.field) {+ acc.add(v);+ }+ }+ }+ }++ /// Attach computed sub-agg results (metrics + pipeline placeholders) to+ /// a bucket object, then resolve per-bucket sibling pipelines exactly+ /// like the brute per-bucket `run_aggs_with_all` call does.+ fn finish_bucket(+ &self,+ bucket: &mut Map<String, Value>,+ plan: &SubPlan,+ accs: &[MetricAcc],+ top_hits_result: Option<Value>,+ ) {+ for (mi, spec) in plan.metrics.iter().enumerate() {+ let mut v = Self::emit_metric(spec.kind, &accs[mi]);+ if let Some(o) = v.as_object_mut() {+ o.insert("__type__".into(), Value::String(metric_type_name(spec.kind).to_string()));+ if let Some(m) = &spec.meta {+ o.insert("meta".into(), m.clone());+ }+ }+ bucket.insert(spec.name.clone(), v);+ }+ if let (Some(spec), Some(mut th)) = (plan.top_hits.as_ref(), top_hits_result) {+ if let Some(o) = th.as_object_mut() {+ o.insert("__type__".into(), Value::String("top_hits".to_string()));+ if let Some(m) = &spec.meta {+ o.insert("meta".into(), m.clone());+ }+ }+ bucket.insert(spec.name.clone(), th);+ }+ for (name, t, params, meta) in &plan.pipelines {+ let mut v = run_pipeline_agg(t, params);+ if let Some(o) = v.as_object_mut() {+ o.insert("__type__".into(), Value::String(t.clone()));+ if let Some(m) = meta {+ o.insert("meta".into(), m.clone());+ }+ }+ bucket.insert(name.clone(), v);+ }+ if !plan.pipelines.is_empty() {+ resolve_sibling_pipelines(bucket);+ }+ }++ // ── dispatch ─────────────────────────────────────────────────────────++ fn exec_agg(&self, agg_type: &str, params: &Value, sub: Option<&Value>) -> Option<Value> {+ match agg_type {+ "avg" | "sum" | "min" | "max" | "stats" | "value_count" => {+ if sub.is_some() {+ return None;+ }+ self.exec_metric_top(metric_kind_of(agg_type)?, params)+ }+ "terms" => self.exec_terms(params, sub),+ "range" => self.exec_range(params, sub),+ "date_range" => self.exec_date_range(params, sub),+ "filter" => self.exec_filter(params, sub),+ "filters" => self.exec_filters(params, sub),+ "adjacency_matrix" => self.exec_adjacency_matrix(params, sub),+ "composite" => self.exec_composite(params, sub),+ "sampler" | "random_sampler" => self.exec_sampler(params, sub),+ "variable_width_histogram" => self.exec_vwh(params, sub),+ "date_histogram" => self.exec_date_histogram(params, sub),+ _ => None,+ }+ }++ // ── top-level metric ─────────────────────────────────────────────────++ fn exec_metric_top(&self, kind: MetricKind, params: &Value) -> Option<Value> {+ if !params_only(params, &["field", "format"]) {+ return None;+ }+ let field = params.get("field").and_then(Value::as_str)?;+ let seg_kind = self.seg_field_kind(field).ok()?;+ if kind != MetricKind::ValueCount {+ if seg_kind == Some(ColKind::Keyword) {+ return None;+ }+ if !self.mem_field_numeric_safe(field) {+ return None;+ }+ }+ let mut acc = MetricAcc::default();+ for s in &self.segs {+ match s.cols.get(field) {+ Some(Column::Numeric(n)) => {+ if n.live_count > 0 {+ if kind == MetricKind::ValueCount {+ acc.count += n.live_count;+ } else {+ // O(1) per segment via precomputed column stats.+ if acc.count == 0 {+ acc.min = n.live_min;+ acc.max = n.live_max;+ } else {+ if n.live_min < acc.min {+ acc.min = n.live_min;+ }+ if n.live_max > acc.max {+ acc.max = n.live_max;+ }+ }+ acc.count += n.live_count;+ acc.sum += n.live_sum;+ }+ }+ }+ Some(Column::Keyword(k)) => {+ // Only reachable for value_count.+ acc.count += (k.doc_count as u64).saturating_sub(k.null_bitmap.len());+ }+ None => {}+ }+ }+ let spec = MetricSpec {+ name: String::new(),+ kind,+ field: field.to_string(),+ meta: None,+ };+ for d in &self.mem_docs {+ Self::fold_mem_metric(d, &spec, &mut acc);+ }+ Some(Self::emit_metric(kind, &acc))+ }++ // ── shared fused row pass ────────────────────────────────────────────+ //+ // For a parent that assigns each segment row to at most one bucket slot+ // (terms ord → slot, date_histogram ord → slot, …), fold every metric+ // sub-agg and the optional top_hits accumulator in a single pass.++ #[allow(clippy::too_many_arguments)]+ fn fused_seg_pass(+ &self,+ si: usize,+ slot_of_row: &mut dyn FnMut(u32) -> Option<usize>,+ n_slots: usize,+ plan: &SubPlan,+ accs: &mut [Vec<MetricAcc>],+ tops: &mut [Vec<(f64, u64, DocRef)>],+ missing_sort_seen: &mut bool,+ ) -> Option<()> {+ let seg = &self.segs[si];+ // Resolve metric columns once.+ let mut num_cols: Vec<Option<&NumericColumn>> = Vec::with_capacity(plan.metrics.len());+ let mut kw_cols: Vec<Option<&KeywordColumn>> = Vec::with_capacity(plan.metrics.len());+ for m in &plan.metrics {+ match seg.cols.get(&m.field) {+ Some(Column::Numeric(n)) => {+ num_cols.push(Some(n));+ kw_cols.push(None);+ }+ Some(Column::Keyword(k)) => {+ if m.kind != MetricKind::ValueCount {+ return None;+ }+ num_cols.push(None);+ kw_cols.push(Some(k));+ }+ None => {+ num_cols.push(None);+ kw_cols.push(None);+ }+ }+ }+ let th_col: Option<&NumericColumn> = match &plan.top_hits {+ Some(spec) => match seg.cols.get(&spec.sort_field) {+ Some(Column::Numeric(n)) => Some(n),+ Some(_) => return None,+ None => None,+ },+ None => None,+ };+ let rank_off = self.seg_rank_offset(si);+ debug_assert!(accs.len() == plan.metrics.len());+ let _ = n_slots;++ for row in 0..seg.docs {+ let Some(slot) = slot_of_row(row) else { continue };+ for (mi, m) in plan.metrics.iter().enumerate() {+ match m.kind {+ MetricKind::ValueCount => {+ let present = if let Some(n) = num_cols[mi] {+ !n.null_bitmap.contains(row)+ } else if let Some(k) = kw_cols[mi] {+ !k.null_bitmap.contains(row)+ } else {+ false+ };+ if present {+ accs[mi][slot].add_presence();+ }+ }+ _ => {+ if let Some(n) = num_cols[mi] {+ if !n.null_bitmap.contains(row) {+ let v = f64::from_bits(n.data[row as usize] as u64);+ accs[mi][slot].add(v);+ }+ }+ }+ }+ }+ if let Some(spec) = &plan.top_hits {+ let v = match th_col {+ Some(n) if !n.null_bitmap.contains(row) => {+ f64::from_bits(n.data[row as usize] as u64)+ }+ _ => {+ *missing_sort_seen = true;+ continue;+ }+ };+ push_top(+ &mut tops[slot],+ spec.k,+ spec.desc,+ v,+ rank_off + row as u64,+ DocRef::Seg(si, row),+ );+ }+ }+ Some(())+ }++ /// Materialise + render a bucket's top_hits from its winner set.+ fn render_top_hits(+ &self,+ spec: &TopHitsSpec,+ winners: &[(f64, u64, DocRef)],+ bucket_total: u64,+ ) -> Option<Value> {+ let mut sorted: Vec<(f64, u64, DocRef)> = winners.to_vec();+ sort_top(&mut sorted, spec.desc);+ let docs: Vec<Value> = sorted+ .iter()+ .map(|(_, _, r)| self.fetch_doc(*r))+ .collect::<Option<Vec<_>>>()?;+ Some(run_top_hits_with_total(&spec.params, &docs, Some(bucket_total)))+ }++ // ── terms ────────────────────────────────────────────────────────────++ fn exec_terms(&self, params: &Value, sub: Option<&Value>) -> Option<Value> {+ if !params_only(params, &["field", "size", "order", "shard_size", "min_doc_count"]) {+ return None;+ }+ // Brute default & only supported min_doc_count is 1 (0 needs the+ // background corpus, >1 is honored below since it's a plain filter).+ let min_doc_count = params.get("min_doc_count").and_then(Value::as_u64).unwrap_or(1);+ if params.get("min_doc_count").is_some() && min_doc_count == 0 {+ return None;+ }+ let field = params.get("field").and_then(Value::as_str)?;+ // Boolean-mapped fields land in numeric 0/1 columns; the schema is+ // 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`).+ let is_bool = self.bool_fields.contains(field);+ match self.seg_field_kind(field) {+ Ok(Some(ColKind::Keyword)) | Ok(None) => {}+ Ok(Some(ColKind::Numeric)) if is_bool => {}+ _ => return None, // numeric terms keys → typed-key subtleties, bail+ }+ // Orders: only _count/_key entries supported (sub-agg ordering needs+ // the per-bucket sub results *before* truncation — brute-only).+ let orders = parse_orders(params);+ if orders.iter().any(|(k, _)| k != "_count" && k != "_key") {+ return None;+ }+ let size_opt: Option<usize> = params.get("size").and_then(Value::as_u64).map(|v| v as usize);+ let cap: Option<usize> = match size_opt {+ Some(0) => None,+ Some(n) => Some(n),+ None => Some(10),+ };++ let plan = self.plan_subs(sub, true)?;+ let has_row_work = !plan.metrics.is_empty() || plan.top_hits.is_some();++ // Global per-term state.+ struct TermState {+ count: u64,+ accs: Vec<MetricAcc>,+ top: Vec<(f64, u64, DocRef)>,+ }+ let mut terms_map: HashMap<String, TermState> = HashMap::new();+ let new_state = |plan: &SubPlan| TermState {+ count: 0,+ accs: vec![MetricAcc::default(); plan.metrics.len()],+ top: Vec::new(),+ };+ let mut missing_sort_seen = false;++ // Per-segment term column view: keyword ords, or a boolean numeric+ // column exposed as the two-term dictionary ["false", "true"].+ enum TCol<'x> {+ Kw(&'x KeywordColumn),+ Bool(&'x NumericColumn),+ }+ const BOOL_TERMS: [&str; 2] = ["false", "true"];++ for si in 0..self.segs.len() {+ let seg = &self.segs[si];+ let Some(col) = seg.cols.get(field) else { continue };+ let tcol = match col {+ Column::Keyword(k) => TCol::Kw(k),+ Column::Numeric(n) if is_bool => {+ // Sanity: the column must be pure 0/1 (a mapping change+ // could have let stray numbers in — brute would render+ // those as "0"/"1"/"2.5", not booleans → bail).+ let zeros = n.range_count(0.0, 0.0, true, true);+ let ones = n.range_count(1.0, 1.0, true, true);+ if zeros + ones != n.live_count {+ return None;+ }+ TCol::Bool(n)+ }+ _ => return None,+ };+ if !has_row_work {+ match &tcol {+ TCol::Kw(k) => {+ for (ord, &cnt) in k.per_ord_count.iter().enumerate() {+ if cnt > 0 {+ terms_map+ .entry(k.terms[ord].clone())+ .or_insert_with(|| new_state(&plan))+ .count += cnt as u64;+ }+ }+ }+ TCol::Bool(n) => {+ for (ord, term) in BOOL_TERMS.iter().enumerate() {+ let v = ord as f64;+ let cnt = n.range_count(v, v, true, true);+ if cnt > 0 {+ terms_map+ .entry((*term).to_string())+ .or_insert_with(|| new_state(&plan))+ .count += cnt;+ }+ }+ }+ }+ continue;+ }+ // Row pass: per-ord local accumulators, then merged by term.+ let n_ords = match &tcol {+ TCol::Kw(k) => k.terms.len(),+ TCol::Bool(_) => 2,+ };+ let term_of_ord = |ord: usize| -> &str {+ match &tcol {+ TCol::Kw(k) => k.terms[ord].as_str(),+ TCol::Bool(_) => BOOL_TERMS[ord],+ }+ };+ let mut accs: Vec<Vec<MetricAcc>> = plan+ .metrics+ .iter()+ .map(|_| vec![MetricAcc::default(); n_ords])+ .collect();+ let mut tops: Vec<Vec<(f64, u64, DocRef)>> = vec![Vec::new(); n_ords];+ let mut counts: Vec<u64> = vec![0; n_ords];+ {+ let mut slot_of_row = |row: u32| -> Option<usize> {+ let ord = match &tcol {+ TCol::Kw(k) => k.ord_for(row)? as usize,+ TCol::Bool(n) => {+ let bits = n.get(row)?;+ usize::from(f64::from_bits(bits as u64) != 0.0)+ }+ };+ counts[ord] += 1;+ Some(ord)+ };+ self.fused_seg_pass(+ si,+ &mut slot_of_row,+ n_ords,+ &plan,+ &mut accs,+ &mut tops,+ &mut missing_sort_seen,+ )?;+ }+ for ord in 0..n_ords {+ if counts[ord] == 0 {+ continue;+ }+ let st = terms_map+ .entry(term_of_ord(ord).to_string())+ .or_insert_with(|| new_state(&plan));+ st.count += counts[ord];+ for (mi, acc) in st.accs.iter_mut().enumerate() {+ merge_acc(acc, &accs[mi][ord]);+ }+ if let Some(spec) = &plan.top_hits {+ for e in tops[ord].drain(..) {+ push_top(&mut st.top, spec.k, spec.desc, e.0, e.1, e.2);+ }+ }+ }+ }++ // Memtable docs — brute extractor semantics (multi-value, weights).+ for (di, doc) in self.mem_docs.iter().enumerate() {+ let weight = doc_count_weight(doc);+ let vals = extract_field_values(doc, field);+ for term in vals {+ let st = terms_map.entry(term).or_insert_with(|| new_state(&plan));+ st.count += weight;+ for (mi, spec) in plan.metrics.iter().enumerate() {+ Self::fold_mem_metric(doc, spec, &mut st.accs[mi]);+ }+ if let Some(spec) = &plan.top_hits {+ match extract_numeric(doc, &spec.sort_field) {+ Some(v) => push_top(&mut st.top, spec.k, spec.desc, v, di as u64, DocRef::Mem(di)),+ None => missing_sort_seen = true,+ }+ }+ }+ }++ if plan.top_hits.is_some() && missing_sort_seen {+ // A bucket doc without the sort value would need brute+ // missing-last + _id tie-breaking — bail for exactness.+ return None;+ }++ // Order + truncate, mirroring run_terms' default and _count/_key+ // orders (cmp_terms_by_orders with no sub-agg references).+ let mut candidates: Vec<(String, TermState)> = terms_map+ .into_iter()+ .filter(|(_, st)| st.count >= min_doc_count)+ .collect();+ candidates.sort_by(|a, b| cmp_by_orders(&(a.0.clone(), a.1.count), &(b.0.clone(), b.1.count), &orders));+ if let Some(n) = cap {+ candidates.truncate(n);+ }++ let mut buckets: Vec<Value> = Vec::with_capacity(candidates.len());+ for (key, st) in candidates {+ let (typed_key, key_as_string) = typed_term_key(&key);+ let mut bucket = Map::new();+ bucket.insert("key".to_string(), typed_key);+ if let Some(kas) = key_as_string {+ bucket.insert("key_as_string".to_string(), json!(kas));+ }+ bucket.insert("doc_count".to_string(), json!(st.count));+ let th = match &plan.top_hits {+ Some(spec) => Some(self.render_top_hits(spec, &st.top, st.count)?),+ None => None,+ };+ self.finish_bucket(&mut bucket, &plan, &st.accs, th);+ buckets.push(Value::Object(bucket));+ }+ let buckets = apply_bucket_pipeline_ops(buckets, sub);++ Some(json!({+ "doc_count_error_upper_bound": 0,+ "sum_other_doc_count": 0,+ "buckets": buckets+ }))+ }++ // ── range (numeric) ──────────────────────────────────────────────────++ fn exec_range(&self, params: &Value, sub: Option<&Value>) -> Option<Value> {+ if !params_only(params, &["field", "ranges", "keyed"]) {+ return None;+ }+ let field = params.get("field").and_then(Value::as_str)?;+ let ranges = params.get("ranges").and_then(Value::as_array)?;+ if ranges.is_empty() {+ return None;+ }+ // Numeric-only (string bounds switch brute into date mode).+ for r in ranges {+ let o = r.as_object()?;+ if !o.keys().all(|k| k == "from" || k == "to" || k == "key") {+ return None;+ }+ for b in ["from", "to"] {+ if let Some(v) = o.get(b) {+ if !v.is_number() {+ return None;+ }+ }+ }+ }+ match self.seg_field_kind(field) {+ Ok(Some(ColKind::Numeric)) | Ok(None) => {}+ _ => return None,+ }+ if !self.mem_field_numeric_safe(field) {+ return None;+ }+ let plan = self.plan_subs(sub, false)?;++ let mut buckets: Vec<Value> = Vec::with_capacity(ranges.len());+ for range_def in ranges {+ let from: Option<f64> = range_def.get("from").and_then(Value::as_f64);+ let to: Option<f64> = range_def.get("to").and_then(Value::as_f64);+ let lo = from.unwrap_or(f64::NEG_INFINITY);+ let hi = to.unwrap_or(f64::INFINITY);+ // match: n >= from && n < to (to == +inf → inclusive is moot)+ let hi_incl = to.is_none();++ let mut count: u64 = 0;+ let mut accs: Vec<MetricAcc> = vec![MetricAcc::default(); plan.metrics.len()];+ for si in 0..self.segs.len() {+ let seg = &self.segs[si];+ let Some(Column::Numeric(n)) = seg.cols.get(field) else { continue };+ if plan.metrics.is_empty() {+ count += n.range_count(lo, hi, true, hi_incl) as u64;+ } else {+ let rows = n.range_doc_ids(lo, hi, true, hi_incl);+ count += rows.len() as u64;+ let mut wrapped: Vec<Vec<MetricAcc>> =+ accs.iter().map(|_| vec![MetricAcc::default()]).collect();+ let mut tops: Vec<Vec<(f64, u64, DocRef)>> = vec![Vec::new()];+ // Dense membership bitmap — the fused row pass probes+ // every row of the segment, so a HashSet here costs a+ // SipHash per row per range (~50 ms/M rows); a Vec<bool>+ // probe is ~1 ns.+ let mut in_range: Vec<bool> = vec![false; seg.docs as usize];+ for r in rows {+ if let Some(slot) = in_range.get_mut(r as usize) {+ *slot = true;+ }+ }+ let mut slot = |row: u32| -> Option<usize> {+ if in_range.get(row as usize).copied().unwrap_or(false) {+ Some(0)+ } else {+ None+ }+ };+ let mut ms = false;+ self.fused_seg_pass(si, &mut slot, 1, &plan, &mut wrapped, &mut tops, &mut ms)?;+ for (mi, w) in wrapped.iter().enumerate() {+ merge_acc(&mut accs[mi], &w[0]);+ }+ }+ }+ for doc in &self.mem_docs {+ let Some(v) = extract_numeric(doc, field) else { continue };+ let matches = match (from, to) {+ (Some(f), Some(t)) => v >= f && v < t,+ (Some(f), None) => v >= f,+ (None, Some(t)) => v < t,+ (None, None) => true,+ };+ if !matches {+ continue;+ }+ count += 1;+ for (mi, spec) in plan.metrics.iter().enumerate() {+ Self::fold_mem_metric(doc, spec, &mut accs[mi]);+ }+ }++ let key = range_def+ .get("key")+ .and_then(Value::as_str)+ .map(String::from)+ .unwrap_or_else(|| match (from, to) {+ (Some(f), Some(t)) => format!("{}-{}", format_range_val(f), format_range_val(t)),+ (Some(f), None) => format!("{}-*", format_range_val(f)),+ (None, Some(t)) => format!("*-{}", format_range_val(t)),+ (None, None) => "*-*".to_string(),+ });+ let mut bucket = Map::new();+ bucket.insert("key".to_string(), json!(key));+ bucket.insert("doc_count".to_string(), json!(count));+ if let Some(f) = from {+ bucket.insert("from".to_string(), json!(f));+ }+ if let Some(t) = to {+ bucket.insert("to".to_string(), json!(t));+ }+ self.finish_bucket(&mut bucket, &plan, &accs, None);+ buckets.push(Value::Object(bucket));+ }+ let buckets = apply_bucket_pipeline_ops(buckets, sub);++ let keyed = params.get("keyed").and_then(Value::as_bool).unwrap_or(false);+ if keyed {+ let mut keyed_map = Map::new();+ for mut b in buckets {+ let k = b.get("key").and_then(Value::as_str).unwrap_or("").to_string();+ if let Some(obj) = b.as_object_mut() {+ obj.remove("key");+ }+ keyed_map.insert(k, b);+ }+ return Some(json!({ "buckets": Value::Object(keyed_map) }));+ }+ Some(json!({ "buckets": buckets }))+ }++ // ── date_range ───────────────────────────────────────────────────────++ fn exec_date_range(&self, params: &Value, sub: Option<&Value>) -> Option<Value> {+ if sub.is_some() {+ return None;+ }+ if !params_only(params, &["field", "ranges", "keyed"]) {+ return None;+ }+ let field = params.get("field").and_then(Value::as_str).unwrap_or("@timestamp");+ let ranges = params.get("ranges").and_then(Value::as_array)?;+ match self.seg_field_kind(field) {+ Ok(Some(ColKind::Keyword)) | Ok(None) => {}+ _ => return None, // numeric-date columns: brute parse semantics differ; bail+ }++ // Fractional-precision detection — mirror run_date_range.+ let nanos_digits: usize = ranges+ .iter()+ .flat_map(|r| {+ let f = r.get("from").and_then(Value::as_str).map(detect_fractional_digits).unwrap_or(0);+ let t = r.get("to").and_then(Value::as_str).map(detect_fractional_digits).unwrap_or(0);+ [f, t]+ })+ .max()+ .unwrap_or(3);+ let nanos_digits = if nanos_digits >= 9 { 9 } else { 3 };+ let render = |ms: i64| -> String { render_iso_date(ms, nanos_digits, None) };++ // Parallel pre-warm of the per-segment date-ordinal cache (chrono+ // parsing of every distinct term is the dominant first-call cost).+ {+ use rayon::prelude::*;+ self.segs.par_iter().for_each(|seg| {+ if matches!(seg.cols.get(field), Some(Column::Keyword(_))) {+ let _ = self.date_ord_index(seg, field);+ }+ });+ }+ // Per-segment parsed date ordinals (cached on the Index).+ let mut ord_ms_per_seg: Vec<Option<std::sync::Arc<Vec<i64>>>> = Vec::new();+ for s in &self.segs {+ match s.cols.get(field) {+ Some(Column::Keyword(_)) => {+ ord_ms_per_seg.push(Some(self.date_ord_index(s, field)?));+ }+ _ => ord_ms_per_seg.push(None),+ }+ }++ let keyed = params.get("keyed").and_then(Value::as_bool).unwrap_or(false);+ let mut keyed_map = Map::new();+ let mut buckets: Vec<Value> = Vec::new();+ for range_def in ranges {+ let o = range_def.as_object()?;+ if !o.keys().all(|k| k == "from" || k == "to" || k == "key") {+ return None;+ }+ let from_ms = range_def.get("from").and_then(parse_date_ms);+ let to_ms = range_def.get("to").and_then(parse_date_ms);+ // Unparseable explicit bound → brute would fall to format-aware+ // parsing; bail to stay exact.+ if range_def.get("from").is_some() && from_ms.is_none() {+ return None;+ }+ if range_def.get("to").is_some() && to_ms.is_none() {+ return None;+ }+ let from_str_in = range_def.get("from").and_then(Value::as_str);+ let to_str_in = range_def.get("to").and_then(Value::as_str);++ let mut count: u64 = 0;+ for (si, s) in self.segs.iter().enumerate() {+ let Some(Column::Keyword(k)) = s.cols.get(field) else { continue };+ let ord_ms = ord_ms_per_seg[si].as_ref()?;+ for (ord, &cnt) in k.per_ord_count.iter().enumerate() {+ if cnt == 0 {+ continue;+ }+ let ms = ord_ms[ord];+ if ms == i64::MIN {+ continue; // unparseable value — brute skips too+ }+ let pass_from = from_ms.map(|f| ms >= f).unwrap_or(true);+ let pass_to = to_ms.map(|t| ms < t).unwrap_or(true);+ if pass_from && pass_to {+ count += cnt as u64;+ }+ }+ }+ for doc in &self.mem_docs {+ let v = doc.get(field);+ let Some(ms) = v.and_then(parse_date_ms) else { continue };+ let pass_from = from_ms.map(|f| ms >= f).unwrap_or(true);+ let pass_to = to_ms.map(|t| ms < t).unwrap_or(true);+ if pass_from && pass_to {+ count += doc_count_weight(doc);+ }+ }++ let from_key = match (from_ms, from_str_in) {+ (Some(ms), _) => render(ms),+ (None, Some(s)) => s.to_string(),+ _ => "*".to_string(),+ };+ let to_key = match (to_ms, to_str_in) {+ (Some(ms), _) => render(ms),+ (None, Some(s)) => s.to_string(),+ _ => "*".to_string(),+ };+ let default_key = format!("{}-{}", from_key, to_key);+ let key = range_def+ .get("key")+ .and_then(Value::as_str)+ .map(String::from)+ .unwrap_or(default_key);++ let mut bucket = Map::new();+ if !keyed {+ bucket.insert("key".to_string(), json!(key));+ }+ if let Some(ms) = from_ms {+ bucket.insert("from".to_string(), json!(ms));+ bucket.insert("from_as_string".to_string(), json!(render(ms)));+ }+ if let Some(ms) = to_ms {+ bucket.insert("to".to_string(), json!(ms));+ bucket.insert("to_as_string".to_string(), json!(render(ms)));+ }+ bucket.insert("doc_count".to_string(), json!(count));+ if keyed {+ keyed_map.insert(key, Value::Object(bucket));+ } else {+ buckets.push(Value::Object(bucket));+ }+ }+ if keyed {+ Some(json!({ "buckets": Value::Object(keyed_map) }))+ } else {+ Some(json!({ "buckets": buckets }))+ }+ }++ /// Cached ord → epoch-ms mapping for a keyword date column.+ /// `i64::MIN` marks unparseable terms.+ fn date_ord_index(&self, seg: &SegEntry, field: &str) -> Option<std::sync::Arc<Vec<i64>>> {+ let key = (seg.id.clone(), field.to_string());+ if let Some(v) = self.idx.fast_date_cache.get(&key) {+ return Some(std::sync::Arc::clone(v.value()));+ }+ let Some(Column::Keyword(k)) = seg.cols.get(field) else {+ return None;+ };+ let mut ord_ms: Vec<i64> = Vec::with_capacity(k.terms.len());+ for t in &k.terms {+ ord_ms.push(parse_date_ms(&Value::String(t.clone())).unwrap_or(i64::MIN));+ }+ let arc = std::sync::Arc::new(ord_ms);+ self.idx.fast_date_cache.insert(key, std::sync::Arc::clone(&arc));+ Some(arc)+ }++ // ── filter / filters / adjacency_matrix ─────────────────────────────++ fn exec_filter(&self, filter_query: &Value, sub: Option<&Value>) -> Option<Value> {+ let plan = self.plan_subs(sub, false)?;+ let pred = compile_pred(filter_query)?;+ self.check_pred_kinds(&pred)?;++ let mut count: u64 = 0;+ let mut accs: Vec<MetricAcc> = vec![MetricAcc::default(); plan.metrics.len()];+ for si in 0..self.segs.len() {+ let seg = &self.segs[si];+ let sp = resolve_pred(&seg.cols, &pred)?;+ if plan.metrics.is_empty() {+ count += seg_pred_count(&sp, seg.docs);+ } else {+ let mut wrapped: Vec<Vec<MetricAcc>> =+ accs.iter().map(|_| vec![MetricAcc::default()]).collect();+ let mut tops: Vec<Vec<(f64, u64, DocRef)>> = vec![Vec::new()];+ let mut slot = |row: u32| -> Option<usize> {+ if seg_pred_matches(&sp, row) {+ count += 1;+ Some(0)+ } else {+ None+ }+ };+ let mut ms = false;+ self.fused_seg_pass(si, &mut slot, 1, &plan, &mut wrapped, &mut tops, &mut ms)?;+ for (mi, w) in wrapped.iter().enumerate() {+ merge_acc(&mut accs[mi], &w[0]);+ }+ }+ }+ for doc in &self.mem_docs {+ if doc_matches_filter(doc, filter_query) {+ count += doc_count_weight(doc);+ for (mi, spec) in plan.metrics.iter().enumerate() {+ Self::fold_mem_metric(doc, spec, &mut accs[mi]);+ }+ }+ }+ let mut bucket = Map::new();+ bucket.insert("doc_count".to_string(), json!(count));+ self.finish_bucket(&mut bucket, &plan, &accs, None);+ Some(Value::Object(bucket))+ }++ fn exec_filters(&self, params: &Value, sub: Option<&Value>) -> Option<Value> {+ if !params_only(params, &["filters", "keyed"]) {+ return None;+ }+ let plan = self.plan_subs(sub, false)?;+ let filters_val = params.get("filters")?;+ let keyed_override = params.get("keyed").and_then(Value::as_bool);++ // Normalise to (Option<name>, query) preserving order.+ let entries: Vec<(Option<String>, &Value)> = match filters_val {+ Value::Object(map) => map.iter().map(|(k, v)| (Some(k.clone()), v)).collect(),+ Value::Array(arr) => arr.iter().map(|v| (None, v)).collect(),+ _ => return None,+ };+ let named = matches!(filters_val, Value::Object(_));+ let keyed = if named { keyed_override.unwrap_or(true) } else { false };++ let mut rendered: Vec<(Option<String>, Value)> = Vec::with_capacity(entries.len());+ for (name, q) in &entries {+ let one = self.filter_bucket_body(q, &plan)?;+ rendered.push((name.clone(), one));+ }++ if named && keyed {+ let mut buckets = Map::new();+ for (name, b) in rendered {+ buckets.insert(name.unwrap_or_default(), b);+ }+ Some(json!({ "buckets": buckets }))+ } else if named {+ let mut buckets: Vec<Value> = Vec::new();+ for (name, mut b) in rendered {+ if let Some(o) = b.as_object_mut() {+ o.insert("key".to_string(), Value::String(name.unwrap_or_default()));+ }+ buckets.push(b);+ }+ Some(json!({ "buckets": buckets }))+ } else {+ let buckets: Vec<Value> = rendered.into_iter().map(|(_, b)| b).collect();+ Some(json!({ "buckets": buckets }))+ }+ }++ /// A single filters-agg bucket body: `{doc_count, <subs>}`.+ fn filter_bucket_body(&self, filter_query: &Value, plan: &SubPlan) -> Option<Value> {+ let pred = compile_pred(filter_query)?;+ self.check_pred_kinds(&pred)?;+ let mut count: u64 = 0;+ let mut accs: Vec<MetricAcc> = vec![MetricAcc::default(); plan.metrics.len()];+ for si in 0..self.segs.len() {+ let seg = &self.segs[si];+ let sp = resolve_pred(&seg.cols, &pred)?;+ if plan.metrics.is_empty() {+ count += seg_pred_count(&sp, seg.docs);+ } else {+ let mut wrapped: Vec<Vec<MetricAcc>> =+ accs.iter().map(|_| vec![MetricAcc::default()]).collect();+ let mut tops: Vec<Vec<(f64, u64, DocRef)>> = vec![Vec::new()];+ let mut slot = |row: u32| -> Option<usize> {+ if seg_pred_matches(&sp, row) {+ count += 1;+ Some(0)+ } else {+ None+ }+ };+ let mut ms = false;+ self.fused_seg_pass(si, &mut slot, 1, plan, &mut wrapped, &mut tops, &mut ms)?;+ for (mi, w) in wrapped.iter().enumerate() {+ merge_acc(&mut accs[mi], &w[0]);+ }+ }+ }+ for doc in &self.mem_docs {+ if doc_matches_filter(doc, filter_query) {+ count += doc_count_weight(doc);+ for (mi, spec) in plan.metrics.iter().enumerate() {+ Self::fold_mem_metric(doc, spec, &mut accs[mi]);+ }+ }+ }+ let mut bucket = Map::new();+ bucket.insert("doc_count".to_string(), json!(count));+ self.finish_bucket(&mut bucket, plan, &accs, None);+ Some(Value::Object(bucket))+ }++ fn exec_adjacency_matrix(&self, params: &Value, sub: Option<&Value>) -> Option<Value> {+ if sub.is_some() {+ return None;+ }+ if !params_only(params, &["filters"]) {+ return None;+ }+ let filters_map = params.get("filters").and_then(Value::as_object)?;+ let names: Vec<&String> = filters_map.keys().collect();+ let preds: Vec<Pred> = filters_map+ .values()+ .map(compile_pred)+ .collect::<Option<Vec<_>>>()?;+ for p in &preds {+ self.check_pred_kinds(p)?;+ }+ let n = preds.len();+ if n == 0 {+ return Some(json!({ "buckets": [] }));+ }+ if n > 32 {+ return None;+ }+ let mut singles: Vec<u64> = vec![0; n];+ let mut pairs: Vec<u64> = vec![0; n * n];+ for seg in &self.segs {+ let sps: Vec<SegPred<'_>> = preds+ .iter()+ .map(|p| resolve_pred(&seg.cols, p))+ .collect::<Option<Vec<_>>>()?;+ for row in 0..seg.docs {+ let mut mask: u32 = 0;+ for (i, sp) in sps.iter().enumerate() {+ if seg_pred_matches(sp, row) {+ mask |= 1 << i;+ }+ }+ if mask == 0 {+ continue;+ }+ let mut m = mask;+ while m != 0 {+ let i = m.trailing_zeros() as usize;+ m &= m - 1;+ singles[i] += 1;+ let mut m2 = mask & !((1u32 << (i + 1)) - 1);+ while m2 != 0 {+ let j = m2.trailing_zeros() as usize;+ m2 &= m2 - 1;+ pairs[i * n + j] += 1;+ }+ }+ }+ }+ for doc in &self.mem_docs {+ let matches: Vec<bool> = filters_map+ .values()+ .map(|q| doc_matches_filter(doc, q))+ .collect();+ for i in 0..n {+ if matches[i] {+ singles[i] += 1;+ for j in (i + 1)..n {+ if matches[j] {+ pairs[i * n + j] += 1;+ }+ }+ }+ }+ }+ let mut buckets: Vec<Value> = Vec::new();+ for i in 0..n {+ if singles[i] > 0 {+ buckets.push(json!({ "key": names[i], "doc_count": singles[i] }));+ }+ }+ for i in 0..n {+ for j in (i + 1)..n {+ if pairs[i * n + j] > 0 {+ buckets.push(json!({+ "key": format!("{}&{}", names[i], names[j]),+ "doc_count": pairs[i * n + j]+ }));+ }+ }+ }+ buckets.sort_by(|a, b| {+ let ka = a.get("key").and_then(Value::as_str).unwrap_or("");+ let kb = b.get("key").and_then(Value::as_str).unwrap_or("");+ ka.cmp(kb)+ });+ Some(json!({ "buckets": buckets }))+ }++ fn check_pred_kinds(&self, pred: &Pred) -> Option<()> {+ match pred {+ Pred::MatchAll => Some(()),+ Pred::TermKw { field, .. } | Pred::TermsKw { field, .. } => {+ match self.seg_field_kind(field) {+ Ok(Some(ColKind::Keyword)) | Ok(None) => Some(()),+ _ => None,+ }+ }+ Pred::RangeNum { field, .. } => match self.seg_field_kind(field) {+ Ok(Some(ColKind::Numeric)) | Ok(None) => Some(()),+ _ => None,+ },+ }+ }++ // ── composite ────────────────────────────────────────────────────────++ fn exec_composite(&self, params: &Value, sub: Option<&Value>) -> Option<Value> {+ if sub.is_some() {+ return None;+ }+ if !params_only(params, &["sources", "size"]) {+ return None;+ }+ let sources = params.get("sources").and_then(Value::as_array)?;+ let size = params.get("size").and_then(Value::as_u64).unwrap_or(10) as usize;++ // All sources must be plain `terms` over keyword columns.+ let mut src_names: Vec<String> = Vec::new();+ let mut src_fields: Vec<String> = Vec::new();+ for src in sources {+ let src_obj = src.as_object()?;+ if src_obj.len() != 1 {+ return None;+ }+ let (name, spec) = src_obj.iter().next()?;+ let spec_obj = spec.as_object()?;+ if spec_obj.len() != 1 {+ return None;+ }+ let (t, tp) = spec_obj.iter().next()?;+ if t != "terms" || !params_only(tp, &["field"]) {+ return None;+ }+ let field = tp.get("field").and_then(Value::as_str)?;+ match self.seg_field_kind(field) {+ Ok(Some(ColKind::Keyword)) | Ok(None) => {}+ _ => return None,+ }+ src_names.push(name.clone());+ src_fields.push(field.to_string());+ }+ if src_names.is_empty() {+ return Some(json!({ "buckets": [] }));+ }++ let mut counts: HashMap<Vec<String>, u64> = HashMap::new();+ for seg in &self.segs {+ let cols: Vec<&KeywordColumn> = match src_fields+ .iter()+ .map(|f| match seg.cols.get(f) {+ Some(Column::Keyword(k)) => Some(k),+ _ => None,+ })+ .collect::<Option<Vec<_>>>()+ {+ Some(c) => c,+ None => continue, // some source field absent → no docs from this segment+ };+ let mut local: HashMap<Vec<u32>, u64> = HashMap::new();+ 'rows: for row in 0..seg.docs {+ let mut key: Vec<u32> = Vec::with_capacity(cols.len());+ for k in &cols {+ match k.ord_for(row) {+ Some(o) => key.push(o),+ None => continue 'rows,+ }+ }+ *local.entry(key).or_insert(0) += 1;+ }+ for (ords, c) in local {+ let key: Vec<String> = ords+ .iter()+ .zip(cols.iter())+ .map(|(o, k)| k.terms[*o as usize].clone())+ .collect();+ *counts.entry(key).or_insert(0) += c;+ }+ }+ for doc in &self.mem_docs {+ let weight = doc_count_weight(doc);+ // Cross-product across multi-valued fields — brute semantics.+ let mut keys: Vec<Vec<String>> = vec![vec![]];+ let mut dead = false;+ for f in &src_fields {+ let vals = extract_field_values(doc, f);+ if vals.is_empty() {+ dead = true;+ break;+ }+ let mut next: Vec<Vec<String>> = Vec::new();+ for k in &keys {+ for v in &vals {+ let mut nk = k.clone();+ nk.push(v.clone());+ next.push(nk);+ }+ }+ keys = next;+ }+ if dead {+ continue;+ }+ for k in keys {+ *counts.entry(k).or_insert(0) += weight;+ }+ }++ let mut sorted_keys: Vec<Vec<String>> = counts.keys().cloned().collect();+ sorted_keys.sort_by(|a, b| composite_cmp(a, b));+ sorted_keys.truncate(size);++ let result_buckets: Vec<Value> = sorted_keys+ .iter()+ .map(|key| {+ let mut key_obj = Map::new();+ for (i, name) in src_names.iter().enumerate() {+ let val = key.get(i).cloned().unwrap_or_default();+ if let Ok(n) = val.parse::<i64>() {+ key_obj.insert(name.clone(), json!(n));+ } else if let Ok(f) = val.parse::<f64>() {+ key_obj.insert(+ name.clone(),+ serde_json::Number::from_f64(f)+ .map(Value::Number)+ .unwrap_or(Value::String(val.clone())),+ );+ } else {+ key_obj.insert(name.clone(), Value::String(val));+ }+ }+ json!({ "key": Value::Object(key_obj), "doc_count": counts[key] })+ })+ .collect();++ let after_key = result_buckets+ .last()+ .and_then(|b| b.get("key").cloned())+ .unwrap_or(Value::Null);+ let mut out = json!({ "buckets": result_buckets });+ if !after_key.is_null() {+ if let Some(obj) = out.as_object_mut() {+ obj.insert("after_key".into(), after_key);+ }+ }+ Some(out)+ }++ // ── sampler / random_sampler ─────────────────────────────────────────++ fn exec_sampler(&self, params: &Value, sub: Option<&Value>) -> Option<Value> {+ if !params_only(params, &["shard_size", "probability", "seed", "max_docs_per_value"]) {+ return None;+ }+ if let Some(s) = sub {+ if sub_tree_needs_background(s) {+ return None;+ }+ }+ let shard_size = params.get("shard_size").and_then(Value::as_u64).unwrap_or(200) as usize;+ if shard_size > 10_000 {+ return None; // keep the materialisation bounded+ }+ // Sample = first `shard_size` docs in brute corpus order+ // (memtable docs, then segments in snapshot order). With+ // match_all every doc scores equal, so the brute sampler's+ // stable score sort preserves exactly this prefix.+ let mut sample: Vec<Value> = Vec::with_capacity(shard_size);+ for d in &self.mem_docs {+ if sample.len() >= shard_size {+ break;+ }+ sample.push(d.clone());+ }+ let mut si = 0usize;+ while sample.len() < shard_size && si < self.segs.len() {+ let take = (shard_size - sample.len()).min(self.segs[si].docs as usize);+ for row in 0..take {+ sample.push(self.fetch_seg_doc(si, row as u32)?);+ }+ si += 1;+ }+ // Brute enriches the first `materialisation_limit` (256) corpus docs+ // with `_score: 1.0` (the match_all hit window). Mirror it so+ // score-sensitive sub-aggs (top_hits default sort) behave the same.+ for d in sample.iter_mut().take(256) {+ if let Some(o) = d.as_object_mut() {+ o.insert("_score".to_string(), json!(1.0));+ }+ }+ Some(run_sampler(params, sub, &sample, &sample))+ }++ // ── variable_width_histogram ─────────────────────────────────────────++ fn exec_vwh(&self, params: &Value, sub: Option<&Value>) -> Option<Value> {+ if sub.is_some() {+ return None;+ }+ if !params_only(params, &["field", "buckets"]) {+ return None;+ }+ let field = params.get("field").and_then(Value::as_str)?;+ let num_buckets = params.get("buckets").and_then(Value::as_u64).unwrap_or(10) as usize;+ match self.seg_field_kind(field) {+ Ok(Some(ColKind::Numeric)) | Ok(None) => {}+ _ => return None,+ }+ if !self.mem_field_numeric_safe(field) {+ return None;+ }++ // Distinct (value → weight) across all sources, ascending by value.+ // Each segment's `n.sorted` is already value-ascending, so collapse+ // each into a distinct-run list and k-way merge — no HashMap (a 1M-row+ // corpus paid ~300 ms of SipHash there), no global re-sort.+ let mut runs: Vec<Vec<(f64, u64)>> = Vec::with_capacity(self.segs.len() + 1);+ for seg in &self.segs {+ let Some(Column::Numeric(n)) = seg.cols.get(field) else { continue };+ let mut run: Vec<(f64, u64)> = Vec::new();+ let mut i = 0usize;+ while i < n.sorted.len() {+ let bits = n.sorted[i].0;+ let mut j = i + 1;+ while j < n.sorted.len() && n.sorted[j].0 == bits {+ j += 1;+ }+ run.push((f64::from_bits(bits as u64), (j - i) as u64));+ i = j;+ }+ if !run.is_empty() {+ runs.push(run);+ }+ }+ if !self.mem_docs.is_empty() {+ let mut mem_vals: Vec<f64> = self+ .mem_docs+ .iter()+ .filter_map(|doc| extract_numeric(doc, field))+ .collect();+ mem_vals.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));+ let mut run: Vec<(f64, u64)> = Vec::new();+ for v in mem_vals {+ match run.last_mut() {+ Some((lv, w)) if *lv == v => *w += 1,+ _ => run.push((v, 1)),+ }+ }+ if !run.is_empty() {+ runs.push(run);+ }+ }+ let vals = merge_weighted_runs(runs);+ if vals.is_empty() {+ return Some(json!({ "buckets": [] }));+ }++ // Bound the exact agglomerative clustering working set. The+ // heap-merge in `vwh_cluster` does (distinct − buckets) merges — on a+ // ~500 k-distinct float column that's hundreds of ms. ES's own VWH+ // is approximate (it never keeps more than shard_size ≈ buckets×50+ // clusters while collecting), so pre-coarsening the sorted distinct+ // list into equal-weight groups before the exact pass matches ES's+ // accuracy class while keeping the whole agg in the ~10 ms range.+ // Below the cap the behaviour is byte-identical to before.+ const VWH_COARSE_CAP: usize = 5_000;+ let vals = if vals.len() > VWH_COARSE_CAP.max(num_buckets * 50) {+ coarsen_weighted(&vals, VWH_COARSE_CAP.max(num_buckets * 50))+ } else {+ vals+ };++ let buckets = vwh_cluster(&vals, num_buckets);+ let result_buckets: Vec<Value> = buckets+ .iter()+ .map(|b| {+ json!({+ "min": b.min, "key": b.sum / b.count as f64, "max": b.max,+ "doc_count": b.count+ })+ })+ .collect();+ Some(json!({ "buckets": result_buckets }))+ }++ // ── date_histogram ───────────────────────────────────────────────────++ fn exec_date_histogram(&self, params: &Value, sub: Option<&Value>) -> Option<Value> {+ if !params_only(+ params,+ &["field", "calendar_interval", "fixed_interval", "interval", "format", "keyed", "min_doc_count"],+ ) {+ return None;+ }+ let field = params.get("field").and_then(Value::as_str)?;+ match self.seg_field_kind(field) {+ Ok(Some(ColKind::Keyword)) | Ok(None) => {}+ _ => return None,+ }+ let interval_str = params+ .get("fixed_interval")+ .or_else(|| params.get("calendar_interval"))+ .or_else(|| params.get("interval"))+ .and_then(Value::as_str)+ .unwrap_or("1d");+ let interval_ms = interval_to_ms(interval_str)?;+ let use_calendar = is_calendar_interval(interval_str);+ let bucket_of = |ms: i64| -> i64 {+ if use_calendar {+ calendar_bucket_key(ms, interval_str)+ } else {+ ms.div_euclid(interval_ms) * interval_ms+ }+ };+ let next_bucket = |key: i64| -> i64 {+ let next = if use_calendar {+ next_calendar_bucket(key, interval_str)+ } else {+ key + interval_ms+ };+ if next <= key { key + interval_ms } else { next }+ };++ // Parallel pre-warm of the per-segment date-ordinal cache (chrono+ // parsing of every distinct term is the dominant first-call cost).+ {+ use rayon::prelude::*;+ self.segs.par_iter().for_each(|seg| {+ if matches!(seg.cols.get(field), Some(Column::Keyword(_))) {+ let _ = self.date_ord_index(seg, field);+ }+ });+ }+ let plan = self.plan_subs(sub, false)?;+ let has_row_work = !plan.metrics.is_empty();++ // Global bucket table.+ let mut bucket_ids: HashMap<i64, usize> = HashMap::new();+ let mut bucket_keys: Vec<i64> = Vec::new();+ let mut counts: Vec<u64> = Vec::new();+ let mut accs: Vec<Vec<MetricAcc>> = plan.metrics.iter().map(|_| Vec::new()).collect();+ let mut ensure_bucket =+ |key: i64,+ bucket_ids: &mut HashMap<i64, usize>,+ bucket_keys: &mut Vec<i64>,+ counts: &mut Vec<u64>,+ accs: &mut Vec<Vec<MetricAcc>>| -> usize {+ *bucket_ids.entry(key).or_insert_with(|| {+ bucket_keys.push(key);+ counts.push(0);+ for a in accs.iter_mut() {+ a.push(MetricAcc::default());+ }+ bucket_keys.len() - 1+ })+ };++ let mut missing_sort_seen = false;+ for si in 0..self.segs.len() {+ let seg = &self.segs[si];+ let Some(Column::Keyword(k)) = seg.cols.get(field) else { continue };+ let ord_ms = self.date_ord_index(seg, field)?;+ // ord → bucket slot table.+ let mut ord_slot: Vec<i32> = Vec::with_capacity(k.terms.len());+ for (ord, &ms) in ord_ms.iter().enumerate() {+ if ms == i64::MIN || k.per_ord_count.get(ord).copied().unwrap_or(0) == 0 {+ ord_slot.push(-1);+ continue;+ }+ let slot = ensure_bucket(+ bucket_of(ms),+ &mut bucket_ids,+ &mut bucket_keys,+ &mut counts,+ &mut accs,+ );+ ord_slot.push(slot as i32);+ }+ if !has_row_work {+ for (ord, &cnt) in k.per_ord_count.iter().enumerate() {+ if cnt > 0 && ord_slot[ord] >= 0 {+ counts[ord_slot[ord] as usize] += cnt as u64;+ }+ }+ continue;+ }+ let n_slots = bucket_keys.len();+ let mut tops: Vec<Vec<(f64, u64, DocRef)>> = vec![Vec::new(); n_slots.max(1)];+ {+ let counts_ref = &mut counts;+ let mut slot_of_row = |row: u32| -> Option<usize> {+ let ord = k.ord_for(row)? as usize;+ let s = ord_slot[ord];+ if s < 0 {+ return None;+ }+ counts_ref[s as usize] += 1;+ Some(s as usize)+ };+ self.fused_seg_pass(+ si,+ &mut slot_of_row,+ n_slots,+ &plan,+ &mut accs,+ &mut tops,+ &mut missing_sort_seen,+ )?;+ }+ }+ // Memtable docs — brute multi-value date extraction with per-doc+ // bucket dedup.+ for doc in &self.mem_docs {+ let raws = extract_date_ms_values(doc, field);+ let weight = doc_count_weight(doc);+ let mut seen: Vec<i64> = Vec::with_capacity(raws.len());+ for ms in raws {+ let key = bucket_of(ms);+ if seen.contains(&key) {+ continue;+ }+ seen.push(key);+ let slot = ensure_bucket(key, &mut bucket_ids, &mut bucket_keys, &mut counts, &mut accs);+ counts[slot] += weight;+ for (mi, spec) in plan.metrics.iter().enumerate() {+ Self::fold_mem_metric(doc, spec, &mut accs[mi][slot]);+ }+ }+ }++ let min_doc_count = params.get("min_doc_count").and_then(Value::as_u64).unwrap_or(0);+ let keyed = params.get("keyed").and_then(Value::as_bool).unwrap_or(false);++ // Bucket-key set: gap-fill when min_doc_count == 0 (brute default).+ const MAX_BUCKETS: i64 = 65_536;+ let mut final_keys: Vec<i64> = if min_doc_count > 0 {+ bucket_keys.clone()+ } else if let (Some(&min_key), Some(&max_key)) =+ (bucket_keys.iter().min(), bucket_keys.iter().max())+ {+ let mut span: i64 = 0;+ let mut probe = min_key;+ while probe <= max_key {+ span += 1;+ if span > MAX_BUCKETS {+ return Some(json!({+ "error": format!(+ "Trying to create too many buckets. Must be less than or equal to: [{}] but this number of buckets was exceeded. This limit can be set by changing the [search.max_buckets] cluster level setting.",+ MAX_BUCKETS+ )+ }));+ }+ probe = next_bucket(probe);+ }+ let mut keys = Vec::with_capacity(span as usize);+ let mut k = min_key;+ while k <= max_key {+ keys.push(k);+ k = next_bucket(k);+ }+ keys+ } else {+ bucket_keys.clone()+ };+ final_keys.sort_unstable();+ if min_doc_count > 0 {+ final_keys.retain(|k| {+ bucket_ids+ .get(k)+ .map(|&s| counts[s] >= min_doc_count)+ .unwrap_or(false)+ });+ }++ let fmt_param = params.get("format").and_then(Value::as_str);+ let render_key = |key: i64| -> String {+ let dt_val = chrono::DateTime::from_timestamp_millis(key).unwrap_or_default();+ render_date_format(fmt_param, key, dt_val)+ };++ let empty_accs: Vec<MetricAcc> = vec![MetricAcc::default(); plan.metrics.len()];+ let mut result_buckets: Vec<Value> = Vec::with_capacity(final_keys.len());+ for &key in &final_keys {+ let slot = bucket_ids.get(&key).copied();+ let count = slot.map(|s| counts[s]).unwrap_or(0);+ let mut bucket = Map::new();+ bucket.insert("key".to_string(), json!(key));+ bucket.insert("key_as_string".to_string(), json!(render_key(key)));+ bucket.insert("doc_count".to_string(), json!(count));+ let bucket_accs: Vec<MetricAcc> = match slot {+ Some(s) => plan.metrics.iter().enumerate().map(|(mi, _)| accs[mi][s]).collect(),+ None => empty_accs.clone(),+ };+ self.finish_bucket(&mut bucket, &plan, &bucket_accs, None);+ result_buckets.push(Value::Object(bucket));+ }+ let result_buckets = apply_bucket_pipeline_ops(result_buckets, sub);++ if keyed {+ let mut map = Map::new();+ for b in result_buckets {+ let k = b+ .get("key_as_string")+ .and_then(Value::as_str)+ .map(str::to_string)+ .or_else(|| b.get("key").and_then(Value::as_i64).map(|i| i.to_string()))+ .unwrap_or_default();+ map.insert(k, b);+ }+ Some(json!({ "buckets": Value::Object(map) }))+ } else {+ Some(json!({ "buckets": result_buckets }))+ }+ }+}++fn metric_type_name(kind: MetricKind) -> &'static str {+ match kind {+ MetricKind::Avg => "avg",+ MetricKind::Sum => "sum",+ MetricKind::Min => "min",+ MetricKind::Max => "max",+ MetricKind::Stats => "stats",+ MetricKind::ValueCount => "value_count",+ }+}++fn merge_acc(into: &mut MetricAcc, other: &MetricAcc) {+ if other.count == 0 {+ return;+ }+ if into.count == 0 {+ *into = *other;+ return;+ }+ into.count += other.count;+ into.sum += other.sum;+ if other.min < into.min {+ into.min = other.min;+ }+ if other.max > into.max {+ into.max = other.max;+ }+}++/// Keep the top-`k` (by sort value + corpus-rank tiebreak) entries.+fn push_top(buf: &mut Vec<(f64, u64, DocRef)>, k: usize, desc: bool, v: f64, rank: u64, r: DocRef) {+ buf.push((v, rank, r));+ if buf.len() > k.saturating_mul(2).max(16) {+ sort_top(buf, desc);+ buf.truncate(k);+ }+}++fn sort_top(buf: &mut Vec<(f64, u64, DocRef)>, desc: bool) {+ buf.sort_by(|a, b| {+ let c = if desc {+ b.0.partial_cmp(&a.0)+ } else {+ a.0.partial_cmp(&b.0)+ }+ .unwrap_or(std::cmp::Ordering::Equal);+ c.then_with(|| a.1.cmp(&b.1))+ });+}++/// Parse a terms `order` param into (path, asc) entries — mirror of the+/// closure in `run_terms`.+fn parse_orders(params: &Value) -> Vec<(String, bool)> {+ let order = match params.get("order") {+ Some(v) => v,+ None => return Vec::new(),+ };+ let mut out: Vec<(String, bool)> = Vec::new();+ match order {+ Value::Object(o) => {+ for (k, v) in o {+ let asc = v.as_str().map(|s| s == "asc").unwrap_or(false);+ out.push((k.clone(), asc));+ }+ }+ Value::Array(arr) => {+ for item in arr {+ if let Some(o) = item.as_object() {+ for (k, v) in o {+ let asc = v.as_str().map(|s| s == "asc").unwrap_or(false);+ out.push((k.clone(), asc));+ }+ }+ }+ }+ _ => {}+ }+ out+}++/// `cmp_terms_by_orders` for (key, count) with no sub-agg entries.+fn cmp_by_orders(a: &(String, u64), b: &(String, u64), orders: &[(String, bool)]) -> std::cmp::Ordering {+ use std::cmp::Ordering;+ if orders.is_empty() {+ return b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0));+ }+ for (path, asc) in orders {+ let ord = match path.as_str() {+ "_count" => a.1.cmp(&b.1),+ "_key" => a.0.cmp(&b.0),+ _ => Ordering::Equal,+ };+ let ord = if *asc { ord } else { ord.reverse() };+ if ord != Ordering::Equal {+ return ord;+ }+ }+ a.0.cmp(&b.0)+}++/// Composite key comparison for terms-only sources (mirror of the brute+/// sort: numeric when both sides parse as f64, else lexicographic; asc).+fn composite_cmp(a: &[String], b: &[String]) -> std::cmp::Ordering {+ use std::cmp::Ordering;+ for i in 0..a.len().min(b.len()) {+ let (av, bv) = (&a[i], &b[i]);+ let cmp = if let (Ok(an), Ok(bn)) = (av.parse::<f64>(), bv.parse::<f64>()) {+ an.partial_cmp(&bn).unwrap_or(Ordering::Equal)+ } else {+ av.cmp(bv)+ };+ if cmp != Ordering::Equal {+ return cmp;+ }+ }+ a.len().cmp(&b.len())+}++/// True when a sub-agg tree references background-corpus semantics the+/// sampler fast path can't provide (it hands the sample as `all_docs`).+fn sub_tree_needs_background(sub: &Value) -> bool {+ match sub {+ Value::Object(o) => o.iter().any(|(k, v)| {+ matches!(k.as_str(), "significant_terms" | "significant_text" | "global")+ || (k == "min_doc_count" && v.as_u64() == Some(0))+ || sub_tree_needs_background(v)+ }),+ Value::Array(a) => a.iter().any(sub_tree_needs_background),+ _ => false,+ }+}++// ── predicate compilation (filter / filters / adjacency_matrix) ─────────────++enum Pred {+ MatchAll,+ TermKw { field: String, value: String },+ TermsKw { field: String, values: Vec<String> },+ RangeNum { field: String, lo: f64, lo_incl: bool, hi: f64, hi_incl: bool },+}++/// Compile the (single-clause) filter queries `doc_matches_filter` supports+/// into a columnar predicate. Anything not exactly mirrored → `None`.+fn compile_pred(filter: &Value) -> Option<Pred> {+ let obj = filter.as_object()?;+ if obj.len() != 1 {+ return None;+ }+ let (qtype, body) = obj.iter().next()?;+ match qtype.as_str() {+ "match_all" => Some(Pred::MatchAll),+ "term" => {+ let fm = body.as_object()?;+ if fm.len() != 1 {+ return None;+ }+ let (field, expected) = fm.iter().next()?;+ let value = match expected {+ Value::String(s) => s.clone(),+ Value::Object(o) => match o.get("value") {+ Some(Value::String(s)) => s.clone(),+ _ => return None,+ },+ _ => return None, // numeric/bool string-form subtleties → bail+ };+ Some(Pred::TermKw { field: field.clone(), value })+ }+ "terms" => {+ let fm = body.as_object()?;+ if fm.len() != 1 {+ return None;+ }+ let (field, expected) = fm.iter().next()?;+ let arr = expected.as_array()?;+ let mut values = Vec::with_capacity(arr.len());+ for v in arr {+ match v {+ Value::String(s) => values.push(s.clone()),+ _ => return None,+ }+ }+ Some(Pred::TermsKw { field: field.clone(), values })+ }+ "range" => {+ let fm = body.as_object()?;+ if fm.len() != 1 {+ return None;+ }+ let (field, bounds) = fm.iter().next()?;+ let bo = bounds.as_object()?;+ if !bo.keys().all(|k| matches!(k.as_str(), "gte" | "gt" | "lte" | "lt")) {+ return None;+ }+ let get_num = |k: &str| -> Option<Option<f64>> {+ match bo.get(k) {+ None => Some(None),+ Some(Value::Number(n)) => Some(n.as_f64()),+ Some(_) => None,+ }+ };+ let gte = get_num("gte")?;+ let gt = get_num("gt")?;+ let lte = get_num("lte")?;+ let lt = get_num("lt")?;+ let (lo, lo_incl) = match (gte, gt) {+ (Some(v), _) => (v, true),+ (None, Some(v)) => (v, false),+ (None, None) => (f64::NEG_INFINITY, true),+ };+ let (hi, hi_incl) = match (lte, lt) {+ (Some(v), _) => (v, true),+ (None, Some(v)) => (v, false),+ (None, None) => (f64::INFINITY, true),+ };+ Some(Pred::RangeNum { field: field.clone(), lo, lo_incl, hi, hi_incl })+ }+ _ => None,+ }+}++enum SegPred<'a> {+ Never,+ Always,+ KwEq(&'a KeywordColumn, u32),+ KwIn(&'a KeywordColumn, Vec<u32>),+ Num(&'a NumericColumn, f64, bool, f64, bool),+}++fn resolve_pred<'a>(+ cols: &'a std::collections::BTreeMap<String, Column>,+ pred: &Pred,+) -> Option<SegPred<'a>> {+ Some(match pred {+ Pred::MatchAll => SegPred::Always,+ Pred::TermKw { field, value } => match cols.get(field) {+ Some(Column::Keyword(k)) => match k.ord_for_term(value) {+ Some(ord) => SegPred::KwEq(k, ord),+ None => SegPred::Never,+ },+ Some(Column::Numeric(_)) => return None,+ None => SegPred::Never,+ },+ Pred::TermsKw { field, values } => match cols.get(field) {+ Some(Column::Keyword(k)) => {+ let ords: Vec<u32> = values.iter().filter_map(|v| k.ord_for_term(v)).collect();+ if ords.is_empty() {+ SegPred::Never+ } else {+ SegPred::KwIn(k, ords)+ }+ }+ Some(Column::Numeric(_)) => return None,+ None => SegPred::Never,+ },+ Pred::RangeNum { field, lo, lo_incl, hi, hi_incl } => match cols.get(field) {+ Some(Column::Numeric(n)) => SegPred::Num(n, *lo, *lo_incl, *hi, *hi_incl),+ Some(Column::Keyword(_)) => return None,+ None => SegPred::Never,+ },+ })+}++#[inline]+fn seg_pred_matches(sp: &SegPred<'_>, row: u32) -> bool {+ match sp {+ SegPred::Never => false,+ SegPred::Always => true,+ SegPred::KwEq(k, ord) => k.ord_for(row) == Some(*ord),+ SegPred::KwIn(k, ords) => match k.ord_for(row) {+ Some(o) => ords.contains(&o),+ None => false,+ },+ SegPred::Num(n, lo, lo_incl, hi, hi_incl) => {+ if n.null_bitmap.contains(row) {+ return false;+ }+ let v = f64::from_bits(n.data[row as usize] as u64);+ let lo_ok = if *lo_incl { v >= *lo } else { v > *lo };+ let hi_ok = if *hi_incl { v <= *hi } else { v < *hi };+ lo_ok && hi_ok+ }+ }+}++fn seg_pred_count(sp: &SegPred<'_>, docs: u32) -> u64 {+ match sp {+ SegPred::Never => 0,+ SegPred::Always => docs as u64,+ SegPred::KwEq(k, ord) => k.per_ord_count.get(*ord as usize).copied().unwrap_or(0) as u64,+ SegPred::KwIn(k, ords) => ords+ .iter()+ .map(|o| k.per_ord_count.get(*o as usize).copied().unwrap_or(0) as u64)+ .sum(),+ SegPred::Num(n, lo, lo_incl, hi, hi_incl) => n.range_count(*lo, *hi, *lo_incl, *hi_incl) as u64,+ }+}++// ── variable_width_histogram weighted clustering ─────────────────────────────++pub(super) struct VwhBucket {+ pub min: f64,+ pub max: f64,+ pub sum: f64,+ pub count: u64,+}++/// Weighted replay of the brute adaptive-merge clustering+/// (`run_variable_width_histogram`): the brute algorithm starts from one+/// bucket per value *instance* and repeatedly merges the adjacent pair with+/// the strictly-smallest centroid gap (earliest pair wins ties). All+/// zero-gap pairs (duplicate values) merge before any positive gap, and+/// they merge left-to-right, so the instance-level process is exactly+/// reproducible from the sorted distinct (value, weight) sequence.+/// K-way merge of value-ascending `(value, weight)` runs into one distinct+/// ascending list, summing weights of equal values across runs.+fn merge_weighted_runs(mut runs: Vec<Vec<(f64, u64)>>) -> Vec<(f64, u64)> {+ match runs.len() {+ 0 => return Vec::new(),+ 1 => return runs.pop().unwrap(),+ _ => {}+ }+ use std::cmp::Reverse;+ use std::collections::BinaryHeap;+ // Heap entries keyed on the value's total_cmp bit pattern (all runs come+ // from finite doc values, so the sign-flip trick keeps ordering exact).+ fn key(v: f64) -> u64 {+ let b = v.to_bits();+ if b >> 63 == 1 { !b } else { b | (1 << 63) }+ }+ let total: usize = runs.iter().map(Vec::len).sum();+ let mut out: Vec<(f64, u64)> = Vec::with_capacity(total);+ let mut heap: BinaryHeap<Reverse<(u64, usize)>> = BinaryHeap::new();+ let mut pos: Vec<usize> = vec![0; runs.len()];+ for (ri, run) in runs.iter().enumerate() {+ if let Some(&(v, _)) = run.first() {+ heap.push(Reverse((key(v), ri)));+ }+ }+ while let Some(Reverse((_, ri))) = heap.pop() {+ let (v, w) = runs[ri][pos[ri]];+ match out.last_mut() {+ Some((lv, lw)) if *lv == v => *lw += w,+ _ => out.push((v, w)),+ }+ pos[ri] += 1;+ if let Some(&(nv, _)) = runs[ri].get(pos[ri]) {+ heap.push(Reverse((key(nv), ri)));+ }+ }+ out+}++/// Coarsen an ascending distinct `(value, weight)` list into at most `cap`+/// equal-weight groups, each represented by its weighted mean. Order and+/// total weight are preserved; only used above the exact-clustering budget+/// where the reference (brute) implementation cannot run anyway.+fn coarsen_weighted(vals: &[(f64, u64)], cap: usize) -> Vec<(f64, u64)> {+ let total_w: u64 = vals.iter().map(|&(_, w)| w).sum();+ let per_group: u64 = total_w.div_ceil(cap as u64).max(1);+ let mut out: Vec<(f64, u64)> = Vec::with_capacity(cap + 1);+ let mut g_sum = 0.0_f64;+ let mut g_w = 0_u64;+ for &(v, w) in vals {+ g_sum += v * w as f64;+ g_w += w;+ if g_w >= per_group {+ out.push((g_sum / g_w as f64, g_w));+ g_sum = 0.0;+ g_w = 0;+ }+ }+ if g_w > 0 {+ out.push((g_sum / g_w as f64, g_w));+ }+ out+}++fn vwh_cluster(vals: &[(f64, u64)], num_buckets: usize) -> Vec<VwhBucket> {+ let n_total: u64 = vals.iter().map(|(_, w)| w).sum();+ let effective: u64 = (num_buckets as u64).min(n_total).max(1);+ let mut merges_needed: u64 = n_total - effective;+ let zero_merges: u64 = n_total - vals.len() as u64;++ if merges_needed <= zero_merges {+ // Phase A only: duplicates collapse left-to-right until the target+ // bucket count is reached.+ let mut out: Vec<VwhBucket> = Vec::new();+ for &(v, w) in vals {+ if merges_needed >= w - 1 {+ merges_needed -= w - 1;+ out.push(VwhBucket { min: v, max: v, sum: v * w as f64, count: w });+ } else {+ // Partially collapsed run: one merged bucket of+ // (merges_needed + 1) instances, then singletons.+ let m = merges_needed;+ merges_needed = 0;+ out.push(VwhBucket { min: v, max: v, sum: v * (m + 1) as f64, count: m + 1 });+ for _ in 0..(w - 1 - m) {+ out.push(VwhBucket { min: v, max: v, sum: v, count: 1 });+ }+ }+ }+ return out;+ }++ // Phase B: all duplicates collapsed; merge weighted adjacent buckets by+ // centroid distance (smallest gap, earliest pair) until `effective`+ // buckets remain. Heap + doubly-linked list = O(d log d).+ let mut remaining = merges_needed - zero_merges;+ let d = vals.len();+ let mut sum: Vec<f64> = vals.iter().map(|&(v, w)| v * w as f64).collect();+ let mut cnt: Vec<u64> = vals.iter().map(|&(_, w)| w).collect();+ let mut mn: Vec<f64> = vals.iter().map(|&(v, _)| v).collect();+ let mut mx: Vec<f64> = vals.iter().map(|&(v, _)| v).collect();+ let mut next: Vec<usize> = (0..d).map(|i| i + 1).collect(); // d = sentinel end+ let mut prev: Vec<usize> = (0..d).map(|i| i.wrapping_sub(1)).collect();+ let mut gen: Vec<u64> = vec![0; d];+ let mut alive: Vec<bool> = vec![true; d];++ use std::cmp::Reverse;+ use std::collections::BinaryHeap;+ #[derive(PartialEq, Eq, PartialOrd, Ord)]+ struct Entry(u64 /*gap bits (total_cmp key)*/, usize /*left idx*/, u64 /*gen sum*/);+ let gap_key = |g: f64| -> u64 {+ // total_cmp-compatible ordering for non-negative floats.+ g.to_bits()+ };+ let mut heap: BinaryHeap<Reverse<Entry>> = BinaryHeap::new();+ let centroid = |i: usize, sum: &[f64], cnt: &[u64]| sum[i] / cnt[i] as f64;+ for i in 0..d.saturating_sub(1) {+ let g = (centroid(i + 1, &sum, &cnt) - centroid(i, &sum, &cnt)).abs();+ heap.push(Reverse(Entry(gap_key(g), i, 0)));+ }+ while remaining > 0 {+ let Some(Reverse(Entry(_, left, gsum))) = heap.pop() else { break };+ if !alive[left] {+ continue;+ }+ let right = next[left];+ if right >= d || !alive[right] {+ continue;+ }+ if gen[left] + gen[right] != gsum {+ continue; // stale entry+ }+ // Merge right into left.+ sum[left] += sum[right];+ cnt[left] += cnt[right];+ if mn[right] < mn[left] {+ mn[left] = mn[right];+ }+ if mx[right] > mx[left] {+ mx[left] = mx[right];+ }+ alive[right] = false;+ let rr = next[right];+ next[left] = rr;+ if rr < d {+ prev[rr] = left;+ }+ gen[left] += 1;+ remaining -= 1;+ // Refresh neighbour gaps.+ let pl = prev[left];+ if pl != usize::MAX && pl < d && alive[pl] {+ let g = (centroid(left, &sum, &cnt) - centroid(pl, &sum, &cnt)).abs();+ heap.push(Reverse(Entry(gap_key(g), pl, gen[pl] + gen[left])));+ }+ if rr < d && alive[rr] {+ let g = (centroid(rr, &sum, &cnt) - centroid(left, &sum, &cnt)).abs();+ heap.push(Reverse(Entry(gap_key(g), left, gen[left] + gen[rr])));+ }+ }+ let mut out = Vec::new();+ let mut i = 0usize;+ // Find the first alive bucket.+ while i < d && !alive[i] {+ i += 1;+ }+ while i < d {+ out.push(VwhBucket { min: mn[i], max: mx[i], sum: sum[i], count: cnt[i] });+ i = next[i];+ while i < d && !alive[i] {+ i += 1;+ }+ }+ out+}diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 76c351c4a..ccee6993c 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -26,6 +26,11 @@ use xerj_vector::hnsw::{HnswIndex, HnswParams};use xerj_vector::distance::DistanceMetric;use crate::aggs::{run_aggs_with_all, run_agg_fast, run_agg_fast_filtered, FastAggResult};++// Doc-values (columnar) fast path for size:0 + match_all + aggs — child+// module so it can reach Index's private fields/methods via `super::`.+#[path = "fast_aggs.rs"]+mod fast_aggs;use crate::memtable::FtsMemtable;use crate::{EngineError, Result};@@ -373,6 +378,11 @@ pub struct Index {/// on every request.regexp_expand_cache: Arc<dashmap::DashMap<(String, String, String), Arc<RegexpExpansion>>>,+ /// Fast-agg path: per-(segment, field) parsed date ordinals+ /// (ord → epoch-ms; i64::MIN = unparseable). Same immutable-segment+ /// lifecycle as `dv_cache`; evicted alongside it on merge.+ fast_date_cache: Arc<dashmap::DashMap<(String, String), Arc<Vec<i64>>>>,+/// M3 framework — response cache for identical queries. Keyed on/// `(query_body_hash, dataset_version)` and holds the pre-computed/// `SearchResult` ready to serialize. Cache hit → ~10 µs total@@ -514,6 +524,7 @@ impl Index {stored_slices_cache: Arc::new(dashmap::DashMap::new()),stored_slices_cache_bytes: Arc::new(AtomicU64::new(0)),regexp_expand_cache: Arc::new(dashmap::DashMap::new()),+ fast_date_cache: Arc::new(dashmap::DashMap::new()),query_cache: Arc::new(dashmap::DashMap::new()),dataset_version: Arc::new(AtomicU64::new(0)),flush_signal: Arc::new(SyncFlushCoord::new()),@@ -668,6 +679,7 @@ impl Index {stored_slices_cache: Arc::new(dashmap::DashMap::new()),stored_slices_cache_bytes: Arc::new(AtomicU64::new(0)),regexp_expand_cache: Arc::new(dashmap::DashMap::new()),+ fast_date_cache: Arc::new(dashmap::DashMap::new()),query_cache: Arc::new(dashmap::DashMap::new()),dataset_version: Arc::new(AtomicU64::new(0)),flush_signal: Arc::new(SyncFlushCoord::new()),@@ -2500,6 +2512,7 @@ impl Index {self.stored_slices_cache_bytes.fetch_sub(slices.retained_bytes(), Ordering::Relaxed);}+ self.fast_date_cache.retain(|(seg, _), _| seg != id.as_str());}}@@ -4307,7 +4320,7 @@ impl Index {// result is stashed in `precomputed_aggs` and consumed at the// agg-section below.let mut precomputed_aggs: Option<Value> = None;- if is_match_all && size == 0 && request.aggs.is_some() {+ if is_match_all && size == 0 && request.aggs.is_some() && request.min_score.is_none() {if let Some(aggs_def) = &request.aggs {let r_opt = self.try_aggs_fast_with_segments_cached(aggs_def, &snap, &segments_dir)@@ -7163,15 +7176,29 @@ impl Index {snap: &xerj_storage::index_store::IndexSnapshot,segments_dir: &std::path::Path,) -> Option<Value> {- // M5.1 — disabled under sharded memtable for the same reason- // `try_aggs_fast` is disabled: the memtable doc-values live- // inside per-shard FtsMemtable instances and can't be handed- // to `run_numeric_agg_with_segments_refs` as a single- // `&DocValues`. Falls back to `run_aggs_with_all`- // stored-doc path (correct, slightly slower). See V5 §2.4- // + §6 for the cross-shard column aggregator follow-up.- let _ = (aggs_def, snap, segments_dir);- None+ // 2026-07 agg-hang fix: the columnar executor in `fast_aggs.rs`+ // serves `size:0 + match_all + aggs` straight from segment `.dv`+ // sidecars + the live memtable. It bails (None) on any shape it+ // can't reproduce byte-identically, on small indices, and when+ // deletes/updates are present — the caller then falls back to the+ // brute `run_aggs_with_all` stored-doc path.+ //+ // Boolean-mapped fields are stored as 0/1 in numeric `.dv` columns,+ // indistinguishable from real integers at the column level. The+ // schema is the only source of truth for "render 0/1 as+ // false/true", so snapshot the boolean field names here (async+ // lock) and hand them to the sync executor.+ let bool_fields: std::collections::HashSet<String> = {+ let guard = self.schema.read().await;+ guard+ .schema+ .fields+ .iter()+ .filter(|f| matches!(f.field_type, xerj_common::FieldType::Boolean))+ .map(|f| f.name.clone())+ .collect()+ };+ self.try_fast_aggs(aggs_def, snap, segments_dir, &bool_fields)}}