Skip to main content

nmbrs_runtime/wrappers/
traverse.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Default result-traversal wrapper. Always wraps the inner
5//! adapter dispenser: counts result elements + bytes, walks
6//! declared capture points, and writes extracted values onto
7//! the per-fiber op-template kernel via `ctx.wires.write`.
8
9use std::collections::HashMap;
10use std::sync::Arc;
11
12use crate::adapter::WrappingDispenser;
13use crate::adapter::{ExecutionError, OpDispenser, OpResult};
14use crate::wrapper_registry::{WrapperName, WrapperRegistration, WrapperSubject};
15use nmbrs_workload::bindpoints;
16
17/// SRD-32a wrapper name. Innermost layer; always present.
18pub const NAME: WrapperName = WrapperName::new("traverse");
19
20/// Trigger: always — every op gets a traversal layer so result
21/// bodies are consumed (and per-row metrics record element /
22/// byte counts) even if the workload didn't ask for anything.
23fn triggers(s: WrapperSubject) -> bool {
24    s.op().is_some()
25}
26
27/// No per-op assignment text — the wrapper has no operator-
28/// configurable knobs.
29fn describe_assignment(_: WrapperSubject) -> Option<String> {
30    None
31}
32
33inventory::submit! {
34    WrapperRegistration {
35        name: NAME,
36        owned_fields: &[],
37        triggers,
38        requires_inner: &[],
39        forbids_outer: &[],
40        mutually_exclusive_with: &[],
41        describe_assignment,
42        levels: &[crate::wrapper_registry::WrapperLevel::Op],
43    }
44}
45
46/// Result traversal statistics, backed by activity metrics counters.
47pub struct TraversalStats {
48    pub metrics: Arc<crate::activity::ActivityMetrics>,
49}
50
51/// Wraps an inner OpDispenser with result traversal and optional
52/// capture extraction.
53///
54/// This is the default wrapper, always applied unless disabled.
55/// It ensures that:
56/// 1. The result body is fully consumed (element/byte counting)
57/// 2. Captures are extracted from the result (if declared)
58/// 3. Traversal metrics are recorded
59pub struct TraversingDispenser {
60    inner: Arc<dyn OpDispenser>,
61    stats: Arc<TraversalStats>,
62    /// Capture points parsed from the template at init time.
63    /// Empty if no captures are declared.
64    captures: Vec<bindpoints::CapturePoint>,
65    /// The op's `traverse:` block, if it declared one. Absent means defaults —
66    /// the layer is always installed, so this only tunes it.
67    spec: Option<nmbrs_workload::model::TraverseSpec>,
68}
69
70impl TraversingDispenser {
71    /// Wrap an inner dispenser with traversal.
72    ///
73    /// Reads `template.captures` (the parse-time-extracted capture
74    /// specs) directly. The op-template parser has already stripped
75    /// `[name]` / `[@name]` brackets from the op text fields, so
76    /// adapters see clean SQL/URL/body strings.
77    pub fn wrap(
78        inner: Arc<dyn OpDispenser>,
79        template: &nmbrs_workload::model::ParsedOp,
80        stats: Arc<TraversalStats>,
81    ) -> Arc<dyn OpDispenser> {
82        Arc::new(Self {
83            inner,
84            stats,
85            captures: template.captures.clone(),
86            spec: template.traverse.clone(),
87        })
88    }
89}
90
91/// Extract captures from a result body's JSON.
92///
93/// Walks each declared capture spec against the body. Two modes:
94///
95/// - **Single** (`[name]`): take the first matching value. For an
96///   array-of-rows body shape (CQL's standard JSON form), reads
97///   row[0].name. For an object body, reads top-level `name`. For
98///   wildcard `*`, captures every top-level field.
99/// - **Slurp** (`[@name]`): walks every row of an array-of-rows
100///   body and collects each row's column into a single
101///   `Value::Json(array)`. Object bodies produce a single-element
102///   list. This is the convenient shape for downstream consumers
103///   that need all per-row values as a list (e.g. recall
104///   evaluator's `actual:` reads).
105///
106/// The body's `.to_json()` form is the source of truth — adapters
107/// that produce typed-row data render to a JSON array of row
108/// objects.
109#[cfg(test)]
110fn extract_captures_from_json(
111    body: &dyn crate::adapter::ResultBody,
112    specs: &[bindpoints::CapturePoint],
113) -> HashMap<String, polydat::ast::Value> {
114    extract_captures_rooted(body, specs, None)
115}
116
117/// As [`extract_captures_from_json`], with an optional `traverse.path:` base
118/// pointer applied to the body FIRST.
119///
120/// Re-roots the document rather than prefixing each capture: every capture
121/// then addresses relative to the base, which is the whole point of the knob
122/// (`{value, status, …}` envelopes force the same prefix onto every capture).
123/// A base that does not resolve yields no captures at all — the caller's
124/// `on_missing` policy decides whether that is worth saying out loud.
125fn extract_captures_rooted(
126    body: &dyn crate::adapter::ResultBody,
127    specs: &[bindpoints::CapturePoint],
128    base: Option<&str>,
129) -> HashMap<String, polydat::ast::Value> {
130    if specs.is_empty() {
131        return HashMap::new();
132    }
133    let full = body.to_json();
134    let json = match base.filter(|b| !b.is_empty()) {
135        None => full,
136        Some(b) => match full.pointer(b) {
137            Some(sub) => sub.clone(),
138            None => return HashMap::new(),
139        },
140    };
141    let mut captures = HashMap::new();
142    for spec in specs {
143        // Declarative `capture:` block form: JSON-Pointer path
144        // takes precedence over the bracket-source-name path.
145        // Lets a workload address Jolokia bulk-POST responses
146        // (`[{value:N}, {value:[...]}, {value:K}]`) by index +
147        // nested field without re-shaping the response.
148        if let Some(path) = spec.path.as_deref() {
149            let sub = json.pointer(path);
150            let value = if spec.count {
151                polydat::ast::Value::U64(count_of_subtree(sub))
152            } else if let Some(agg) = &spec.agg {
153                aggregate_rows(sub, agg, spec.row_filter.as_ref())
154            } else {
155                match sub {
156                    Some(v) => json_subtree_to_value(v),
157                    None => polydat::ast::Value::None,
158                }
159            };
160            captures.insert(spec.as_name.clone(), value);
161            continue;
162        }
163        if spec.slurp {
164            // Slurp form: collect across all rows.
165            let collected = slurp_column(&json, &spec.source_name);
166            captures.insert(
167                spec.as_name.clone(),
168                polydat::ast::Value::Json(std::sync::Arc::new(serde_json::Value::Array(collected))),
169            );
170            continue;
171        }
172        // Single form.
173        if spec.source_name == "*" {
174            // Wildcard: capture every top-level field. Falls
175            // through to scalar-form per field.
176            let target = match &json {
177                serde_json::Value::Array(rows) => {
178                    rows.first().cloned().unwrap_or(serde_json::Value::Null)
179                }
180                other => other.clone(),
181            };
182            if let serde_json::Value::Object(map) = target {
183                for (k, v) in map {
184                    captures.insert(k, json_to_value(&v));
185                }
186            }
187            continue;
188        }
189        if let Some(val) = first_row_field(&json, &spec.source_name) {
190            captures.insert(spec.as_name.clone(), json_to_value(&val));
191        }
192    }
193    captures
194}
195
196/// Reduce an addressed JSON sub-tree to a u64 count:
197/// array → length, object → key count, scalar → 1 (non-empty)
198/// or 0 (false / empty string / zero number), null / missing →
199/// 0. Use cases: `capture: { active_count: "/value:count" }`
200/// reduces a list-of-running-jobs to a numeric gauge in one
201/// step.
202fn count_of_subtree(v: Option<&serde_json::Value>) -> u64 {
203    let Some(v) = v else { return 0 };
204    match v {
205        serde_json::Value::Array(a) => a.len() as u64,
206        serde_json::Value::Object(m) => m.len() as u64,
207        serde_json::Value::Number(n) => n
208            .as_u64()
209            .or_else(|| n.as_i64().map(|i| i.max(0) as u64))
210            .or_else(|| n.as_f64().map(|f| f.max(0.0) as u64))
211            .unwrap_or(0),
212        serde_json::Value::Bool(b) => {
213            if *b {
214                1
215            } else {
216                0
217            }
218        }
219        serde_json::Value::String(s) if s.is_empty() => 0,
220        serde_json::Value::String(_) => 1,
221        serde_json::Value::Null => 0,
222    }
223}
224
225/// Project a JSON sub-tree into a Polydat [`Value`]. Scalars go
226/// through [`json_to_value`]'s typed coercion; structural
227/// shapes (array / object) are kept as `Value::Json` so the
228/// kernel can carry the original shape without lossy
229/// stringification.
230/// Folds one numeric field across the rows of an addressed array
231/// (`:min(f)` / `:max(f)` / `:sum(f)` capture aggregation). Rows
232/// missing the field, and non-numeric values, are skipped; an
233/// empty fold yields `Value::None` (renders like a missing
234/// capture). Sum stays integral (`U64`) while every contributing
235/// value is a non-negative integer, else widens to `F64`; min/max
236/// return the winning row's value with its original JSON type.
237/// The capture values an op should publish when it SUCCEEDED but returned no
238/// body at all — an empty CQL result set, an HTTP 204, an accepted timeout.
239///
240/// Skipping the write (the original behaviour) leaves every capture holding
241/// its PREVIOUS value, so a wire that is being watched for "went to zero" can
242/// never read zero once it has been nonzero. That pinned a compaction drain's
243/// task count above zero permanently and hung the poll: cqlsh showed an empty
244/// table while the workload's wire still read the last nonzero count.
245///
246/// An empty measurement is a measurement, and every fold is a commutative
247/// monoid — the empty fold publishes the monoid's identity, TOTALLY:
248///
249/// - `count` / `sum` — the identity is mathematically forced: **0**.
250/// - `min` / `max` — over an unbounded domain the identity is an extreme
251///   (⊤ / ⊥) that would poison displays and metric series; the AUTHOR's
252///   identity is the wire's own declared initial value. These return
253///   `Value::None` here as a *reset marker*, and [`publish_capture`]
254///   translates it into `wires.reset(name)` — the wire returns to its
255///   declared unit instead of holding a raw `None` that every downstream
256///   consumer would have to be None-aware of.
257///
258/// Folding any later real observation into a reset wire behaves as folding
259/// into the unit — the monoid law the drain polls and the SRD-93 pressure
260/// servo both lean on.
261fn captures_for_empty_result(
262    specs: &[bindpoints::CapturePoint],
263) -> std::collections::HashMap<String, polydat::ast::Value> {
264    use bindpoints::CaptureAgg;
265    let mut out = std::collections::HashMap::new();
266    for spec in specs {
267        let value = if spec.count {
268            polydat::ast::Value::U64(0)
269        } else {
270            match &spec.agg {
271                Some(CaptureAgg::Sum(_)) => polydat::ast::Value::U64(0),
272                Some(CaptureAgg::Min(_)) | Some(CaptureAgg::Max(_)) => polydat::ast::Value::None,
273                None => polydat::ast::Value::None,
274            }
275        };
276        out.insert(spec.as_name.clone(), value);
277    }
278    out
279}
280
281/// The single capture-publish chokepoint: a real value writes; the
282/// `Value::None` reset marker (an empty min/max fold, or a plain capture
283/// that resolved to nothing) RESTORES the wire to its declared initial
284/// value. No path parks a raw `None` on a typed wire.
285fn publish_capture(ctx: &crate::adapter::ExecCtx<'_>, name: &str, value: polydat::ast::Value) {
286    if matches!(value, polydat::ast::Value::None) {
287        let _ = ctx.wires.reset(name);
288    } else {
289        let _ = ctx.wires.write(name, value);
290    }
291}
292
293fn aggregate_rows(
294    sub: Option<&serde_json::Value>,
295    agg: &bindpoints::CaptureAgg,
296    row_filter: Option<&(String, String)>,
297) -> polydat::ast::Value {
298    use bindpoints::CaptureAgg;
299    let rows = match sub {
300        Some(serde_json::Value::Array(rows)) => rows,
301        _ => return polydat::ast::Value::None,
302    };
303    let field = match agg {
304        CaptureAgg::Min(f) | CaptureAgg::Max(f) | CaptureAgg::Sum(f) => f.as_str(),
305    };
306    // `where <field>='<value>'` — drop rows that are not commensurable before
307    // folding. A result set can mix them: `system_views.sstable_tasks` lists a
308    // data compaction in `unit=bytes` beside an index build in
309    // `unit=token range parts`, and summing across both adds unlike
310    // quantities. Compared as strings so it works on any scalar column
311    // without the capture layer needing the column's type.
312    let keep = |row: &serde_json::Value| -> bool {
313        let Some((k, want)) = row_filter else {
314            return true;
315        };
316        match row.get(k.as_str()) {
317            Some(serde_json::Value::String(s)) => s == want,
318            Some(other) => other.to_string().trim_matches('"') == want,
319            None => false,
320        }
321    };
322    let nums: Vec<&serde_json::Number> = rows
323        .iter()
324        .filter(|row| keep(row))
325        .filter_map(|row| row.get(field))
326        .filter_map(|v| v.as_number())
327        .collect();
328    if nums.is_empty() {
329        // Same totality contract as `captures_for_empty_result`, applied to
330        // the rows-present-but-none-match case — the two empty paths used to
331        // disagree (`:sum` gave 0 with no body but None past a `where` that
332        // matched nothing), and a `None` parked on a typed wire forced every
333        // downstream consumer to be None-aware. `sum` publishes its forced
334        // identity 0; `min`/`max` return the `None` RESET MARKER, which
335        // `publish_capture` turns into a reset to the wire's declared
336        // initial value (the author's identity element).
337        return match agg {
338            CaptureAgg::Sum(_) => polydat::ast::Value::U64(0),
339            CaptureAgg::Min(_) | CaptureAgg::Max(_) => polydat::ast::Value::None,
340        };
341    }
342    match agg {
343        CaptureAgg::Sum(_) => {
344            if nums.iter().all(|n| n.as_u64().is_some()) {
345                polydat::ast::Value::U64(nums.iter().map(|n| n.as_u64().unwrap()).sum())
346            } else {
347                polydat::ast::Value::F64(nums.iter().filter_map(|n| n.as_f64()).sum())
348            }
349        }
350        CaptureAgg::Min(_) | CaptureAgg::Max(_) => {
351            let want_min = matches!(agg, CaptureAgg::Min(_));
352            let mut best = nums[0];
353            for n in &nums[1..] {
354                let (a, b) = (
355                    n.as_f64().unwrap_or(f64::NAN),
356                    best.as_f64().unwrap_or(f64::NAN),
357                );
358                if (want_min && a < b) || (!want_min && a > b) {
359                    best = n;
360                }
361            }
362            json_to_value(&serde_json::Value::Number((*best).clone()))
363        }
364    }
365}
366
367fn json_subtree_to_value(v: &serde_json::Value) -> polydat::ast::Value {
368    match v {
369        serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
370            polydat::ast::Value::Json(std::sync::Arc::new(v.clone()))
371        }
372        scalar => json_to_value(scalar),
373    }
374}
375
376/// First-row lookup: for an array body, read `rows[0].name`; for
377/// an object body, read `obj.name`. Returns `None` when the field
378/// isn't present.
379fn first_row_field(json: &serde_json::Value, name: &str) -> Option<serde_json::Value> {
380    match json {
381        serde_json::Value::Array(rows) => rows.first().and_then(|row| row.get(name)).cloned(),
382        serde_json::Value::Object(_) => json.get(name).cloned(),
383        _ => None,
384    }
385}
386
387/// Slurp helper: walk an array body and collect each row's `name`
388/// field. Object bodies produce a single-element list. Non-object,
389/// non-array bodies produce an empty list.
390fn slurp_column(json: &serde_json::Value, name: &str) -> Vec<serde_json::Value> {
391    match json {
392        serde_json::Value::Array(rows) => rows
393            .iter()
394            .filter_map(|row| row.get(name).cloned())
395            .collect(),
396        serde_json::Value::Object(_) => json.get(name).map(|v| vec![v.clone()]).unwrap_or_default(),
397        _ => Vec::new(),
398    }
399}
400
401/// Convert a serde_json::Value to a Polydat Value. JSON `null`
402/// maps to [`Value::None`] (per SRD-74 — None propagates
403/// rather than coercing to the string `"null"`); arrays and
404/// objects stringify only when reached via the row-shape
405/// extraction path (the JSON-Pointer extraction route uses
406/// [`json_subtree_to_value`] which preserves them as
407/// `Value::Json`).
408pub(crate) fn json_to_value(v: &serde_json::Value) -> polydat::ast::Value {
409    match v {
410        serde_json::Value::Null => polydat::ast::Value::None,
411        serde_json::Value::Number(n) => {
412            if let Some(i) = n.as_u64() {
413                polydat::ast::Value::U64(i)
414            } else if let Some(f) = n.as_f64() {
415                polydat::ast::Value::F64(f)
416            } else {
417                polydat::ast::Value::Str(n.to_string().into())
418            }
419        }
420        serde_json::Value::Bool(b) => polydat::ast::Value::Bool(*b),
421        serde_json::Value::String(s) => polydat::ast::Value::Str(s.as_str().into()),
422        other => polydat::ast::Value::Str(other.to_string().into()),
423    }
424}
425
426impl WrappingDispenser for TraversingDispenser {}
427
428impl OpDispenser for TraversingDispenser {
429    fn execute<'a>(
430        &'a self,
431        cycle: u64,
432        ctx: &'a crate::fixture::ExecCtx<'a>,
433    ) -> std::pin::Pin<
434        Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
435    > {
436        Box::pin(async move {
437            // Execute the inner dispenser
438            let result = self.inner.execute(cycle, ctx).await?;
439
440            // Traverse: count elements and bytes
441            if let Some(body) = &result.body {
442                self.stats
443                    .metrics
444                    .result_elements
445                    .inc_by(body.element_count());
446                if let Some(bytes) = body.byte_count() {
447                    self.stats.metrics.result_bytes.inc_by(bytes);
448                }
449            }
450
451            // Extract captures from result if declared. Values land
452            // on the per-fiber kernel's input slot via ctx.wires.write;
453            // wrappers above this layer (e.g. MetricsDispenser) see
454            // them through wires.get on the same cycle.
455            // A SUCCEEDING op that returned no body still measured something:
456            // zero rows. Publish the identity values rather than skipping the
457            // write, or every capture silently keeps its previous reading and a
458            // "wait for it to reach zero" poll can never succeed.
459            if !self.captures.is_empty() && result.body.is_none() {
460                for (name, value) in captures_for_empty_result(&self.captures) {
461                    publish_capture(ctx, &name, value);
462                }
463            }
464            if !self.captures.is_empty()
465                && let Some(body) = &result.body
466            {
467                let base = self.spec.as_ref().and_then(|s| s.path.as_deref());
468                let extracted = extract_captures_rooted(body.as_ref(), &self.captures, base);
469                // `on_missing:` — a capture that resolved to nothing reads
470                // exactly like one that measured an absence, which is how a
471                // renamed column or a changed schema hides. Default stays
472                // `ignore` so existing workloads are unaffected.
473                let policy = self.spec.as_ref().map(|s| s.on_missing).unwrap_or_default();
474                if !matches!(policy, nmbrs_workload::model::OnMissing::Ignore) {
475                    for cp in &self.captures {
476                        let missing = match extracted.get(&cp.as_name) {
477                            None => true,
478                            Some(polydat::ast::Value::None) => true,
479                            Some(_) => false,
480                        };
481                        if !missing {
482                            continue;
483                        }
484                        let detail = format!(
485                            "op capture '{}' resolved to nothing{}",
486                            cp.as_name,
487                            match base {
488                                Some(b) => format!(" (traverse path '{b}')"),
489                                None => String::new(),
490                            }
491                        );
492                        match policy {
493                            nmbrs_workload::model::OnMissing::Warn => {
494                                crate::diag!(crate::observer::LogLevel::Warn, "{detail}")
495                            }
496                            nmbrs_workload::model::OnMissing::Error => {
497                                return Err(ExecutionError::Op(crate::adapter::AdapterError {
498                                    error_name: "capture_missing".into(),
499                                    message: detail,
500                                    retryable: false,
501                                }));
502                            }
503                            nmbrs_workload::model::OnMissing::Ignore => {}
504                        }
505                    }
506                }
507                for (name, value) in extracted {
508                    publish_capture(ctx, &name, value);
509                }
510            }
511
512            Ok(result)
513        })
514    }
515    fn inner_dispenser(&self) -> Option<&dyn OpDispenser> {
516        Some(self.inner.as_ref())
517    }
518}
519
520#[cfg(test)]
521mod tests {
522    use super::*;
523    use crate::adapter::ResultBody;
524
525    fn agg_cap(
526        alias: &str,
527        agg: Option<bindpoints::CaptureAgg>,
528        count: bool,
529    ) -> bindpoints::CapturePoint {
530        bindpoints::CapturePoint {
531            row_filter: None,
532            source_name: alias.into(),
533            as_name: alias.into(),
534            cast_type: None,
535            slurp: false,
536            path: Some(String::new()),
537            count,
538            agg,
539        }
540    }
541
542    /// An op that SUCCEEDS with no body measured zero rows, and must publish
543    /// that. Skipping the write leaves every capture holding its previous
544    /// reading, so a wire watched for "went to zero" can never reach zero once
545    /// it has been nonzero — which pinned a compaction drain's task count above
546    /// zero permanently and hung its poll for 275s+ against a 48h timeout,
547    /// while cqlsh showed the table empty.
548    #[test]
549    fn empty_result_publishes_identity_for_count_and_sum() {
550        let specs = vec![
551            agg_cap("n", None, true),
552            agg_cap("s", Some(bindpoints::CaptureAgg::Sum("x".into())), false),
553        ];
554        let out = super::captures_for_empty_result(&specs);
555        assert!(
556            matches!(out.get("n"), Some(polydat::ast::Value::U64(0))),
557            "counting nothing is 0, not 'leave the old count': {:?}",
558            out.get("n")
559        );
560        assert!(
561            matches!(out.get("s"), Some(polydat::ast::Value::U64(0))),
562            "summing nothing is 0: {:?}",
563            out.get("s")
564        );
565    }
566
567    /// min/max of nothing has NO honest value, so they publish None — which
568    /// clears the wire rather than leaving a stale reading that is
569    /// indistinguishable from a real observation. Writing 0 would be a lie:
570    /// zero is a plausible minimum.
571    #[test]
572    fn empty_result_clears_min_and_max_rather_than_inventing_a_value() {
573        let specs = vec![
574            agg_cap("lo", Some(bindpoints::CaptureAgg::Min("x".into())), false),
575            agg_cap("hi", Some(bindpoints::CaptureAgg::Max("x".into())), false),
576        ];
577        let out = super::captures_for_empty_result(&specs);
578        assert!(
579            matches!(out.get("lo"), Some(polydat::ast::Value::None)),
580            "min of nothing must not invent 0: {:?}",
581            out.get("lo")
582        );
583        assert!(
584            matches!(out.get("hi"), Some(polydat::ast::Value::None)),
585            "max of nothing must not invent 0: {:?}",
586            out.get("hi")
587        );
588    }
589
590    /// A plain (non-aggregate) capture over an empty result is simply absent.
591    #[test]
592    fn empty_result_leaves_plain_captures_absent() {
593        let specs = vec![agg_cap("v", None, false)];
594        let out = super::captures_for_empty_result(&specs);
595        assert!(matches!(out.get("v"), Some(polydat::ast::Value::None)));
596    }
597
598    /// Rows that EXIST but match nothing stay `None`, deliberately — a
599    /// different statement from "there was no result at all", and the
600    /// pre-existing rule (`aggregate_filter_matching_no_rows_yields_none`).
601    /// That case was never the staleness bug: this value IS written to the
602    /// wire, so it clears. Only the no-body path skipped the write.
603    #[test]
604    fn empty_fold_totality_sum_is_zero_min_max_are_reset_markers() {
605        // The monoid contract (SRD-93-era fold totality): sum-of-nothing
606        // publishes its forced identity 0; min/max-of-nothing return the
607        // `None` RESET MARKER that `publish_capture` translates into a
608        // reset to the wire's declared initial value — no path parks a
609        // raw None on a typed wire, and no path leaves a stale reading.
610        let rows = serde_json::json!([{"other": 1}, {"other": 2}]);
611        let v = super::aggregate_rows(
612            Some(&rows),
613            &bindpoints::CaptureAgg::Sum("missing".into()),
614            None,
615        );
616        assert!(
617            matches!(v, polydat::ast::Value::U64(0)),
618            "sum-of-nothing is its identity 0: {v:?}"
619        );
620        for agg in [
621            bindpoints::CaptureAgg::Min("missing".into()),
622            bindpoints::CaptureAgg::Max("missing".into()),
623        ] {
624            let v = super::aggregate_rows(Some(&rows), &agg, None);
625            assert!(
626                matches!(v, polydat::ast::Value::None),
627                "min/max-of-nothing is the reset marker: {v:?}"
628            );
629        }
630    }
631
632    fn cap(source: &str, alias: &str, slurp: bool) -> bindpoints::CapturePoint {
633        bindpoints::CapturePoint {
634            row_filter: None,
635            source_name: source.into(),
636            as_name: alias.into(),
637            cast_type: None,
638            slurp,
639            path: None,
640            count: false,
641            agg: None,
642        }
643    }
644
645    #[test]
646    fn parse_captures_from_template() {
647        let parsed =
648            bindpoints::parse_capture_points("SELECT [username], [age as user_age] FROM users");
649        assert_eq!(parsed.captures.len(), 2);
650        assert_eq!(parsed.captures[0].source_name, "username");
651        assert_eq!(parsed.captures[0].as_name, "username");
652        assert!(!parsed.captures[0].slurp);
653        assert_eq!(parsed.captures[1].source_name, "age");
654        assert_eq!(parsed.captures[1].as_name, "user_age");
655        assert_eq!(parsed.raw_template, "SELECT username, age FROM users");
656    }
657
658    #[test]
659    fn parse_slurp_capture() {
660        let parsed = bindpoints::parse_capture_points("SELECT [@keys] FROM t");
661        assert_eq!(parsed.captures.len(), 1);
662        assert_eq!(parsed.captures[0].source_name, "keys");
663        assert!(parsed.captures[0].slurp);
664        assert_eq!(parsed.raw_template, "SELECT keys FROM t");
665    }
666
667    #[derive(Debug)]
668    struct JsonBody(serde_json::Value);
669    impl ResultBody for JsonBody {
670        fn to_json(&self) -> serde_json::Value {
671            self.0.clone()
672        }
673        fn as_any(&self) -> &dyn std::any::Any {
674            self
675        }
676    }
677
678    #[test]
679    fn extract_from_json_top_level() {
680        let body = JsonBody(serde_json::json!({
681            "user_id": 42,
682            "name": "alice",
683            "balance": 99.5
684        }));
685        let specs = vec![cap("user_id", "uid", false), cap("name", "name", false)];
686        let captures = extract_captures_from_json(&body, &specs);
687        assert_eq!(captures.len(), 2);
688        assert_eq!(captures["uid"].as_u64(), 42);
689        match &captures["name"] {
690            polydat::ast::Value::Str(s) => assert_eq!(&**s, "alice"),
691            other => panic!("expected Str, got {other:?}"),
692        }
693    }
694
695    #[test]
696    fn extract_wildcard() {
697        let body = JsonBody(serde_json::json!({"a": 1, "b": 2}));
698        let specs = vec![cap("*", "*", false)];
699        let captures = extract_captures_from_json(&body, &specs);
700        assert_eq!(captures.len(), 2);
701    }
702
703    #[test]
704    fn extract_slurp_array_of_rows() {
705        let body = JsonBody(serde_json::json!([
706            {"key": 4, "value": 0.5},
707            {"key": 17, "value": 0.4},
708            {"key": 42, "value": 0.3},
709        ]));
710        let specs = vec![cap("key", "key", true)];
711        let captures = extract_captures_from_json(&body, &specs);
712        assert_eq!(captures.len(), 1);
713        match &captures["key"] {
714            polydat::ast::Value::Json(arc) => {
715                let serde_json::Value::Array(items) = arc.as_ref() else {
716                    panic!("expected Value::Json(array), got {arc:?}");
717                };
718                assert_eq!(items.len(), 3);
719                assert_eq!(items[0], serde_json::json!(4));
720                assert_eq!(items[1], serde_json::json!(17));
721                assert_eq!(items[2], serde_json::json!(42));
722            }
723            other => panic!("expected Value::Json(array), got {other:?}"),
724        }
725    }
726
727    #[test]
728    fn extract_single_first_row_of_array() {
729        let body = JsonBody(serde_json::json!([
730            {"key": 4}, {"key": 17}, {"key": 42},
731        ]));
732        let specs = vec![cap("key", "first_key", false)];
733        let captures = extract_captures_from_json(&body, &specs);
734        assert_eq!(captures.len(), 1);
735        assert_eq!(captures["first_key"].as_u64(), 4);
736    }
737
738    fn cap_path(name: &str, path: &str, count: bool) -> bindpoints::CapturePoint {
739        bindpoints::CapturePoint {
740            source_name: name.into(),
741            as_name: name.into(),
742            cast_type: None,
743            slurp: false,
744            path: Some(path.into()),
745            count,
746            agg: None,
747            row_filter: None,
748        }
749    }
750
751    /// `traverse.path:` re-roots the body, so a capture addresses relative to
752    /// it instead of repeating the envelope prefix on every line.
753    #[test]
754    fn traverse_path_re_roots_the_document() {
755        let body = JsonBody(serde_json::json!({
756            "status": 200,
757            "value": [{"progress": 7u64}],
758        }));
759        let spec = |name: &str, path: &str| bindpoints::CapturePoint {
760            source_name: name.into(),
761            as_name: name.into(),
762            cast_type: None,
763            slurp: false,
764            path: Some(path.to_string()),
765            count: false,
766            agg: None,
767            row_filter: None,
768        };
769        // Without the base, the capture must carry the whole prefix.
770        let long = extract_captures_rooted(&body, &[spec("p", "/value/0/progress")], None);
771        assert_eq!(long["p"].as_u64(), 7);
772
773        // With it, the same value is addressed relative to `/value`.
774        let short = extract_captures_rooted(&body, &[spec("p", "/0/progress")], Some("/value"));
775        assert_eq!(short["p"].as_u64(), 7);
776    }
777
778    /// A base path that does not resolve yields no captures — the caller's
779    /// `on_missing` decides whether that is worth saying out loud.
780    #[test]
781    fn an_unresolvable_traverse_path_yields_nothing() {
782        let body = JsonBody(serde_json::json!({"value": 1}));
783        let spec = bindpoints::CapturePoint {
784            source_name: "x".into(),
785            as_name: "x".into(),
786            cast_type: None,
787            slurp: false,
788            path: Some("/x".into()),
789            count: false,
790            agg: None,
791            row_filter: None,
792        };
793        let caps = extract_captures_rooted(&body, &[spec], Some("/nonesuch"));
794        assert!(caps.is_empty(), "unresolvable base must not invent values");
795    }
796
797    /// The same shape, folded PER KIND. Summing across the two rows adds
798    /// bytes to token range parts — dimensionally meaningless, and its
799    /// magnitude depends on how many tasks were registered at sample time.
800    /// `where kind='…'` keeps each fold to one unit.
801    #[test]
802    fn aggregate_captures_filter_rows_by_kind() {
803        let body = JsonBody(serde_json::json!([
804            {"kind": "compaction",            "progress": 47048035855u64},
805            {"kind": "secondary index build", "progress": 4855601u64},
806        ]));
807        fn cap_filtered(
808            name: &str,
809            field: &str,
810            filter: Option<(&str, &str)>,
811        ) -> bindpoints::CapturePoint {
812            bindpoints::CapturePoint {
813                source_name: name.into(),
814                as_name: name.into(),
815                cast_type: None,
816                slurp: false,
817                path: Some(String::new()),
818                count: false,
819                agg: Some(bindpoints::CaptureAgg::Sum(field.into())),
820                row_filter: filter.map(|(k, v)| (k.to_string(), v.to_string())),
821            }
822        }
823        let specs = vec![
824            cap_filtered("all", "progress", None),
825            cap_filtered("index", "progress", Some(("kind", "secondary index build"))),
826            cap_filtered("data", "progress", Some(("kind", "compaction"))),
827        ];
828        let caps = extract_captures_from_json(&body, &specs);
829        let num = |k: &str| caps[k].as_u64();
830        assert_eq!(num("index"), 4_855_601, "index build only");
831        assert_eq!(num("data"), 47_048_035_855, "data compaction only");
832        // The unfiltered fold is the sum of unlike quantities — kept as the
833        // record of what the old capture actually produced.
834        assert_eq!(num("all"), num("index") + num("data"));
835    }
836
837    /// A predicate that matches nothing folds to absent, not to zero — zero
838    /// would read as "measured, and it was none".
839    #[test]
840    fn aggregate_filter_matching_no_rows_folds_to_sum_identity() {
841        let body = JsonBody(serde_json::json!([
842            {"kind": "compaction", "progress": 5u64},
843        ]));
844        let specs = vec![bindpoints::CapturePoint {
845            source_name: "x".into(),
846            as_name: "x".into(),
847            cast_type: None,
848            slurp: false,
849            path: Some(String::new()),
850            count: false,
851            agg: Some(bindpoints::CaptureAgg::Sum("progress".into())),
852            row_filter: Some(("kind".into(), "nonesuch".into())),
853        }];
854        let caps = extract_captures_from_json(&body, &specs);
855        // Fold totality: a `where` that matches nothing sums to the
856        // identity 0 — the same statement the no-body path makes, where
857        // the two paths used to disagree (0 vs a stale-prone None).
858        assert!(
859            matches!(caps["x"], polydat::ast::Value::U64(0)),
860            "a filtered-empty sum folds to its identity 0; got {:?}",
861            caps["x"]
862        );
863    }
864
865    #[test]
866    fn aggregate_captures_fold_rows_with_mixed_units() {
867        // The sstable_tasks shape that motivated aggregation: a
868        // byte-denominated task saturated at 1.0 alongside an
869        // ordinal-denominated task mid-flight. min(ratio) must
870        // surface the merge's 0.4, not row 0's 1.0.
871        let body = JsonBody(serde_json::json!([
872            {"completion_ratio": 1.0, "progress": 31357891323u64, "total": 31357891323u64},
873            {"completion_ratio": 0.4, "progress": 8000000u64,     "total": 20000000u64},
874        ]));
875        fn cap_agg(name: &str, agg: bindpoints::CaptureAgg) -> bindpoints::CapturePoint {
876            bindpoints::CapturePoint {
877                source_name: name.into(),
878                as_name: name.into(),
879                cast_type: None,
880                slurp: false,
881                path: Some(String::new()),
882                count: false,
883                agg: Some(agg),
884                row_filter: None,
885            }
886        }
887        let specs = vec![
888            cap_agg(
889                "completion_ratio",
890                bindpoints::CaptureAgg::Min("completion_ratio".into()),
891            ),
892            cap_agg(
893                "max_ratio",
894                bindpoints::CaptureAgg::Max("completion_ratio".into()),
895            ),
896            cap_agg("progress", bindpoints::CaptureAgg::Sum("progress".into())),
897        ];
898        let captures = extract_captures_from_json(&body, &specs);
899        assert_eq!(captures["completion_ratio"].as_f64(), 0.4);
900        assert_eq!(captures["max_ratio"].as_f64(), 1.0);
901        assert_eq!(captures["progress"].as_u64(), 31357891323 + 8000000);
902        // Empty result set folds to None (missing-capture semantics).
903        let empty = JsonBody(serde_json::json!([]));
904        let c2 = extract_captures_from_json(&empty, &specs[..1]);
905        assert!(matches!(c2["completion_ratio"], polydat::ast::Value::None));
906    }
907
908    #[test]
909    fn extract_json_pointer_scalar_from_bulk_response() {
910        let body = JsonBody(serde_json::json!([
911            {"value": 7,       "status": 200},
912            {"value": [],      "status": 200},
913            {"value": 0,       "status": 200},
914        ]));
915        let specs = vec![
916            cap_path("sstables", "/0/value", false),
917            cap_path("pending_for_cf", "/2/value", false),
918        ];
919        let captures = extract_captures_from_json(&body, &specs);
920        assert_eq!(captures["sstables"].as_u64(), 7);
921        assert_eq!(captures["pending_for_cf"].as_u64(), 0);
922    }
923
924    #[test]
925    fn extract_json_pointer_resolved_null_yields_none_not_string() {
926        let body = JsonBody(serde_json::json!([
927            {"value": null, "status": 200},
928        ]));
929        let specs = vec![cap_path("pending_for_cf", "/0/value", false)];
930        let captures = extract_captures_from_json(&body, &specs);
931        assert!(
932            matches!(captures["pending_for_cf"], polydat::ast::Value::None),
933            "JSON null at path should yield Value::None, got {:?}",
934            captures["pending_for_cf"],
935        );
936    }
937
938    #[test]
939    fn extract_json_pointer_count_on_resolved_null_returns_zero() {
940        let body = JsonBody(serde_json::json!([
941            {"value": null, "status": 200},
942        ]));
943        let specs = vec![cap_path("pending_for_cf", "/0/value", true)];
944        let captures = extract_captures_from_json(&body, &specs);
945        assert_eq!(
946            captures["pending_for_cf"].as_u64(),
947            0,
948            "`:count` on resolved-null should return 0, got {:?}",
949            captures["pending_for_cf"],
950        );
951    }
952
953    #[test]
954    fn extract_json_pointer_count_collapses_array_to_length() {
955        let body = JsonBody(serde_json::json!([
956            {"value": 7},
957            {"value": [
958                {"compactionId":"a", "keyspace":"ks", "columnfamily":"cf"},
959                {"compactionId":"b", "keyspace":"ks", "columnfamily":"cf"},
960            ]},
961        ]));
962        let specs = vec![cap_path("active_count", "/1/value", true)];
963        let captures = extract_captures_from_json(&body, &specs);
964        assert_eq!(captures["active_count"].as_u64(), 2);
965    }
966
967    #[test]
968    fn extract_json_pointer_missing_path_yields_none() {
969        let body = JsonBody(serde_json::json!({"value": 7}));
970        let specs = vec![cap_path("not_there", "/missing/path", false)];
971        let captures = extract_captures_from_json(&body, &specs);
972        assert!(
973            matches!(captures["not_there"], polydat::ast::Value::None),
974            "expected Value::None for unresolvable JSON-Pointer, got {:?}",
975            captures["not_there"],
976        );
977    }
978
979    #[test]
980    fn extract_json_pointer_count_of_missing_path_is_zero() {
981        let body = JsonBody(serde_json::json!({"value": 7}));
982        let specs = vec![cap_path("active_count", "/missing/value", true)];
983        let captures = extract_captures_from_json(&body, &specs);
984        assert_eq!(captures["active_count"].as_u64(), 0);
985    }
986
987    #[test]
988    fn extract_json_pointer_structural_sub_tree_captured_as_json() {
989        let body = JsonBody(serde_json::json!([
990            {"value": {"keyspace": "ks", "table": "cf", "ssTables": 3}},
991        ]));
992        let specs = vec![cap_path("state", "/0/value", false)];
993        let captures = extract_captures_from_json(&body, &specs);
994        match &captures["state"] {
995            polydat::ast::Value::Json(arc) => {
996                assert_eq!(arc.get("keyspace").and_then(|v| v.as_str()), Some("ks"));
997                assert_eq!(arc.get("ssTables").and_then(|v| v.as_u64()), Some(3));
998            }
999            other => panic!("expected Value::Json, got {other:?}"),
1000        }
1001        // Silence dead-code warnings if helpers are unused in some subset
1002        let _ = count_of_subtree;
1003        let _ = json_subtree_to_value;
1004    }
1005}