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): scripted_metric sum shape → columnar .dv fast path (+730ms → 0ms)
xerj-org008040a6d518
diff --git a/demo/playbooks/FULL_MATRIX_SCORECARD_2026-07-10_CACHEHARDENED.md b/demo/playbooks/FULL_MATRIX_SCORECARD_2026-07-10_CACHEHARDENED.mdnew file mode 100644index 000000000..561f85773--- /dev/null+++ b/demo/playbooks/FULL_MATRIX_SCORECARD_2026-07-10_CACHEHARDENED.md@@ -0,0 +1,82 @@+# Full-matrix scorecard — cache-hardened — 2026-07-10++Engine: `c45dfd4` (MLT bool-rewrite). ES: 8.13.4 on :9201. Corpus: `perf`,+100k docs, explicit ids 0..99999, single segment, memtable drained. Closed-loop+single-client keep-alive, warm 8 + p50 over 40 iters. TIE band ±0.30ms.++## Anti-trick proofs (the whole point of this run)++**Cache off — proven by A/B, not asserted.** Two XERJ instances, seeded+identically, hit with `scripted_metric` (~710ms uncached):++| instance | flag | call#1 | calls#2-6 (took) | meaning |+|---|---|---|---|---|+| xerj-B :9202 | cache ON (default) | 719ms | **0ms ×5** | query_cache is REAL — would trick us |+| xerj-A :9200 | `XERJ_DISABLE_QUERY_CACHE=1` | 710ms | **705–775ms ×5, took>0** | flag bypasses it |++Flag confirmed in the kernel process env (`/proc/<pid>/environ`). ES ran every+`_search` with `request_cache=false`. The matrix engine is xerj-A (cache off).++**Static data off — proven by cross-check.** Every cell's result compared to ES.+69/76 identical (incl. `scripted_metric` total = 83,826,063 on both). The 7+"DIFF" cells all have **identical hit counts** — only `max_score` differs+(scoring semantics, below). Canned answers can't equal ES across 69 diverse+queries.++**took=0 caveat (honest):** 47 cells show XERJ max `took=0`. That is NOT cache+(proven off) — it is genuine sub-1ms columnar execution rounded by integer-ms+`took`. All 47 MATCH ES's computed result.++## Totals: **WIN 53 · LOSS 13 · TIE 10 · UNSUP 3** (of 79; 76 runnable)+## _(pre-campaign: WIN 52 · LOSS 14; Batch 2 flipped scripted_metric LOSS→WIN)_++UNSUP = ES 400s on this corpus (`match_phrase_prefix`, `combined_fields`,+`_count?request_cache=false`), not XERJ losses.++## Campaign progress++- **Batch 1 (`4c69c05`)** — `prefix`/`wildcard` keyword → `constant_score`:+ `max_score` DIFF 1.50 → 1.0 = ES (correctness fix; latency unchanged).+- **Batch 2 (this commit)** — `agg: scripted_metric` **+730ms → 0ms**: the+ canonical "sum one numeric doc field" script shape is now served off the+ numeric `.dv` column instead of the per-doc Painless interpreter over a+ materialised JSON corpus. Live A/B on the `perf` 100k corpus, cache off:+ fast `{"value":83826063}` @ 0ms vs brute (`XERJ_DISABLE_FAST_AGGS=1`)+ `{"value":83826063}` @ 969ms — **byte-identical**, biggest loss on the board+ eliminated. ES-YAML gate held 1360/0/3.++## The remaining losses (XERJ slower by >0.30ms)++| cell | Δms | correctness |+|---|---|---|+| ~~agg: scripted_metric~~ | ~~+730.01~~ | ✅ FIXED → 0ms (columnar sum fast path) |+| q: wildcard(model) | +5.38 | DIFF max_score 1.50 vs 1.0 |+| q: prefix(model) | +5.04 | DIFF max_score 1.50 vs 1.0 |+| q: fuzzy(model) | +1.83 | DIFF max_score 1.282 vs 1.202 |+| q: multi_match | +1.41 | DIFF last-digit float only |+| feat: deep from+size (from 500) | +1.38 | DIFF max_score null vs 1.0 |+| q: range(@timestamp) | +1.30 | MATCH |+| q: term(cache_hit) | +1.30 | MATCH |+| q: dis_max | +0.91 | MATCH |+| q: bool must+filter+should+must_not | +0.91 | MATCH |+| q: terms(model) | +0.82 | MATCH |+| q: match_bool_prefix | +0.78 | DIFF max_score 2.52 vs 1.0 |+| agg: composite | +0.66 | MATCH |+| q: exists(cost_usd) | +0.65 | MATCH |++## Correctness DIFFs (7) — all scoring semantics, hit counts all match++- `match_all` / deep-from: XERJ max_score `null`, ES `1.0`.+- `prefix` / `wildcard`: XERJ BM25-scores (1.50); ES rewrites to constant_score `1.0`.+- `match_bool_prefix`: XERJ 2.52 vs ES 1.0.+- `fuzzy`: XERJ 1.282 vs ES 1.202 (fuzzy rewrite boost).+- `multi_match`: 1.2821425 vs 1.2821424 (f32 last digit — effectively equal).++## Fix priority++1. **prefix/wildcard/regexp → constant_score 1.0** — fixes 2 DIFFs + the two+ biggest non-script perf losses (constant score short-circuits BM25). ES-compat.+2. **match_all max_score = 1.0** (not null) — trivial, 2 cells.+3. **match_bool_prefix scoring** — DIFF.+4. **scripted_metric +730ms** — biggest perf, hardest (needs compiled/vectorized path).+5. Residual 0.6–1.3ms term/range/bool losses — fixed-overhead; chase last.diff --git a/engine/crates/xerj-engine/src/aggs.rs b/engine/crates/xerj-engine/src/aggs.rsindex 8485dfe2e..f04115259 100644--- a/engine/crates/xerj-engine/src/aggs.rs+++ b/engine/crates/xerj-engine/src/aggs.rs@@ -10204,6 +10204,122 @@ fn run_scripted_metric(params: &Value, docs: &[Value]) -> Value {json!({"value": reduce_val})}+/// Recognise the canonical "sum a single numeric doc field" `scripted_metric`+/// shape and, when it matches, return the field name so the columnar fast path+/// (`fast_aggs::FastCtx::exec_scripted_metric`) can serve it off doc-values+/// instead of interpreting the script per doc over a materialised JSON corpus.+///+/// Exact shape (whitespace-insensitive — matched on the parsed AST):+/// ```painless+/// init_script: state.S = 0+/// map_script: state.S += doc.FIELD.value+/// combine_script: return state.S+/// reduce_script: <type> T = 0; for (V in states) { T += V } return T+/// ```+/// Any deviation returns `None` and the caller keeps the exact interpreter.+/// The reduce is required to be a plain sum-over-states so that — under our+/// single-shard model where `states == [combine_val]` — the reduced value is+/// exactly the per-shard sum; the fast path may then emit that sum directly.+pub(crate) fn scripted_metric_sum_field(params: &Value) -> Option<String> {+ let src_of = |key: &str| -> Option<String> {+ params.get(key).and_then(|v| {+ v.as_str()+ .map(String::from)+ .or_else(|| v.get("source").and_then(Value::as_str).map(String::from))+ })+ };+ let init = parse_script(&src_of("init_script")?).ok()?;+ let map = parse_script(&src_of("map_script")?).ok()?;+ let combine = parse_script(&src_of("combine_script")?).ok()?;++ // `state.<name>` accessor: Member(Ident("state"), name).+ fn state_field(e: &PlExpr) -> Option<&str> {+ match e {+ PlExpr::Member(base, name) => match &**base {+ PlExpr::Ident(root) if root == "state" => Some(name.as_str()),+ _ => None,+ },+ _ => None,+ }+ }+ // `doc.<field>.value` accessor: Member(Member(Ident("doc"), field), "value").+ fn doc_value_field(e: &PlExpr) -> Option<&str> {+ match e {+ PlExpr::Member(base, val) if val == "value" => match &**base {+ PlExpr::Member(doc, field) => match &**doc {+ PlExpr::Ident(root) if root == "doc" => Some(field.as_str()),+ _ => None,+ },+ _ => None,+ },+ _ => None,+ }+ }++ // init: `state.<acc> = 0`+ let acc = match init.as_slice() {+ [PlStmt::Assign(lhs, PlExpr::Num(n))] if *n == 0.0 => state_field(lhs)?,+ _ => return None,+ };+ // map: `state.<acc> += doc.<field>.value`+ let field = match map.as_slice() {+ [PlStmt::AugAssign(lhs, op, rhs)] if *op == "+=" && state_field(lhs) == Some(acc) => {+ doc_value_field(rhs)?+ }+ _ => return None,+ };+ // combine: `return state.<acc>` — makes the per-shard combine value exactly+ // the accumulated sum (`state.<acc>`). Required: a combine that fails to+ // parse or is absent would make the interpreter return the whole `state`+ // object (`{acc: sum}`), not the scalar sum.+ match combine.as_slice() {+ [PlStmt::Return(e)] if state_field(e) == Some(acc) => {}+ _ => return None,+ }++ // reduce: under our single-shard model `states == [combine_val]`, so the+ // reduced value must equal `combine_val` (the sum). Two accepted cases,+ // both yielding exactly the sum — mirroring `run_scripted_metric`:+ // 1. reduce is absent OR fails to parse → the interpreter's `reduce_ast`+ // is `None` and it returns `combine_val` unchanged. (The canonical+ // `for (s in states) t += s` body is BRACELESS, which the Painless+ // subset parser rejects — this is the common real-world shape.)+ // 2. reduce parses to `<type> t = 0; for (v in states) { t += v }+ // return t` — sum-over-states of the single element == that element.+ // Anything that parses to some OTHER computation is rejected (its result+ // need not equal the sum).+ if let Some(reduce_src) = src_of("reduce_script") {+ if let Ok(reduce) = parse_script(&reduce_src) {+ // Canonical sum-over-states, else bail.+ let reduce_acc = match reduce.first() {+ Some(PlStmt::Decl(name, PlExpr::Num(n))) if *n == 0.0 => name.as_str(),+ _ => return None,+ };+ if reduce.len() != 3 {+ return None;+ }+ match &reduce[1] {+ PlStmt::ForIn(v, PlExpr::Ident(container), body) if container == "states" => {+ match body.as_slice() {+ [PlStmt::AugAssign(PlExpr::Ident(a), op, PlExpr::Ident(s))]+ if *op == "+=" && a.as_str() == reduce_acc && s == v => {}+ _ => return None,+ }+ }+ _ => return None,+ }+ match &reduce[2] {+ PlStmt::Return(PlExpr::Ident(r)) if r == reduce_acc => {}+ _ => return None,+ }+ }+ // parse error → interpreter falls back to combine_val == sum → accept.+ }+ // absent reduce → interpreter uses combine_val == sum → accept.++ Some(field.to_string())+}+#[derive(Debug, Clone)]enum PlTok {Ident(String),diff --git a/engine/crates/xerj-engine/src/fast_aggs.rs b/engine/crates/xerj-engine/src/fast_aggs.rsindex afa550956..4a2e2d600 100644--- a/engine/crates/xerj-engine/src/fast_aggs.rs+++ b/engine/crates/xerj-engine/src/fast_aggs.rs@@ -1095,10 +1095,93 @@ impl<'a> FastCtx<'a> {"variable_width_histogram" => self.exec_vwh(params, sub),"date_histogram" => self.exec_date_histogram(params, sub),"histogram" => self.exec_histogram(params, sub),+ "scripted_metric" => {+ if sub.is_some() {+ return None;+ }+ self.exec_scripted_metric(params)+ }_ => None,}}+ // ── scripted_metric (reducible sum shape) ────────────────────────────+ //+ // The interpreter path (`aggs::run_scripted_metric`) runs only inside the+ // brute `run_aggs_with_all`, which first decompresses + JSON-parses EVERY+ // live doc, then tree-walks the map script per doc (≈730 ms on a 100 k+ // corpus). When the four scripts form the canonical "sum one numeric doc+ // field" shape (`aggs::scripted_metric_sum_field`), the whole aggregation+ // is exactly `Σ doc.FIELD.value` over the matched docs — served here off the+ // numeric `.dv` column with no materialisation.+ //+ // Correctness contract (byte-identical to the interpreter):+ // * Painless long arithmetic renders an INTEGER as long as every summed+ // value is integral (`num_binop`'s `both_int` rule); the moment a+ // fractional value — or a missing field (`doc.F.value` → Null, which+ // flips the accumulator to a float) — participates, the result becomes a+ // float. We therefore serve ONLY the wholly-integral, no-missing case+ // and render `{"value": <i64>}`; anything else bails (`None`) to the exact+ // interpreter. Integer sums below 2^53 are order-independent in f64, so+ // the columnar summation order is irrelevant to the emitted value.+ // * A top-level query filter never reaches here (scripted_metric is absent+ // from `exec_agg`'s filtered whitelist, so `top_filter.is_some()` already+ // returned `None`).+ fn exec_scripted_metric(&self, params: &Value) -> Option<Value> {+ let field = crate::aggs::scripted_metric_sum_field(params)?;+ if self.seg_field_kind(&field).ok()? != Some(ColKind::Numeric) {+ return None;+ }++ // ~9.007e15 == 2^53: the largest magnitude whose integer neighbours are+ // all exactly representable in f64 (mirrors `num_binop`'s int-shape cap).+ const INT_SAFE_ABS: f64 = 9.007e15;+ let mut sum = 0f64;++ // Segments: every doc in the segment must contribute a live, integral+ // value (no missing → no interpreter Null → stays integer).+ for s in &self.segs {+ if s.docs == 0 {+ continue;+ }+ match s.cols.get(&field) {+ Some(Column::Numeric(n)) => {+ if !n.null_bitmap.is_empty() || n.live_count != s.docs as u64 {+ return None; // some doc lacks the field+ }+ for bits in &n.data {+ let v = f64::from_bits(*bits as u64);+ if v.fract() != 0.0 {+ return None; // fractional → float result+ }+ sum += v;+ }+ }+ _ => return None, // field absent in this segment+ }+ }++ // Memtable docs (usually empty on the drained-corpus fast path): each+ // must carry the field as an integral number, else bail.+ for doc in self.mem().iter() {+ match doc.get(&field) {+ Some(Value::Number(num)) => {+ let v = num.as_f64()?;+ if v.fract() != 0.0 {+ return None;+ }+ sum += v;+ }+ _ => return None,+ }+ }++ if !sum.is_finite() || sum.abs() >= INT_SAFE_ABS {+ return None; // interpreter would flip to float shape here+ }+ Some(json!({ "value": sum as i64 }))+ }+// ── top-level metric ─────────────────────────────────────────────────fn exec_metric_top(&self, kind: MetricKind, params: &Value) -> Option<Value> {