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): execute weighted_avg and fail loud on unsupported shapes (#2805)

SheckHall5023f8350552
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f7eeae6df..0623ecd94 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -95,6 +95,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- `weighted_avg` now executes field-based requests (`value` / `weight`, each
+ with a `field` and optional numeric `missing`) instead of returning HTTP 200
+ with an `unsupported aggregation type` error in the aggregations body. A
+ `script` on either side, a malformed side, a missing `field`, and a
+ non-numeric `missing` return a 400 naming the side. Multi-index searches
+ recombine by weighted sum, not by averaging the per-index values. A
+ multi-valued weight field is skipped rather than refused, because the
+ aggregation evaluator has no error channel; that case stays in
+ `catch-lenient.txt` (#204).
+
- Re-indexing the same doc ids no longer grows `hnsw/graph.bin` without
bound. Each overwrite tombstoned the old graph node and nothing ever
removed one, so the graph (on disk and in memory) kept every vector ever
diff --git a/ROADMAP.md b/ROADMAP.md
index 9825fe298..340ecb858 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -280,7 +280,7 @@ These are implemented and exercised by real API requests / the test suite / benc
- Elasticsearch REST wire compatibility (1,444 / 1,454 ES-YAML conformance cases on main CI, 2026-10-23; the gate on every change is **0 failed**, and the case count grows as cases are added — read the current number off CI, not off this file).
- Full-text search (BM25) and **<!-- generated:query-type-count -->50<!-- /generated:query-type-count --> query types**. Neither the list nor the number is maintained by hand here: the list is generated from `xerj_query::parser::SUPPORTED_QUERY_TYPES`, printed in full in [engine/README.md](./engine/README.md#query-types-supported) and [llms-full.txt](https://xerj.org/llms-full.txt), and pinned to `parse_query`'s dispatch table by `parser::tests::dispatch_table_matches_capability_manifest`; the number above sits in a machine-checked region pinned to that constant's length by `docs_capability_lists::published_capability_counts_match_the_constants`. A further <!-- generated:rejected-query-type-count -->2<!-- /generated:rejected-query-type-count --> keys — `has_child` and `has_parent` — are recognised and **rejected with a 400**, and are listed as such in the same places (issue #211).
**Honest caveat, unchanged:** that count is the *dispatch* surface — every name on it parses, plans and executes, which is not a claim that every one is semantically faithful to ES. The known divergences are enumerated under *Known partials* below, and the ES-YAML conformance suite is the measured answer.
-- **Aggregations: <!-- generated:agg-type-count -->62<!-- /generated:agg-type-count --> types**, likewise generated from `xerj_engine::aggs::SUPPORTED_AGG_TYPES`, printed in [engine/README.md](./engine/README.md#aggregation-types-supported) and [llms-full.txt](https://xerj.org/llms-full.txt), and pinned by the same count test. This includes the full **pipeline family**. `weighted_avg` is **not** in `SUPPORTED_AGG_TYPES` — see *Known partials*.
+- **Aggregations: <!-- generated:agg-type-count -->63<!-- /generated:agg-type-count --> types**, likewise generated from `xerj_engine::aggs::SUPPORTED_AGG_TYPES`, printed in [engine/README.md](./engine/README.md#aggregation-types-supported) and [llms-full.txt](https://xerj.org/llms-full.txt), and pinned by the same count test. This includes the full **pipeline family**. `weighted_avg` is field-based (`value` / `weight` objects with `field` and optional `missing`); see *Known partials* for the shapes it does not run.
**Exactness, precisely.** No probabilistic sketch sits in the metric path: `cardinality` is a true distinct count rather than an HLL estimate, and `terms` `doc_count` is precise. Two deliberate exceptions, stated the same way in `engine/README.md` and `llms-full.txt`: (1) the **sampling family** is a sample by definition — `run_sampler` sorts the matched documents by `_score` and keeps the first `shard_size` (default **200**), so every sub-aggregation under `sampler`, `random_sampler` or `diversified_sampler` is computed over that slice rather than the whole match set, `diversified_sampler` additionally caps documents per `field` value, and `random_sampler` shares the `sampler` implementation and **ignores ES's `probability`** (an accepted-and-ignored input, #204); (2) `percentiles` with the `hdr` option returns HdrHistogram-quantized values, deliberately, so ES's own outputs reproduce — the default `tdigest` path sorts every value and interpolates instead.
- **Dense-vector kNN** (`knn` query and ES 8.x top-level `knn`): unfiltered kNN on a full-precision cosine field (≥1,024 docs) is served by a **persisted HNSW graph with exact rescoring** — measured recall@10 1.00 on the official bench query, 100-probe mean 0.976 (ES 8.13.4 same protocol: 0.937); filtered/nested kNN, non-cosine similarity, SQ8 fields, and small indexes run the exact brute-force scan (cosine mapped to `(1+cos)/2`).
- **Hybrid search** — BM25 + kNN combined in a single request via the `hybrid` **query type** with `rrf|linear` fusion, verified live. (`fusion: "learned"` is parsed and **rejected** with a 400 naming the supported values — it is not implemented.) (The ES-native top-level `{query, knn}` body also unions both halves since rc.72 — see *Known partials* for its performance caveat.)
@@ -576,7 +576,7 @@ The 1.0 bar: **every public claim verified against the release binary, and every
**The program to the first official release** ([discussion #1054](https://github.com/xerj-org/xerj/discussions/1054); filed as ten issues indexed in [tracker #1065](https://github.com/xerj-org/xerj/issues/1065)) — **executed whole in rc.80** (rc.79 folded into the cut by direction), every item measured on the release binary and every gate verdict published whether it passed or not. Passed: `xerj_map` ([#1055](https://github.com/xerj-org/xerj/issues/1055), unknown-field 400s 20/30 → 0/30), `/_ask` + `xerj_plan` ([#1056](https://github.com/xerj-org/xerj/issues/1056), macro-F1 0.9975 / p50 1.129 ms), MCP `max_tokens` ([#1058](https://github.com/xerj-org/xerj/issues/1058)), the calibration layer ([#1063](https://github.com/xerj-org/xerj/issues/1063), FiQA pair-level ECE 0.3109 → 0.0088 held-out), and the `xerj-decide` training harness with its measured eval card ([#1064](https://github.com/xerj-org/xerj/issues/1064) — the artifact's Hugging Face publication still PENDING operator credentials; no URL is claimed). Failed, shipped under its own loses-does-not-ship rule with the numbers public: the local judge ([#1060](https://github.com/xerj-org/xerj/issues/1060), −0.1077 SciFact vs hybrid — opt-in, no quality claim) and the flywheel's cache-share bar ([#1061](https://github.com/xerj-org/xerj/issues/1061), the write-back freeze is now defect #1094). Split: stemming ([#1059](https://github.com/xerj-org/xerj/issues/1059), +0.0160/+0.0179 BM25 nDCG@10, zero-hits 25 → 15 against ≤ 10). Real and, against #1062's wrong-and-confident ≤ 5 % bar, measured on rc.94 and **failing**: `_watcher` detections ([#1062](https://github.com/xerj-org/xerj/issues/1062) — the evaluate-or-501 half shipped; the detection gate was run through the real watcher path in [#1108](https://github.com/xerj-org/xerj/issues/1108) and scored 0.2449 wrong-and-confident at raw `p` ≥ 0.8 vs the ≤ 5 % bar, published under loses-does-not-ship in `benchmarks/systemone-watcher-gate/`). The tier-2 decide head ([#1057](https://github.com/xerj-org/xerj/issues/1057)) missed its SMS/AG News bars and ships behind `--decide-mode local` with the numbers published, arming on the stock binary since #1097. The packaging rule held for all ten: a `benchmarks/<name>` directory with raw results plus [the blog post](https://xerj.org/blog/the-rc80-gates) with the losses left in.
-- **Close the accepted-and-ignored class** (the [#204](https://github.com/xerj-org/xerj/issues/204) umbrella closed once its members carried their own tracking; PR [#258](https://github.com/xerj-org/xerj/pull/258) carried one pass of the sweep and is merged). Known members still open: `nested` `inner_hits` unparsed; `random_sampler`'s ignored `probability`; `weighted_avg` returning HTTP 200 with an error buried in the aggregations body instead of a 400 (the 400 is part of #258). **Retired from this list:** `nested` `score_mode`, which was parsed-then-ignored until [#862](https://github.com/xerj-org/xerj/pull/862) made a nested query roll its matching children's scores into the parent per `score_mode` (rc.71).
+- **Close the accepted-and-ignored class** (the [#204](https://github.com/xerj-org/xerj/issues/204) umbrella closed once its members carried their own tracking; PR [#258](https://github.com/xerj-org/xerj/pull/258) carried one pass of the sweep and is merged). Known members still open: `nested` `inner_hits` unparsed; `random_sampler`'s ignored `probability`. **Retired from this list:** `nested` `score_mode`, which was parsed-then-ignored until [#862](https://github.com/xerj-org/xerj/pull/862) made a nested query roll its matching children's scores into the parent per `score_mode` (rc.71); and `weighted_avg`, which used to answer HTTP 200 with an error buried in the aggregations body and now executes field-based requests (rejecting `script` and malformed sides with a 400).
- **Security hardening backlog** — cargo-audit and fuzzing landed in CI with rc.16 ([#207](https://github.com/xerj-org/xerj/issues/207) closed); the deferred TLS/auth/symlink hardening items from the Phase-2 security backlog remain.
- **The mixed read-under-write p99 gap** — the 4 benchmark losses out of 85 measured comparisons, all the same root cause (reads landing on the live memtable under writer pressure). Written up in [`demo/playbooks/MIXED_READ_UNDER_WRITE_FINDING_2026-07-08.md`](./demo/playbooks/MIXED_READ_UNDER_WRITE_FINDING_2026-07-08.md); the candidate fix is a visibility/parity-mode design decision, not a micro-optimisation, and it stays on the GA gate until fixed or explicitly descoped with the benchmark loss kept public.
- **Ship-or-descope every entry in *Known partials* below.** GA does not ship with a "partial" section that reads like a feature list.
@@ -658,7 +658,7 @@ Honesty section: things that resolve without an error but do not implement full
Re-verified against `main` 2026-08-30:
-- **`weighted_avg`** — not in `SUPPORTED_AGG_TYPES`; still returns HTTP 200 with an embedded error instead of executing or returning 400 (the 400 is part of the #258 sweep).
+- **`weighted_avg`** — field-based `value` / `weight` request shapes execute, including multi-valued value fields and `missing`; `script` on either side and a malformed side are refused with a 400. A multi-valued *weight* field is skipped instead of raising ES's 400, because the aggregation evaluator has no error channel; that case remains in `tests/es-compat-yaml/catch-lenient.txt`.
- **`has_child` / `has_parent`** — recognised and rejected with a 400 (fail-loud by design until real parent-child join semantics exist; `REJECTED_QUERY_TYPES` in `parser.rs`).
Carried forward from the 2026-07-12 review, not re-verified live since:
diff --git a/engine/README.md b/engine/README.md
index 08929fb62..6bd2102ce 100644
--- a/engine/README.md
+++ b/engine/README.md
@@ -258,7 +258,7 @@ set (O(N) memory) instead of a sketch.
Metric — `avg`, `sum`, `min`, `max`, `stats`, `extended_stats`, `value_count`,
`cardinality`, `percentiles`, `percentile_ranks`, `median_absolute_deviation`,
`matrix_stats`, `string_stats`, `boxplot`, `top_metrics`, `top_hits`,
-`scripted_metric`
+`scripted_metric`, `weighted_avg`
Bucket — `terms`, `multi_terms`, `rare_terms`, `significant_terms`,
`significant_text`, `range`, `date_range`, `ip_range`, `ip_prefix`,
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index b6d2715bb..07d374de2 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -6544,6 +6544,32 @@ fn merge_metric_agg(old: &Value, new: &Value) -> Option<Value> {
.and_then(Value::as_str)
.or_else(|| new_obj.get("__xy_agg__").and_then(Value::as_str));
if let Some(t) = agg_type {
+ // Weighted averages combine as total weighted sum over total weight;
+ // averaging the two per-index values would weight each index equally.
+ if t == "weighted_avg" {
+ let sums = |o: &serde_json::Map<String, Value>| {
+ Some((
+ o.get("__xy_weight_sum__").and_then(Value::as_f64)?,
+ o.get("__xy_weighted_sum__").and_then(Value::as_f64)?,
+ ))
+ };
+ if let (Some((weight_a, value_a)), Some((weight_b, value_b))) =
+ (sums(old_obj), sums(new_obj))
+ {
+ let total_weight = weight_a + weight_b;
+ let value = if total_weight == 0.0 {
+ Value::Null
+ } else {
+ serde_json::json!((value_a + value_b) / total_weight)
+ };
+ return Some(serde_json::json!({
+ "value": value,
+ "__xy_agg__": "weighted_avg",
+ "__xy_weight_sum__": total_weight,
+ "__xy_weighted_sum__": value_a + value_b,
+ }));
+ }
+ }
// Cardinality unions the distinct value sets carried as an
// internal `__xy_values__` array so multi-index results are a
// true union, not a sum (which would double-count values present
@@ -6944,6 +6970,28 @@ mod merge_bucket_agg_keyed_tests {
assert_eq!(merged["buckets"]["a"]["doc_count"], 3);
assert_eq!(merged["buckets"]["b"]["doc_count"], 4);
}
+
+ /// `weighted_avg` carries its numerator and denominator as internal
+ /// tracking keys so a multi-index search recombines them. Averaging the
+ /// two per-index values would weight each index equally regardless of its
+ /// total weight — here that would be 3.0, not the correct 3.5.
+ #[test]
+ fn weighted_avg_recombines_across_indices() {
+ let index_a = json!({"value": 2.0, "__xy_agg__": "weighted_avg",
+ "__xy_weight_sum__": 1.0, "__xy_weighted_sum__": 2.0});
+ let index_b = json!({"value": 4.0, "__xy_agg__": "weighted_avg",
+ "__xy_weight_sum__": 3.0, "__xy_weighted_sum__": 12.0});
+ let merged = merge_metric_agg(&index_a, &index_b).expect("weighted_avg must merge");
+ assert_eq!(merged["value"].as_f64(), Some(3.5), "{merged}");
+ assert_eq!(merged["__xy_weight_sum__"].as_f64(), Some(4.0));
+ assert_eq!(merged["__xy_weighted_sum__"].as_f64(), Some(14.0));
+
+ // Zero total weight on both sides stays null, never NaN.
+ let empty = json!({"value": null, "__xy_agg__": "weighted_avg",
+ "__xy_weight_sum__": 0.0, "__xy_weighted_sum__": 0.0});
+ let merged = merge_metric_agg(&empty, &empty).expect("must merge");
+ assert_eq!(merged["value"], Value::Null);
+ }
}
fn synthetic_transform_object_ext2(
@@ -8249,6 +8297,42 @@ fn find_invalid_agg_params(aggs: Option<&Value>) -> Option<String> {
);
}
}
+ // `weighted_avg` is field-based here: ES also accepts a `script`
+ // on either side, which XERJ does not run for this agg. Refuse it
+ // rather than answering `value: null` for a valid ES request.
+ "weighted_avg" => {
+ for side in ["value", "weight"] {
+ let cfg = match params.get(side) {
+ Some(v) if v.is_object() => v,
+ _ => {
+ return Some(format!(
+ "[weighted_avg] aggregation [{name}] requires [{side}] \
+ to be an object with a [field]"
+ ))
+ }
+ };
+ if cfg.get("script").is_some() {
+ return Some(format!(
+ "[weighted_avg] aggregation [{name}] does not support [script] \
+ in [{side}]; use [field]"
+ ));
+ }
+ if cfg.get("field").and_then(Value::as_str).is_none() {
+ return Some(format!(
+ "[weighted_avg] aggregation [{name}] requires [field] in [{side}]"
+ ));
+ }
+ if cfg
+ .get("missing")
+ .is_some_and(|m| !m.is_number() && !m.is_null())
+ {
+ return Some(format!(
+ "[weighted_avg] aggregation [{name}] requires a numeric \
+ [missing] in [{side}]"
+ ));
+ }
+ }
+ }
"random_sampler" => {
if let Some(p) = params.get("probability").and_then(Value::as_f64) {
if p <= 0.0 {
@@ -8371,6 +8455,11 @@ mod agg_param_validation_tests {
// An incompatible type is fine when the request has no time_series.
json!({"c": {"composite": {"sources": [{"k": {"terms": {"field": "k"}}}]}},
"r": {"rare_terms": {"field": "k"}}}),
+ // Both sides field-based, with and without `missing`.
+ json!({"w": {"weighted_avg": {"value": {"field": "v"},
+ "weight": {"field": "w"}}}}),
+ json!({"w": {"weighted_avg": {"value": {"field": "v", "missing": 1},
+ "weight": {"field": "w", "missing": null}}}}),
] {
assert_eq!(check(aggs.clone()), None, "{aggs}");
}
@@ -8449,6 +8538,15 @@ mod agg_param_validation_tests {
(json!({"by_time": {"auto_date_histogram": {"field": "@timestamp"},
"aggs": {"ts": {"time_series": {}}}}}),
"[by_time] aggregation is incompatible with time series execution mode"),
+ // `weighted_avg` accepted these and answered `value: null`.
+ (json!({"w": {"weighted_avg": {"value": {"script": {"source": "1"}},
+ "weight": {"field": "w"}}}}),
+ "[weighted_avg] aggregation [w] does not support [script] in [value]"),
+ (json!({"w": {"weighted_avg": {"value": {"field": "v"},
+ "weight": {"field": "w", "missing": "n/a"}}}}),
+ "[weighted_avg] aggregation [w] requires a numeric [missing] in [weight]"),
+ (json!({"w": {"weighted_avg": {"value": {"field": "v"}}}}),
+ "[weighted_avg] aggregation [w] requires [weight] to be an object with a [field]"),
];
for (aggs, want) in cases {
let got = check(aggs.clone()).unwrap_or_else(|| panic!("not refused: {aggs}"));
diff --git a/engine/crates/xerj-engine/src/aggs.rs b/engine/crates/xerj-engine/src/aggs.rs
index 9cc9e9745..852aab45f 100644
--- a/engine/crates/xerj-engine/src/aggs.rs
+++ b/engine/crates/xerj-engine/src/aggs.rs
@@ -110,6 +110,7 @@ pub const SUPPORTED_AGG_TYPES: &[&str] = &[
"top_metrics",
"value_count",
"variable_width_histogram",
+ "weighted_avg",
];
// ── Field value cache ─────────────────────────────────────────────────────────
@@ -3120,6 +3121,7 @@ fn execute_agg_with_all_cached<'d>(
"string_stats" => run_string_stats(agg_params, docs),
"boxplot" => run_boxplot(agg_params, docs),
"top_metrics" => run_top_metrics(agg_params, docs),
+ "weighted_avg" => run_weighted_avg(agg_params, cache),
// nested — flatten each parent doc's nested-path array so that
// doc_count reflects the number of nested objects, and sub-aggs
// (like `terms` on `courses.name`) see one "doc" per nested entry.
@@ -6704,6 +6706,103 @@ fn run_avg<'d>(params: &Value, docs: &'d [Value], cache: &mut FieldCache<'d>) ->
json!({ "value": avg, "__xy_count__": count, "__xy_sum__": sum })
}
+/// `weighted_avg`: `sum(value × weight) / sum(weight)` over the bucket.
+///
+/// Both sides are field configs — `{ "field": ..., "missing": <number> }`.
+/// A document with no value for a side is skipped unless that side declares
+/// `missing`. A multi-valued value field contributes every value, each
+/// paired with the document's weight, so the weight enters the denominator
+/// once per value (ES-YAML `aggregations/weighted_avg.yml`, "Multi value
+/// field": `(1+2+3)*2 + (0+1+4)*4` over `3*2 + 3*4` = 16/9).
+///
+/// `sum(weights) == 0` and an empty bucket both yield `value: null`, as ES
+/// does.
+///
+/// ES rejects a multi-valued *weight* field with a 400 ("Multi weight field
+/// not allowed"). The aggregation evaluator has no error channel, so such a
+/// document is skipped here; the case stays in
+/// `tests/es-compat-yaml/catch-lenient.txt` until that channel exists.
+/// The API layer still rejects a `weighted_avg` that has no `field`, a
+/// non-numeric `missing`, or a `script` (see `find_invalid_agg_params`).
+fn run_weighted_avg<'d>(params: &Value, cache: &mut FieldCache<'d>) -> Value {
+ let (Some(value_cfg), Some(weight_cfg)) = (params.get("value"), params.get("weight")) else {
+ return weighted_avg_result(0.0, 0.0);
+ };
+ let (Some(value_field), Some(weight_field)) = (
+ value_cfg.get("field").and_then(Value::as_str),
+ weight_cfg.get("field").and_then(Value::as_str),
+ ) else {
+ return weighted_avg_result(0.0, 0.0);
+ };
+ let value_missing = get_missing_value(value_cfg);
+ let weight_missing = get_missing_value(weight_cfg);
+
+ // Both slices are indexed by document. The cache borrows mutably per
+ // lookup, so materialise the value side before asking for the weight side.
+ let values_per_doc: Vec<Vec<f64>> = cache.get_numeric_multi(value_field).to_vec();
+ let weights_per_doc = cache.get_numeric_multi(weight_field);
+
+ let mut weighted_sum = 0.0f64;
+ let mut weight_sum = 0.0f64;
+ for (values, weights) in values_per_doc.iter().zip(weights_per_doc) {
+ // A multi-valued weight is an error in ES (see the doc comment); skip
+ // the document rather than pairing every value with every weight.
+ if weights.len() > 1 {
+ continue;
+ }
+ let value_placeholder: [f64; 1];
+ let values: &[f64] = if values.is_empty() {
+ match value_missing {
+ Some(m) => {
+ value_placeholder = [m];
+ &value_placeholder
+ }
+ None => continue,
+ }
+ } else {
+ values
+ };
+ let weight_placeholder: [f64; 1];
+ let weights: &[f64] = if weights.is_empty() {
+ match weight_missing {
+ Some(m) => {
+ weight_placeholder = [m];
+ &weight_placeholder
+ }
+ None => continue,
+ }
+ } else {
+ weights
+ };
+ let weight = weights[0];
+ for value in values {
+ weighted_sum += value * weight;
+ weight_sum += weight;
+ }
+ }
+
+ weighted_avg_result(weighted_sum, weight_sum)
+}
+
+/// The response shape for `weighted_avg`.
+///
+/// The internal sums let the API combine this metric across indices
+/// (`merge_metric_agg`): averaging two already-averaged values would be wrong.
+/// `strip_internal_tracking` removes them before the response.
+fn weighted_avg_result(weighted_sum: f64, weight_sum: f64) -> Value {
+ let value = if weight_sum == 0.0 {
+ Value::Null
+ } else {
+ json!(weighted_sum / weight_sum)
+ };
+ json!({
+ "value": value,
+ "__xy_agg__": "weighted_avg",
+ "__xy_weight_sum__": weight_sum,
+ "__xy_weighted_sum__": weighted_sum,
+ })
+}
+
fn run_sum<'d>(params: &Value, docs: &'d [Value], cache: &mut FieldCache<'d>) -> Value {
let field = match params.get("field").and_then(Value::as_str) {
Some(f) => f,
@@ -14390,6 +14489,81 @@ mod tests {
);
}
+ /// FAIL-BEFORE: `weighted_avg` was accepted by the request path and fell
+ /// through to the dispatch catch-all, so the response carried
+ /// `{"error": "unsupported aggregation type 'weighted_avg'"}` inside a
+ /// 200. The ES-YAML cases only asserted `close_to`, which treats a missing
+ /// value as NaN and passes vacuously — so the suite was green while the
+ /// aggregation did nothing. These assertions are the same arithmetic the
+ /// fixture expects, computed for real.
+ #[test]
+ fn weighted_avg_matches_es_semantics() {
+ // aggregations/weighted_avg.yml "Basic test" corpus.
+ let docs = vec![
+ json!({"double_field": 1.0, "long_field": 6, "integer_field": 10,
+ "multi_value_field": [1, 2, 3], "weight": 2}),
+ json!({"double_field": 3.0, "long_field": 2,
+ "multi_value_field": [0, 1, 4], "weight": 4}),
+ json!({"double_field": 1.0, "long_field": 1}),
+ json!({"double_field": 5.0, "long_field": 3, "integer_field": 4, "weight": 3}),
+ ];
+ let close = |a: Option<f64>, b: f64| a.is_some_and(|v| (v - b).abs() < 1e-6);
+ let wa = |value: Value, weight: Value| {
+ run_aggs(
+ &json!({"w": {"weighted_avg": {"value": value, "weight": weight}}}),
+ &docs,
+ )
+ };
+
+ // (6*2 + 2*4 + 3*3) / (2+4+3); doc 3 has no weight and is skipped.
+ let r = wa(json!({"field": "long_field"}), json!({"field": "weight"}));
+ assert!(close(r["w"]["value"].as_f64(), 29.0 / 9.0), "{r}");
+
+ // (10*2 + 4*3) / (2+3); integer_field is absent on docs 2 and 3.
+ let r = wa(
+ json!({"field": "integer_field"}),
+ json!({"field": "weight"}),
+ );
+ assert!(close(r["w"]["value"].as_f64(), 6.4), "{r}");
+
+ // value.missing substitutes 2 for docs 2 and 3.
+ let r = wa(
+ json!({"field": "integer_field", "missing": 2}),
+ json!({"field": "weight"}),
+ );
+ assert!(close(r["w"]["value"].as_f64(), 40.0 / 9.0), "{r}");
+
+ // weight.missing makes doc 3 contribute (1*4); denominator 13.
+ let r = wa(
+ json!({"field": "long_field"}),
+ json!({"field": "weight", "missing": 4}),
+ );
+ assert!(close(r["w"]["value"].as_f64(), 33.0 / 13.0), "{r}");
+
+ // Multi-valued value: each value is paired with the doc weight and the
+ // weight enters the denominator once per value.
+ let r = wa(
+ json!({"field": "multi_value_field"}),
+ json!({"field": "weight"}),
+ );
+ assert!(close(r["w"]["value"].as_f64(), 32.0 / 18.0), "{r}");
+
+ // Every weight is zero (unknown field + missing 0) -> null, not NaN.
+ let r = wa(
+ json!({"field": "integer_field"}),
+ json!({"field": "unknown", "missing": 0}),
+ );
+ assert_eq!(r["w"]["value"], Value::Null, "{r}");
+
+ // Empty bucket -> null.
+ let empty = run_aggs(
+ &json!({"w": {"weighted_avg": {"value": {"field": "n"},
+ "weight": {"field": "weight"}}}}),
+ &[],
+ );
+ assert_eq!(empty["w"]["value"], Value::Null, "{empty}");
+ }
+
#[test]
fn missing_agg_counts_empty_and_null_arrays() {
// ES `missing` agg counts docs with NO value: absent, null, [] and
diff --git a/landing/docs/aggregations.html b/landing/docs/aggregations.html
index 99d60ca8b..2ea055e9d 100644
--- a/landing/docs/aggregations.html
+++ b/landing/docs/aggregations.html
@@ -256,6 +256,7 @@
<div class="item">top_hits</div>
<div class="item">top_metrics</div>
<div class="item">scripted_metric<span class="dsc">init / map / combine / reduce in Painless.</span></div>
+ <div class="item">weighted_avg<span class="dsc">Field-based value and weight; multi-valued value fields use every value.</span></div>
<div class="item">geo_bounds</div>
<div class="item">geo_centroid</div>
</div>
diff --git a/landing/docs/migration-from-es.html b/landing/docs/migration-from-es.html
index 48c09d842..d1a8b82cf 100644
--- a/landing/docs/migration-from-es.html
+++ b/landing/docs/migration-from-es.html
@@ -248,7 +248,7 @@
<li><strong>Document CRUD:</strong> <code class="inline">POST /:index/_doc</code>, <code class="inline">PUT /:index/_doc/:id</code>, <code class="inline">GET /:index/_doc/:id</code>, <code class="inline">DELETE /:index/_doc/:id</code>.</li>
<li><strong>Bulk:</strong> <code class="inline">POST /:index/_bulk</code> with index/create/update/delete actions.</li>
<li><strong>Query DSL:</strong> <!-- generated:query-type-count -->50<!-- /generated:query-type-count --> query types including match, bool, range, wildcard, phrase, span, fuzzy, and AI-native (knn, semantic, hybrid) — the full list is on <a href="/docs/queries">Query types</a>. A further <!-- generated:rejected-query-type-count -->2<!-- /generated:rejected-query-type-count --> are recognised and <em>deliberately</em> refused with a 400 (<code class="inline">has_child</code>, <code class="inline">has_parent</code>): XERJ never materialises a parent/child join, so running them would match against flat documents and return silently wrong hits.</li>
- <li><strong>Aggregations:</strong> <!-- generated:agg-type-count -->62<!-- /generated:agg-type-count --> aggregations across the metric, bucket, sampling, scope, geo <em>and pipeline</em> families — <code class="inline">bucket_script</code>, <code class="inline">derivative</code>, <code class="inline">moving_fn</code> and the rest of the pipeline family included. Full list on <a href="/docs/aggregations">Aggregations</a>.</li>
+ <li><strong>Aggregations:</strong> <!-- generated:agg-type-count -->63<!-- /generated:agg-type-count --> aggregations across the metric, bucket, sampling, scope, geo <em>and pipeline</em> families — <code class="inline">bucket_script</code>, <code class="inline">derivative</code>, <code class="inline">moving_fn</code> and the rest of the pipeline family included. Full list on <a href="/docs/aggregations">Aggregations</a>.</li>
<li><strong>Cluster endpoints:</strong> <code class="inline">GET /_cluster/health</code>, <code class="inline">GET /_cat/indices</code>.</li>
<li><strong>Delete by query:</strong> <code class="inline">POST /:index/_delete_by_query</code>.</li>
</ul>
diff --git a/landing/llms-full.txt b/landing/llms-full.txt
index 9c0109956..5dc570a58 100644
--- a/landing/llms-full.txt
+++ b/landing/llms-full.txt
@@ -1196,7 +1196,8 @@ default `tdigest` path sorts every value and interpolates instead:
Metric `avg`, `sum`, `min`, `max`, `stats`, `extended_stats`, `value_count`,
`cardinality`, `percentiles`, `percentile_ranks`,
`median_absolute_deviation`, `matrix_stats`, `string_stats`,
- `boxplot`, `top_metrics`, `top_hits`, `scripted_metric`
+ `boxplot`, `top_metrics`, `top_hits`, `scripted_metric`,
+ `weighted_avg`
Bucket `terms`, `multi_terms`, `rare_terms`, `significant_terms`,
`significant_text`, `range`, `date_range`, `ip_range`, `ip_prefix`,
`histogram`, `variable_width_histogram`, `date_histogram`,