Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(aggs): range aggregations bucket every value of a multi-valued field (#1803)

ordinary being1a4fbb561cbd
diff --git a/engine/crates/xerj-engine/src/aggs.rs b/engine/crates/xerj-engine/src/aggs.rs
index 5092ad05c..e0074bd11 100644
--- a/engine/crates/xerj-engine/src/aggs.rs
+++ b/engine/crates/xerj-engine/src/aggs.rs
@@ -7424,23 +7424,31 @@ fn run_range(
let bucket_docs: Vec<Value> = docs
.iter()
.filter(|doc| {
- let num = if is_date_range {
+ // A multi-valued field contributes the document to a bucket
+ // when ANY of its values falls in range (ES value-source
+ // semantics). This used to read the first value only
+ // (`extract_numeric`/`.first()`), so [22, 8080] counted in
+ // `[.., 100)` and vanished from `[8000, 9000)`.
+ let mut values: Vec<f64> = if is_date_range {
extract_date_ms_values(doc, field)
- .first()
- .copied()
+ .into_iter()
.map(|ms| ms as f64)
+ .collect()
} else {
- extract_numeric(doc, field)
+ extract_numeric_values(doc, field)
};
- // Fall back to `missing` for docs without a value.
- let num = num.or(missing_val);
- match (num, from, to) {
- (Some(n), Some(f), Some(t)) => n >= f && n < t,
- (Some(n), Some(f), None) => n >= f,
- (Some(n), None, Some(t)) => n < t,
- (Some(_), None, None) => true,
- _ => false,
+ // `missing` applies only to a document with NO value.
+ if values.is_empty() {
+ if let Some(m) = missing_val {
+ values.push(m);
+ }
}
+ values.iter().any(|n| match (from, to) {
+ (Some(f), Some(t)) => *n >= f && *n < t,
+ (Some(f), None) => *n >= f,
+ (None, Some(t)) => *n < t,
+ (None, None) => true,
+ })
})
.cloned()
.collect();
@@ -12338,13 +12346,27 @@ fn run_date_range(
// Doc values honor the field-declared format too: a doc
// stored as `{date: 1000}` under `format: epoch_second`
// means 1000 seconds = 1 000 000 ms.
- let doc_ms = match v.and_then(&parse_with_fmt).or(missing_ms) {
- Some(m) => m,
- None => return false,
+ //
+ // A multi-valued field contributes the document when ANY of
+ // its values falls in range (ES value-source semantics); the
+ // array used to be handed to `parse_with_fmt` whole, which
+ // could not parse it, so every array-valued document was
+ // silently missed.
+ let mut values: Vec<i64> = match v {
+ Some(Value::Array(arr)) => arr.iter().filter_map(&parse_with_fmt).collect(),
+ Some(single) => parse_with_fmt(single).into_iter().collect(),
+ None => Vec::new(),
};
- let passes_from = from_ms.map(|f| doc_ms >= f).unwrap_or(true);
- let passes_to = to_ms.map(|t| doc_ms < t).unwrap_or(true);
- passes_from && passes_to
+ if values.is_empty() {
+ if let Some(m) = missing_ms {
+ values.push(m);
+ }
+ }
+ values.iter().any(|ms| {
+ let passes_from = from_ms.map(|f| *ms >= f).unwrap_or(true);
+ let passes_to = to_ms.map(|t| *ms < t).unwrap_or(true);
+ passes_from && passes_to
+ })
})
.cloned()
.collect();
@@ -13985,21 +14007,27 @@ fn run_ip_range(
let val = doc
.get(field)
.or_else(|| doc.get("_source").and_then(|s| s.get(field)));
- let ip_str = match val.and_then(Value::as_str) {
- Some(s) => s,
- None => return false,
+ // A multi-valued ip field contributes the document when ANY
+ // of its addresses falls in range (ES value-source
+ // semantics); the previous `Value::as_str` read returned None
+ // for an array, so array-valued documents were missed.
+ let addrs: Vec<&str> = match val {
+ Some(Value::Array(arr)) => arr.iter().filter_map(Value::as_str).collect(),
+ Some(Value::String(s)) => vec![s.as_str()],
+ _ => Vec::new(),
};
- if let Some(m) = mask {
- cidr_matches(ip_str, m)
- } else {
- let ip_u = match ip_as_u128(ip_str) {
- Some(v) => v,
- None => return false,
- };
- let passes_from = from_u.map(|f| ip_u >= f).unwrap_or(true);
- let passes_to = to_u.map(|t| ip_u < t).unwrap_or(true);
- passes_from && passes_to
- }
+ addrs.iter().any(|ip_str| {
+ if let Some(m) = mask {
+ cidr_matches(ip_str, m)
+ } else {
+ let Some(ip_u) = ip_as_u128(ip_str) else {
+ return false;
+ };
+ let passes_from = from_u.map(|f| ip_u >= f).unwrap_or(true);
+ let passes_to = to_u.map(|t| ip_u < t).unwrap_or(true);
+ passes_from && passes_to
+ }
+ })
})
.cloned()
.collect();
diff --git a/engine/crates/xerj-engine/tests/aggs_range_multi_valued.rs b/engine/crates/xerj-engine/tests/aggs_range_multi_valued.rs
new file mode 100644
index 000000000..65730eb39
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/aggs_range_multi_valued.rs
@@ -0,0 +1,207 @@
+//! Range bucket aggregations must look at every value of a multi-valued
+//! field, not just the first one.
+//!
+//! Found while verifying #1750 (`range` query on arrays): the query side is
+//! fixed separately (PR #1776), but the three range **aggregation** types had
+//! the same blind spot on the aggregation path:
+//!
+//! * `range` read `extract_numeric(doc, field)` — the first numeric element —
+//! so `[7, 8080]` counted in `[.., 10)` and vanished from `[8000, 9000)`;
+//! * `date_range` handed the whole array to the per-value date parser, which
+//! returned `None` for an array, so every array-valued date document was
+//! missed entirely;
+//! * `ip_range` read `Value::as_str()`, which is `None` for an array, so every
+//! array-valued address was missed.
+//!
+//! ES buckets a document into every range that ANY of its values falls into,
+//! and counts it once per bucket (a document is one document). That is the
+//! contract asserted here; the `[5, 7]` document pins the once-per-bucket
+//! half.
+
+use serde_json::{json, Value};
+use tempfile::TempDir;
+use xerj_common::config::Config;
+use xerj_common::types::{FieldConfig, FieldType, Schema};
+use xerj_engine::Engine;
+use xerj_query::parse_request;
+
+fn make_engine(dir: &TempDir) -> Engine {
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ Engine::new(config).expect("engine::new")
+}
+
+fn events_schema() -> Schema {
+ let mut schema = Schema::empty();
+ schema
+ .fields
+ .push(FieldConfig::new("ports", FieldType::Long));
+ schema
+ .fields
+ .push(FieldConfig::new("seen", FieldType::Date));
+ schema.fields.push(FieldConfig::new("ipf", FieldType::Ip));
+ schema
+}
+
+async fn seed(engine: &Engine) -> std::sync::Arc<xerj_engine::Index> {
+ engine.create_index("events", events_schema()).unwrap();
+ let idx = engine.get_index("events").unwrap();
+ for (id, doc) in [
+ (
+ "1",
+ json!({
+ "ports": [7, 8080],
+ "seen": ["2019-01-01", "2022-06-01"],
+ "ipf": ["192.168.0.1", "10.0.0.3"],
+ }),
+ ),
+ (
+ "2",
+ json!({
+ "ports": 443,
+ "seen": "2024-01-01",
+ "ipf": "172.16.0.1",
+ }),
+ ),
+ (
+ "3",
+ json!({
+ "ports": [5, 7],
+ "seen": ["2021-06-01", "2030-01-01"],
+ "ipf": ["10.0.0.9", "10.0.0.4"],
+ }),
+ ),
+ // No value for any of the three fields: exercises `missing`.
+ ("4", json!({"note": "no values"})),
+ ] {
+ idx.index_document(Some(id.into()), doc).await.unwrap();
+ }
+ idx.refresh().await.unwrap();
+ idx
+}
+
+async fn aggs(idx: &xerj_engine::Index, aggs: Value) -> Value {
+ let req = parse_request(&json!({
+ "query": { "match_all": {} },
+ "size": 0,
+ "aggs": aggs,
+ }))
+ .expect("parse_request");
+ idx.search(&req)
+ .await
+ .unwrap()
+ .aggs
+ .expect("aggs in the response")
+}
+
+fn counts(bucket: &Value) -> Vec<u64> {
+ bucket["buckets"]
+ .as_array()
+ .unwrap_or_else(|| panic!("expected buckets, got {bucket}"))
+ .iter()
+ .map(|b| {
+ b["doc_count"]
+ .as_u64()
+ .unwrap_or_else(|| panic!("no doc_count: {b}"))
+ })
+ .collect()
+}
+
+#[tokio::test]
+async fn range_aggregations_bucket_every_value_of_a_multi_valued_field() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ let idx = seed(&engine).await;
+
+ let body = aggs(
+ &idx,
+ json!({
+ "ports": {
+ "range": {
+ "field": "ports",
+ "ranges": [
+ { "from": 8000, "to": 9000 },
+ { "to": 10 },
+ { "from": 8000 }
+ ]
+ }
+ },
+ "dates": {
+ "date_range": {
+ "field": "seen",
+ "ranges": [{ "from": "2021-01-01", "to": "2023-01-01" }]
+ }
+ },
+ "dates_via_range": {
+ "range": {
+ "field": "seen",
+ "ranges": [{ "from": "2021-01-01", "to": "2023-01-01" }]
+ }
+ },
+ "ips": {
+ "ip_range": {
+ "field": "ipf",
+ "ranges": [{ "from": "10.0.0.1", "to": "10.0.0.5" }]
+ }
+ },
+ "ips_mask": {
+ "ip_range": {
+ "field": "ipf",
+ "ranges": [{ "mask": "10.0.0.0/24" }]
+ }
+ },
+ "ports_missing": {
+ "range": {
+ "field": "ports",
+ "missing": 6,
+ "ranges": [{ "to": 10 }]
+ }
+ }
+ }),
+ )
+ .await;
+
+ // d1's 8080 is its SECOND value; d3's 9000 is excluded by `to`.
+ assert_eq!(
+ counts(&body["ports"]),
+ vec![1, 2, 1],
+ "ports range must bucket every value: {body}"
+ );
+ // d1's 2022-06-01 and d3's 2021-06-01 are both second values.
+ assert_eq!(counts(&body["dates"]), vec![2], "date_range: {body}");
+ // Same data through `range` (string bounds select its date branch).
+ assert_eq!(
+ counts(&body["dates_via_range"]),
+ vec![2],
+ "range on dates: {body}"
+ );
+ // d1's 10.0.0.3 and d3's 10.0.0.4.
+ assert_eq!(counts(&body["ips"]), vec![2], "ip_range: {body}");
+ assert_eq!(counts(&body["ips_mask"]), vec![2], "ip_range mask: {body}");
+ // `missing` applies only to d4 (no value at all), never to a doc whose
+ // array merely has no element in range.
+ assert_eq!(
+ counts(&body["ports_missing"]),
+ vec![3],
+ "missing applies once, only to docs without a value: {body}"
+ );
+}
+
+/// The same three aggregations must agree before and after a flush: the
+/// aggregation path reads `_source` on both sides, so a value-drop here is a
+/// data bug, not a timing one.
+#[tokio::test]
+async fn range_aggregations_are_flush_invariant() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ let idx = seed(&engine).await;
+ let aggs_def = json!({
+ "ports": { "range": { "field": "ports", "ranges": [{ "from": 8000, "to": 9000 }] } },
+ "dates": { "date_range": { "field": "seen", "ranges": [{ "from": "2021-01-01", "to": "2023-01-01" }] } },
+ "ips": { "ip_range": { "field": "ipf", "ranges": [{ "from": "10.0.0.1", "to": "10.0.0.5" }] } }
+ });
+ let before = aggs(&idx, aggs_def.clone()).await;
+ idx.flush().await.unwrap();
+ let after = aggs(&idx, aggs_def).await;
+ assert_eq!(before, after, "range aggs must not change at a flush");
+}
diff --git a/engine/tests/es-compat-yaml/yaml/aggregations/range_multi_valued.yml b/engine/tests/es-compat-yaml/yaml/aggregations/range_multi_valued.yml
new file mode 100644
index 000000000..aa5290ed9
--- /dev/null
+++ b/engine/tests/es-compat-yaml/yaml/aggregations/range_multi_valued.yml
@@ -0,0 +1,71 @@
+setup:
+ - do:
+ indices.create:
+ index: events
+ body:
+ mappings:
+ properties:
+ ports:
+ type: long
+ seen:
+ type: date
+ ipf:
+ type: ip
+ - do:
+ bulk:
+ index: events
+ refresh: true
+ body:
+ - index:
+ _id: "1"
+ - ports: [22, 8080]
+ seen: ["2020-01-01", "2024-06-01"]
+ ipf: ["192.168.0.1", "10.0.0.3"]
+ - index:
+ _id: "2"
+ - ports: 443
+ seen: "2024-01-01"
+ ipf: "172.16.0.1"
+ - index:
+ _id: "3"
+ - ports: [5, 9000]
+ seen: ["2030-01-01", "2021-06-01"]
+ ipf: ["10.0.0.9", "10.0.0.4"]
+
+---
+"Range, date_range and ip_range bucket every value of a multi-valued field":
+
+ - do:
+ search:
+ index: events
+ body:
+ size: 0
+ aggs:
+ ports:
+ range:
+ field: ports
+ ranges:
+ - to: 100
+ - from: 8000
+ to: 9000
+ dates:
+ date_range:
+ field: seen
+ ranges:
+ - from: "2021-01-01"
+ to: "2023-01-01"
+ ips:
+ ip_range:
+ field: ipf
+ ranges:
+ - from: "10.0.0.1"
+ to: "10.0.0.5"
+ - match: { hits.total.value: 3 }
+ # doc 1 (22) and doc 3 (5); doc 2 is 443.
+ - match: { aggregations.ports.buckets.0.doc_count: 2 }
+ # doc 1's 8080 is its SECOND value; doc 3's 9000 is excluded by `to`.
+ - match: { aggregations.ports.buckets.1.doc_count: 1 }
+ # doc 3's 2021-06-01 is a second value; doc 1's 2024 is out, doc 2's 2024 is out.
+ - match: { aggregations.dates.buckets.0.doc_count: 1 }
+ # doc 1's 10.0.0.3 and doc 3's 10.0.0.4 are second/first values in range.
+ - match: { aggregations.ips.buckets.0.doc_count: 2 }