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
fix(aggs): terms order resolves percentile keys and rejects unknown paths (#1282, #1283)
Vincenzo Lombardo79ae57791903
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 767a40351..309291789 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -6158,6 +6158,72 @@ fn find_search_body_script_limit_violation(.find_map(find_script_limit_violation)}+/// Request-time check of every `terms` aggregation's `order` paths (#1283).+///+/// ES rejects an order key that names an aggregation the request does not+/// define with a 400 (`Invalid aggregation order path [nope]. Cannot find+/// aggregation named [nope]`, verified against ES 8.13.4). The executor has no+/// error channel for it: an unresolvable path compared every bucket as equal+/// and fell through to the key tiebreaker, so a typo produced a plausible but+/// wrongly ordered HTTP 200. Checked on the request, before execution, so the+/// answer is the same whichever executor path (fast or general) the+/// aggregation later takes.+///+/// A path is `agg1>agg2>…>aggN`, where the last element may carry a value key+/// (`p.95`, `p[95.0]`). Each element's name must be a sub-aggregation of the+/// level before it; `_count` and `_key` are the built-in keys. Value keys are+/// not validated here — that stays the executor's (lenient) business.+fn find_invalid_agg_order_path(aggs: Option<&Value>) -> Option<String> {+ fn sub_aggs(def: &Value) -> Option<&Value> {+ def.get("aggs").or_else(|| def.get("aggregations"))+ }+ fn order_keys(order: &Value) -> Vec<&str> {+ match order {+ Value::Object(o) => o.keys().map(String::as_str).collect(),+ Value::Array(arr) => arr+ .iter()+ .filter_map(Value::as_object)+ .flat_map(|o| o.keys().map(String::as_str))+ .collect(),+ _ => Vec::new(),+ }+ }+ fn check_path(path: &str, mut level: Option<&Value>) -> Option<String> {+ if path == "_count" || path == "_key" {+ return None;+ }+ for element in path.split('>') {+ let name = element+ .find(['.', '['])+ .map_or(element, |at| &element[..at]);+ match level.and_then(|defs| defs.get(name)) {+ Some(def) => level = sub_aggs(def),+ None => {+ return Some(format!(+ "Invalid aggregation order path [{path}]. Cannot find aggregation named [{name}]"+ ))+ }+ }+ }+ None+ }+ let defs = aggs?.as_object()?;+ for def in defs.values() {+ let subs = sub_aggs(def);+ if let Some(order) = def.get("terms").and_then(|t| t.get("order")) {+ for path in order_keys(order) {+ if let Some(reason) = check_path(path, subs) {+ return Some(reason);+ }+ }+ }+ if let Some(reason) = find_invalid_agg_order_path(subs) {+ return Some(reason);+ }+ }+ None+}+/// Parse an ES time-units string to milliseconds: `"500ms"`, `"30s"`,/// `"2m"`, `"1h"`, `"1d"`, `"5micros"`, `"100nanos"`, bare number =/// millis. Sub-millisecond values round up to 1 ms so `timeout=100nanos`@@ -6300,6 +6366,9 @@ fn build_search_request(if let Some(msg) = find_search_body_script_limit_violation(body, aggs_value.as_ref()) {return Err(xerj_common::XerjError::invalid_query(msg));}+ if let Some(msg) = find_invalid_agg_order_path(aggs_value.as_ref()) {+ return Err(xerj_common::XerjError::invalid_query(msg));+ }let query_val = body.query.clone().unwrap_or(json!({ "match_all": {} }));@@ -25487,6 +25556,17 @@ async fn msearch_impl(}));continue;}+ if let Some(msg) = find_invalid_agg_order_path(+ search_body_val+ .get("aggs")+ .or_else(|| search_body_val.get("aggregations")),+ ) {+ responses.push(json!({+ "error": { "type": "illegal_argument_exception", "reason": msg },+ "status": 400+ }));+ continue;+ }// `rerank` is a `_search` stage and this path has its own, smaller// renderer. `parse_request` ignores keys it does not know, so without@@ -35742,6 +35822,13 @@ pub async fn search_template(if let Some(msg) = find_body_script_limit_violation(&search_body_val) {return ApiError::new(xerj_common::XerjError::invalid_query(msg)).into_response();}+ if let Some(msg) = find_invalid_agg_order_path(+ search_body_val+ .get("aggs")+ .or_else(|| search_body_val.get("aggregations")),+ ) {+ return ApiError::new(xerj_common::XerjError::invalid_query(msg)).into_response();+ }// A template that renders a `rerank` block: this minimal path does not run// the stage, and `parse_request` would drop the key without a word. Same@@ -35996,6 +36083,17 @@ async fn msearch_template_impl(}));continue;}+ if let Some(msg) = find_invalid_agg_order_path(+ search_body_val+ .get("aggs")+ .or_else(|| search_body_val.get("aggregations")),+ ) {+ responses.push(json!({+ "error": { "type": "illegal_argument_exception", "reason": msg },+ "status": 400+ }));+ continue;+ }let search_req = match xerj_query::parse_request(&search_body_val).map_err(|e| xerj_common::XerjError::invalid_query(e.to_string()))diff --git a/engine/crates/xerj-api/tests/terms_order_path_resolution.rs b/engine/crates/xerj-api/tests/terms_order_path_resolution.rsnew file mode 100644index 000000000..ac107a4bf--- /dev/null+++ b/engine/crates/xerj-api/tests/terms_order_path_resolution.rs@@ -0,0 +1,299 @@+//! Issues #1282 and #1283: how a `terms` aggregation's `order` resolves a+//! sub-aggregation path.+//!+//! - #1282: ordering by a value of a multi-value metric — `"p.95"` or+//! `"p[95.0]"` for a `percentiles` sub-agg — was silently ignored, so the+//! buckets came back key-ascending. ES 8.13.4 orders by the 95th percentile.+//! - #1283: an order path naming an aggregation the request does not define+//! (`"nope"`) returned HTTP 200 with the order dropped. ES 8.13.4 rejects+//! it with a 400: `Invalid aggregation order path [nope]. Cannot find+//! aggregation named [nope]`.+//!+//! Elasticsearch is referenced for wire semantics only; no ES code is+//! reproduced here.++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use tower::ServiceExt;++async fn app() -> (axum::Router, tempfile::TempDir) {+ let dir = tempfile::tempdir().expect("tempdir");+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ let state = xerj_api::state::AppState::new(config, engine, metrics);+ (xerj_api::router::build_es_compat_router(state), dir)+}++async fn send(+ app: &axum::Router,+ method: &str,+ path: &str,+ ctype: &str,+ body: String,+) -> (StatusCode, Value) {+ let mut req = Request::builder().method(method).uri(path);+ if !body.is_empty() {+ req = req.header("content-type", ctype);+ }+ let response = app+ .clone()+ .oneshot(req.body(Body::from(body)).unwrap())+ .await+ .unwrap();+ let status = response.status();+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ (+ status,+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),+ )+}++/// The issue's 4-document fixture: hosts a (p95 10), b (900), c (59.5, 2 docs).+async fn seeded() -> (axum::Router, tempfile::TempDir) {+ let (app, dir) = app().await;+ let (st, body) = send(+ &app,+ "PUT",+ "/repro",+ "application/json",+ json!({"mappings": {"properties": {+ "host": {"type": "keyword"},+ "ms": {"type": "float"}+ }}})+ .to_string(),+ )+ .await;+ assert_eq!(st, StatusCode::OK, "create index: {body}");+ let mut bulk = String::new();+ for (id, host, ms) in [+ ("1", "a", 10),+ ("2", "c", 60),+ ("3", "b", 900),+ ("4", "c", 50),+ ] {+ bulk.push_str(&format!(+ "{{\"index\":{{\"_index\":\"repro\",\"_id\":\"{id}\"}}}}\n"+ ));+ bulk.push_str(&format!("{{\"host\":\"{host}\",\"ms\":{ms}}}\n"));+ }+ let (st, body) = send(+ &app,+ "POST",+ "/_bulk?refresh=true",+ "application/x-ndjson",+ bulk,+ )+ .await;+ assert_eq!(st, StatusCode::OK, "bulk: {body}");+ assert_eq!(body["errors"], json!(false), "bulk: {body}");+ (app, dir)+}++fn keys(resp: &Value) -> Vec<String> {+ resp["aggregations"]["k"]["buckets"]+ .as_array()+ .unwrap_or_else(|| panic!("no buckets in {resp}"))+ .iter()+ .map(|b| b["key"].as_str().unwrap_or_default().to_string())+ .collect()+}++fn percentile_order_body(path: &str, dir: &str) -> String {+ json!({+ "size": 0,+ "aggs": {"k": {+ "terms": {"field": "host", "order": {path: dir}},+ "aggs": {"p": {"percentiles": {"field": "ms", "percents": [95]}}}+ }}+ })+ .to_string()+}++#[tokio::test]+async fn terms_orders_by_a_percentile_value() {+ let (app, _dir) = seeded().await;+ for path in ["p.95", "p[95.0]", "p[95]"] {+ let (st, resp) = send(+ &app,+ "POST",+ "/repro/_search",+ "application/json",+ percentile_order_body(path, "desc"),+ )+ .await;+ assert_eq!(st, StatusCode::OK, "{path}: {resp}");+ assert_eq!(keys(&resp), ["b", "c", "a"], "{path} desc: {resp}");++ let (st, resp) = send(+ &app,+ "POST",+ "/repro/_search",+ "application/json",+ percentile_order_body(path, "asc"),+ )+ .await;+ assert_eq!(st, StatusCode::OK, "{path}: {resp}");+ assert_eq!(keys(&resp), ["a", "c", "b"], "{path} asc: {resp}");+ }+}++/// Single-value metric ordering already worked; it must keep working.+#[tokio::test]+async fn terms_orders_by_a_single_value_metric() {+ let (app, _dir) = seeded().await;+ let body = json!({+ "size": 0,+ "aggs": {"k": {+ "terms": {"field": "host", "order": {"m": "desc"}},+ "aggs": {"m": {"max": {"field": "ms"}}}+ }}+ })+ .to_string();+ let (st, resp) = send(&app, "POST", "/repro/_search", "application/json", body).await;+ assert_eq!(st, StatusCode::OK, "{resp}");+ assert_eq!(keys(&resp), ["b", "c", "a"], "{resp}");+}++fn unknown_order_body(path: &str, with_sub: bool) -> Value {+ let mut terms = json!({"k": {"terms": {"field": "host", "order": {path: "desc"}}}});+ if with_sub {+ terms["k"]["aggs"] = json!({"m": {"max": {"field": "ms"}}});+ }+ json!({"size": 0, "aggs": terms})+}++#[tokio::test]+async fn terms_order_on_an_unknown_aggregation_is_a_400_on_search() {+ let (app, _dir) = seeded().await;+ // Reasons verified byte-for-byte against ES 8.13.4 for these four shapes.+ for (path, with_sub, missing) in [+ ("nope", false, "nope"),+ ("nope", true, "nope"),+ ("nope.95", true, "nope"),+ ("nope[95.0]", true, "nope"),+ ("_term", false, "_term"),+ ] {+ let body = unknown_order_body(path, with_sub);+ let (st, resp) = send(+ &app,+ "POST",+ "/repro/_search",+ "application/json",+ body.to_string(),+ )+ .await;+ assert_eq!(st, StatusCode::BAD_REQUEST, "{path}: {resp}");+ let reason = resp.to_string();+ assert!(+ reason.contains(&format!(+ "Invalid aggregation order path [{path}]. Cannot find aggregation named [{missing}]"+ )),+ "{path}: reason must name the path and the missing aggregation: {resp}"+ );+ }+}++/// A chain through a metric (`m>nope`): ES 8.13.4 answers 400 with a+/// different reason ("Metrics aggregations cannot have sub-aggregations"), so+/// only the status and the path are pinned here.+#[tokio::test]+async fn order_path_chained_past_a_metric_is_a_400() {+ let (app, _dir) = seeded().await;+ let body = unknown_order_body("m>nope", true);+ let (st, resp) = send(+ &app,+ "POST",+ "/repro/_search",+ "application/json",+ body.to_string(),+ )+ .await;+ assert_eq!(st, StatusCode::BAD_REQUEST, "{resp}");+ assert!(+ resp.to_string()+ .contains("Invalid aggregation order path [m>nope]"),+ "{resp}"+ );+}++/// `_count` / `_key` are built-in order keys, never sub-aggregation names.+#[tokio::test]+async fn builtin_order_keys_stay_valid() {+ let (app, _dir) = seeded().await;+ for path in ["_count", "_key"] {+ let body = unknown_order_body(path, false);+ let (st, resp) = send(+ &app,+ "POST",+ "/repro/_search",+ "application/json",+ body.to_string(),+ )+ .await;+ assert_eq!(st, StatusCode::OK, "{path}: {resp}");+ }+}++/// Nested terms: the check applies at every level, against that level's own+/// sub-aggregations.+#[tokio::test]+async fn unknown_order_path_in_a_nested_terms_is_a_400() {+ let (app, _dir) = seeded().await;+ let body = json!({+ "size": 0,+ "aggs": {"outer": {+ "terms": {"field": "host"},+ "aggs": {+ "m": {"max": {"field": "ms"}},+ "inner": {"terms": {"field": "host", "order": {"m": "desc"}}}+ }+ }}+ });+ let (st, resp) = send(+ &app,+ "POST",+ "/repro/_search",+ "application/json",+ body.to_string(),+ )+ .await;+ // ES 8.13.4: 400 `invalid_path`, "Invalid aggregation order path [m]. The+ // provided aggregation [m] either does not exist, ..." — status and path+ // pinned, not the wording.+ assert_eq!(+ st,+ StatusCode::BAD_REQUEST,+ "inner order names the outer's sibling: {resp}"+ );+ assert!(+ resp.to_string()+ .contains("Invalid aggregation order path [m]"),+ "{resp}"+ );+}++/// `_msearch` fails only the offending item, with ES's per-item error shape.+#[tokio::test]+async fn unknown_order_path_fails_only_that_msearch_item() {+ let (app, _dir) = seeded().await;+ let bad = unknown_order_body("nope", false);+ let good = json!({"size": 0, "query": {"match_all": {}}});+ let ndjson = format!("{{\"index\":\"repro\"}}\n{bad}\n{{\"index\":\"repro\"}}\n{good}\n");+ let (st, resp) = send(&app, "POST", "/_msearch", "application/x-ndjson", ndjson).await;+ assert_eq!(st, StatusCode::OK, "{resp}");+ let items = resp["responses"].as_array().expect("responses");+ assert_eq!(items[0]["status"], 400, "bad item: {resp}");+ assert!(+ items[0]+ .to_string()+ .contains("Invalid aggregation order path [nope]"),+ "bad item reason: {resp}"+ );+ assert_eq!(items[1]["status"], 200, "good item still runs: {resp}");+}diff --git a/engine/crates/xerj-engine/src/aggs.rs b/engine/crates/xerj-engine/src/aggs.rsindex b9b0f242d..f0ead9a12 100644--- a/engine/crates/xerj-engine/src/aggs.rs+++ b/engine/crates/xerj-engine/src/aggs.rs@@ -4031,7 +4031,7 @@ fn lookup_agg_metric(sub: Option<&Value>, path: &str) -> f64 {for seg in normalized.split('.').filter(|s| !s.is_empty()) {match cur.get(seg) {Some(v) => cur = v,- None => return f64::NEG_INFINITY,+ None => return lookup_keyed_metric(root, path).unwrap_or(f64::NEG_INFINITY),}}if let Some(v) = cur.get("value") {@@ -4039,7 +4039,52 @@ fn lookup_agg_metric(sub: Option<&Value>, path: &str) -> f64 {return f;}}- cur.as_f64().unwrap_or(f64::NEG_INFINITY)+ cur.as_f64()+ .or_else(|| lookup_keyed_metric(root, path))+ .unwrap_or(f64::NEG_INFINITY)+}++/// ES's value-key form for a multi-value metric (#1282): `p.95` or `p[95.0]`+/// on a `percentiles` sub-agg names the 95th percentile, which lives at+/// `p.values["95.0"]` (or in a `{key, value}` array when `keyed: false`). The+/// plain dotted walk above cannot reach it — `"95"` is not the stored key, and+/// `[95.0]` is not a segment — so it ranked every bucket as equal and the+/// terms order silently fell back to the key tiebreaker.+fn lookup_keyed_metric(root: &Value, path: &str) -> Option<f64> {+ let (chain, last) = match path.rsplit_once('>') {+ Some((chain, last)) => (Some(chain), last),+ None => (None, path),+ };+ let mut cur = root;+ for name in chain.into_iter().flat_map(|c| c.split('>')) {+ cur = cur.get(name)?;+ }+ let (name, key) = match last.split_once('[') {+ Some((name, rest)) => (name, rest.strip_suffix(']')?),+ None => last.split_once('.')?,+ };+ let agg = cur.get(name)?;+ if let Some(f) = agg.get(key).and_then(Value::as_f64) {+ return Some(f);+ }+ let want = key.parse::<f64>().ok();+ let same_key = |k: &str| want.is_some() && k.parse::<f64>().ok() == want;+ match agg.get("values")? {+ Value::Object(values) => values+ .get(key)+ .or_else(|| values.iter().find(|(k, _)| same_key(k)).map(|(_, v)| v))+ .and_then(Value::as_f64),+ Value::Array(entries) => entries+ .iter()+ .find(|e| match e.get("key") {+ Some(Value::String(k)) => same_key(k),+ Some(k) => k.as_f64().is_some() && k.as_f64() == want,+ None => false,+ })+ .and_then(|e| e.get("value"))+ .and_then(Value::as_f64),+ _ => None,+ }}fn run_ip_prefix(diff --git a/engine/tests/es-compat-yaml/yaml/aggregations/terms_order_path.yml b/engine/tests/es-compat-yaml/yaml/aggregations/terms_order_path.ymlnew file mode 100644index 000000000..fed2fc254--- /dev/null+++ b/engine/tests/es-compat-yaml/yaml/aggregations/terms_order_path.yml@@ -0,0 +1,95 @@+setup:+ - do:+ indices.create:+ index: terms_order_path+ body:+ mappings:+ properties:+ host:+ type: keyword+ ms:+ type: float+ - do:+ bulk:+ refresh: true+ body:+ - '{"index": {"_index": "terms_order_path", "_id": "1"}}'+ - '{"host": "a", "ms": 10}'+ - '{"index": {"_index": "terms_order_path", "_id": "2"}}'+ - '{"host": "c", "ms": 60}'+ - '{"index": {"_index": "terms_order_path", "_id": "3"}}'+ - '{"host": "b", "ms": 900}'+ - '{"index": {"_index": "terms_order_path", "_id": "4"}}'+ - '{"host": "c", "ms": 50}'++---+"terms ordered by a percentiles value key (#1282)":+ - do:+ search:+ index: terms_order_path+ body:+ size: 0+ aggs:+ k:+ terms:+ field: host+ order: { "p.95": desc }+ aggs:+ p:+ percentiles:+ field: ms+ percents: [ 95 ]++ - match: { aggregations.k.buckets.0.key: b }+ - match: { aggregations.k.buckets.1.key: c }+ - match: { aggregations.k.buckets.2.key: a }++ - do:+ search:+ index: terms_order_path+ body:+ size: 0+ aggs:+ k:+ terms:+ field: host+ order: { "p[95.0]": asc }+ aggs:+ p:+ percentiles:+ field: ms+ percents: [ 95 ]++ - match: { aggregations.k.buckets.0.key: a }+ - match: { aggregations.k.buckets.1.key: c }+ - match: { aggregations.k.buckets.2.key: b }++---+"terms order on an undefined aggregation is a 400 (#1283)":+ - do:+ catch: bad_request+ search:+ index: terms_order_path+ body:+ size: 0+ aggs:+ k:+ terms:+ field: host+ order: { nope: desc }++ - do:+ catch: bad_request+ search:+ index: terms_order_path+ body:+ size: 0+ aggs:+ k:+ terms:+ field: host+ order: [ { _count: desc }, { "nope.95": asc } ]+ aggs:+ m:+ max:+ field: ms