Skip to main content

nmbrs_runtime/wrappers/
result.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Result-as-GK adapter (SRD-40b §5). After the inner adapter
5//! returns its `OpResult`, this wrapper exposes declared
6//! op-result fields plus the magic externs (`body`, `count`,
7//! `ok`) as Polydat named wires on the per-fiber op-template kernel
8//! via `ctx.wires.write`. Sits between the inner adapter and
9//! the metrics layer in the wrapper stack.
10
11use std::sync::Arc;
12
13use super::traverse::json_to_value;
14use crate::adapter::WrappingDispenser;
15use crate::adapter::{ExecutionError, OpDispenser, OpResult};
16use crate::wrapper_registry::{WrapperName, WrapperRegistration, WrapperSubject};
17
18/// SRD-32a wrapper name. Always present — no-op when the op
19/// declares no `result:` wires.
20pub const NAME: WrapperName = WrapperName::new("result");
21
22fn triggers(s: WrapperSubject) -> bool {
23    s.op().is_some()
24}
25
26fn describe_assignment(s: WrapperSubject) -> Option<String> {
27    let template = s.op()?;
28    let spec = template.result.as_ref()?;
29    if spec.is_empty() {
30        return None;
31    }
32    let mut names: Vec<String> = Vec::new();
33    spec.walk_fragments(|frag| match frag {
34        nmbrs_workload::model::ResultFragment::Named { name, .. } => {
35            names.push(name.to_string());
36        }
37        nmbrs_workload::model::ResultFragment::Source(source) => {
38            for line in source.lines() {
39                let line = line.trim();
40                if let Some((name, _)) = line.split_once(":=") {
41                    names.push(name.trim().to_string());
42                }
43            }
44        }
45    });
46    if names.is_empty() {
47        return None;
48    }
49    names.sort();
50    names.dedup();
51    Some(format!("result: captures {}", names.join(", ")))
52}
53
54inventory::submit! {
55    WrapperRegistration {
56        name: NAME,
57        // `result:` is parsed into ParsedOp.result, not into
58        // params, so this wrapper has no owned `params`-keys
59        // to declare — the trigger always fires (the cascade
60        // wraps unconditionally, no-op when result map is
61        // empty).
62        owned_fields: &[],
63        triggers,
64        requires_inner: &[super::traverse::NAME],
65        forbids_outer: &[],
66        mutually_exclusive_with: &[],
67        describe_assignment,
68        levels: &[crate::wrapper_registry::WrapperLevel::Op],
69    }
70}
71
72/// Wraps an inner OpDispenser to expose declared op-result fields
73/// as Polydat named wires (SRD-40b §5).
74///
75/// Per cycle, after the inner adapter returns its `OpResult`, this
76/// wrapper walks the op template's `result: HashMap<String,
77/// ResultWireSpec>` declarations, computes each value from the
78/// result body, and writes it through `ctx.wires.write(name, value)`
79/// onto the per-fiber op-template kernel's input slot. Wrappers
80/// later in the stack (e.g. `MetricsDispenser`) read freshly through
81/// `ctx.wires.get(name)`, so SRD-40b §5.2 metric evaluation sees
82/// the values landed this cycle — no HashMap intermediary.
83///
84/// Insertion order in the wrapper stack (SRD-40b §5.2): inner
85/// adapter → ResultDispenser → MetricsDispenser (Phase E).
86///
87/// Source grammars (SRD-40b §5.1):
88/// - `count` — built-in; `OpResult::body.element_count()`.
89/// - `ok` — built-in; `true` iff the inner adapter returned `Ok(_)`
90///   (errors short-circuit before this wrapper's body runs, so
91///   reaching this code already implies success — `ok` is `true`
92///   unless the result was a skip).
93/// - `<path-expr>` — JSON-pointer-style lookup into the result
94///   body. Supports bare names (`field`), dotted paths
95///   (`rows.0.field`), and bracketed indices (`rows[0].field`).
96/// - `<polydat-call>` — DEFERRED. Recognized as anything containing a
97///   `(` token; currently logged once and skipped. Phase E or a
98///   follow-up adds the GK-eval-against-result-context path.
99pub struct ResultDispenser {
100    inner: Arc<dyn OpDispenser>,
101    /// Map-shape `count` / `ok` / path-expr declarations that
102    /// stay on the dispenser's evaluator (SRD-40b §5.1
103    /// backwards compat). SRD-66 string-shape and polydat-call
104    /// entries are NOT here — they're compiled into the
105    /// op-template kernel's body via SRD-67 Phase 5
106    /// `add_result_bindings` and evaluated by GK; the dispenser
107    /// just feeds them inputs through the
108    /// `populate_kernel_inputs` flag.
109    specs: Vec<ResultSlot>,
110    /// SRD-67 Phase 5 — when the op's `result:` source contains
111    /// any string-shape or polydat-call entries, the dispenser writes
112    /// the magic pre-bound inputs (`body` / `count` / `ok`)
113    /// through `ctx.wires.write` onto the op-template kernel's
114    /// input slots before result-binding expressions evaluate.
115    /// The kernel's closure-binding economy returns `NoSlot` for
116    /// slots it doesn't reference, so unconditional writes are
117    /// safe. Under `KernelOptLevel::Diagnostic` every slot is
118    /// allocated regardless.
119    populate_kernel_inputs: bool,
120}
121
122/// Parsed form of one `result:` declaration.
123struct ResultSlot {
124    /// Wire name (the map key in `ParsedOp.result`). Drives the
125    /// `ctx.wires.write(name, …)` call inside `execute` — the
126    /// kernel's matching input slot receives the value.
127    wire: String,
128    /// Decoded source grammar.
129    source: ResultSource,
130    /// Optional default rendered as a Polydat Value (string fallback)
131    /// when the source resolves to nothing.
132    default: Option<polydat::ast::Value>,
133    /// SRD-109 Part 3 — the declared interface type when this wire
134    /// fills an `abstract: results:` contract. Drives wildcard
135    /// projection coercion (the projection lands as exactly this
136    /// type, empty form included) instead of the inference ladder.
137    target: Option<polydat::ast::PortType>,
138}
139
140/// Decoded SRD-40b §5.1 source grammar.
141enum ResultSource {
142    /// `count` — element count of the result body.
143    Count,
144    /// `ok` — success boolean.
145    Ok,
146    /// `<path-expr>` — JSON path into the result body, pre-parsed
147    /// into segments.
148    Path(Vec<PathSeg>),
149    /// `<polydat-call>` — deferred. Carries the raw source for the
150    /// follow-up implementation.
151    #[allow(dead_code)]
152    PolydatCall(String),
153}
154
155/// One segment of a parsed path expression.
156#[derive(Debug, Clone)]
157pub(crate) enum PathSeg {
158    Field(String),
159    Index(usize),
160    /// SRD-70 `[*]` — column projection across every element of
161    /// the array at this position. At most one per path.
162    Wildcard,
163}
164
165/// Parse `rows[0].field` / `rows.0.field` / `field` into segments.
166/// Returns `Err` for empty paths only — anything else parses as a
167/// best-effort sequence of identifiers + indices.
168pub(crate) fn parse_path_expr(src: &str) -> Result<Vec<PathSeg>, String> {
169    let trimmed = src.trim();
170    if trimmed.is_empty() {
171        return Err("empty path".into());
172    }
173    let mut segs = Vec::new();
174    let mut cur = String::new();
175    let mut iter = trimmed.chars().peekable();
176    let push_field = |segs: &mut Vec<PathSeg>, cur: &mut String| {
177        if !cur.is_empty() {
178            // Numeric bareword (after a dot) becomes an index; a
179            // bare `*` bareword is the SRD-70 wildcard.
180            if cur == "*" {
181                segs.push(PathSeg::Wildcard);
182            } else if let Ok(n) = cur.parse::<usize>() {
183                segs.push(PathSeg::Index(n));
184            } else {
185                segs.push(PathSeg::Field(std::mem::take(cur)));
186            }
187            cur.clear();
188        }
189    };
190    while let Some(&c) = iter.peek() {
191        match c {
192            '.' => {
193                push_field(&mut segs, &mut cur);
194                iter.next();
195            }
196            '[' => {
197                push_field(&mut segs, &mut cur);
198                iter.next();
199                let mut idx = String::new();
200                for c2 in iter.by_ref() {
201                    if c2 == ']' {
202                        break;
203                    }
204                    idx.push(c2);
205                }
206                if idx.trim() == "*" {
207                    segs.push(PathSeg::Wildcard);
208                } else {
209                    let n: usize = idx
210                        .trim()
211                        .parse()
212                        .map_err(|_| format!("path '{src}': invalid index '[{idx}]'"))?;
213                    segs.push(PathSeg::Index(n));
214                }
215            }
216            _ => {
217                cur.push(c);
218                iter.next();
219            }
220        }
221    }
222    push_field(&mut segs, &mut cur);
223    if segs.is_empty() {
224        return Err(format!("path '{src}': no segments"));
225    }
226    // SRD-70 first wave: one wildcard per path. Two-level nested
227    // projection is parked until a use case drives it.
228    let wildcards = segs
229        .iter()
230        .filter(|s| matches!(s, PathSeg::Wildcard))
231        .count();
232    if wildcards > 1 {
233        return Err(format!(
234            "path '{src}': at most one [*] wildcard per path \
235             (nested projection is not supported)"
236        ));
237    }
238    Ok(segs)
239}
240
241/// Split a parsed path at its wildcard, if any: `(prefix,
242/// suffix)` — segments before and after the `[*]`.
243fn wildcard_split(segs: &[PathSeg]) -> Option<(&[PathSeg], &[PathSeg])> {
244    let pos = segs.iter().position(|s| matches!(s, PathSeg::Wildcard))?;
245    Some((&segs[..pos], &segs[pos + 1..]))
246}
247
248/// SRD-70 column projection: walk `prefix` to the array, then
249/// apply `suffix` to each element, collecting every match.
250/// Elements whose suffix misses are dropped from the projection
251/// (SRD-70: "skip / drop the row"). Returns `None` when the
252/// prefix itself misses or lands on a non-array — the projection
253/// target does not exist in this body.
254fn resolve_path_projection<'a>(
255    json: &'a serde_json::Value,
256    prefix: &[PathSeg],
257    suffix: &[PathSeg],
258) -> Option<Vec<&'a serde_json::Value>> {
259    let at = resolve_path(json, prefix)?;
260    let arr = at.as_array()?;
261    Some(
262        arr.iter()
263            .filter_map(|el| resolve_path(el, suffix))
264            .collect(),
265    )
266}
267
268/// Coerce one JSON leaf to i64: native integer, or numeric string.
269fn leaf_as_i64(v: &serde_json::Value) -> Option<i64> {
270    v.as_i64().or_else(|| v.as_str()?.trim().parse().ok())
271}
272
273/// Coerce one JSON leaf to f64: native number, or numeric string.
274fn leaf_as_f64(v: &serde_json::Value) -> Option<f64> {
275    v.as_f64().or_else(|| v.as_str()?.trim().parse().ok())
276}
277
278/// Evaluate a parsed path against a result-body JSON: wildcard
279/// paths run the SRD-70 column projection (always landing a
280/// value — an empty body / short array projects to the empty
281/// form of the wire's type, never a stale previous-cycle read);
282/// scalar paths walk to a single value (`None` on miss). Shared
283/// with the validation wrapper, which evaluates `actual:`
284/// projections directly from the op result — it sits INSIDE the
285/// `result` wrapper in the cascade, before the wire write lands.
286pub(crate) fn evaluate_path_value(
287    json: &serde_json::Value,
288    segs: &[PathSeg],
289    target: Option<polydat::ast::PortType>,
290) -> Option<polydat::ast::Value> {
291    if let Some((prefix, suffix)) = wildcard_split(segs) {
292        let collected = resolve_path_projection(json, prefix, suffix).unwrap_or_default();
293        return Some(coerce_projection(&collected, target));
294    }
295    resolve_path(json, segs).map(json_to_value)
296}
297
298/// Type a collected projection as a Polydat value. With a declared
299/// `target` (an SRD-109 `results:` interface type) the column
300/// coerces to exactly that type — empty projection included — and
301/// non-coercible elements are dropped per SRD-70. Without a
302/// target, the inference ladder applies: all-integer → `VecI64`,
303/// all-float → `VecF64`, anything else → the collected array as
304/// `Json`.
305fn coerce_projection(
306    collected: &[&serde_json::Value],
307    target: Option<polydat::ast::PortType>,
308) -> polydat::ast::Value {
309    use polydat::ast::{PortType, SliceArc, Value};
310    let json_array = || {
311        Value::Json(std::sync::Arc::new(serde_json::Value::Array(
312            collected.iter().map(|v| (*v).clone()).collect(),
313        )))
314    };
315    match target {
316        Some(PortType::VecI64) => Value::VecI64(SliceArc::from_vec(
317            collected.iter().filter_map(|v| leaf_as_i64(v)).collect(),
318        )),
319        Some(PortType::VecI32) => Value::VecI32(SliceArc::from_vec(
320            collected
321                .iter()
322                .filter_map(|v| leaf_as_i64(v).map(|n| n as i32))
323                .collect(),
324        )),
325        Some(PortType::VecF64) => Value::VecF64(SliceArc::from_vec(
326            collected.iter().filter_map(|v| leaf_as_f64(v)).collect(),
327        )),
328        Some(PortType::VecF32) => Value::VecF32(SliceArc::from_vec(
329            collected
330                .iter()
331                .filter_map(|v| leaf_as_f64(v).map(|n| n as f32))
332                .collect(),
333        )),
334        Some(PortType::Json) => json_array(),
335        // A declared scalar/other type on a wildcard projection is
336        // rejected at load by the binder; reaching here means an
337        // untyped (non-interface) wire — fall through to inference.
338        _ => {
339            let ints: Vec<i64> = collected.iter().filter_map(|v| leaf_as_i64(v)).collect();
340            if !collected.is_empty() && ints.len() == collected.len() {
341                return Value::VecI64(SliceArc::from_vec(ints));
342            }
343            let floats: Vec<f64> = collected.iter().filter_map(|v| leaf_as_f64(v)).collect();
344            if !collected.is_empty() && floats.len() == collected.len() {
345                return Value::VecF64(SliceArc::from_vec(floats));
346            }
347            json_array()
348        }
349    }
350}
351
352/// Walk a parsed path against a JSON value. Returns `None` when
353/// any segment misses (object lacks key, array shorter than index,
354/// scalar where a container was expected).
355fn resolve_path<'a>(
356    json: &'a serde_json::Value,
357    segs: &[PathSeg],
358) -> Option<&'a serde_json::Value> {
359    let mut cur = json;
360    for seg in segs {
361        cur = match (cur, seg) {
362            (serde_json::Value::Object(m), PathSeg::Field(k)) => m.get(k)?,
363            (serde_json::Value::Array(a), PathSeg::Index(i)) => a.get(*i)?,
364            // Bareword field on an array, or numeric on an object —
365            // we don't try to coerce; the path doesn't match.
366            _ => return None,
367        };
368    }
369    Some(cur)
370}
371
372/// Decode one `(name, source-string)` pair from a SRD-66
373/// map-shape `result:` fragment into a `ResultSlot`. Unknown
374/// / unparseable sources land as `None` (caller logs and
375/// drops them — SRD-40b §5.1 calls for "log a warning and
376/// skip" over a hard failure here, since the value mechanism
377/// is supposed to be best-effort per cycle).
378///
379/// String-shape and list-shape `result:` fragments don't go
380/// through this function — they compile into the auxiliary
381/// kernel under SRD-66 §"Compilation lifecycle" (TBD when
382/// the structural-body Value variant lands).
383fn decode_slot(
384    name: &str,
385    raw_source: &str,
386    target: Option<polydat::ast::PortType>,
387) -> Option<ResultSlot> {
388    let raw = raw_source.trim();
389    let source = if raw == "count" {
390        ResultSource::Count
391    } else if raw == "ok" {
392        ResultSource::Ok
393    } else if raw.contains('(') {
394        // SRD-66 Surface 1 — GK-expression form. The full
395        // kernel-driven path (compile auxiliary kernel,
396        // wire body/count/ok externs via the closure-binding
397        // rule, evaluate per-cycle) is staged behind this
398        // diagnostic until the structural-body Value variant
399        // and op-template kernel extension land. Today the
400        // form is recognised but evaluates to its default.
401        crate::diag!(
402            crate::observer::LogLevel::Warn,
403            "result wire '{name}': GK-expression source '{raw}' is not yet \
404             evaluated end-to-end — slot will resolve to its default. \
405             SRD-66 Push 2 follow-up wires the kernel-driven path.",
406        );
407        ResultSource::PolydatCall(raw.to_string())
408    } else {
409        // Path expression. Parse failures degrade to skip.
410        match parse_path_expr(raw) {
411            Ok(segs) => ResultSource::Path(segs),
412            Err(e) => {
413                crate::diag!(
414                    crate::observer::LogLevel::Warn,
415                    "result wire '{name}': source '{raw}' is not parseable as a \
416                     path expression ({e}) — slot will be skipped.",
417                );
418                return None;
419            }
420        }
421    };
422    Some(ResultSlot {
423        wire: name.to_string(),
424        source,
425        default: None,
426        target,
427    })
428}
429
430impl ResultDispenser {
431    /// Wrap an inner dispenser with result-as-GK exposure
432    /// (SRD-40b §5.2's result-as-GK adapter layer).
433    ///
434    /// **Always wraps.** Per the SRD, this layer is part of the
435    /// canonical per-cycle pipeline: it writes the magic externs
436    /// (`body` / `count` / `ok`) into the op-template kernel's
437    /// input slots after the inner adapter returns, so any
438    /// downstream wrapper (metrics, validation, conditional next
439    /// op) reading those names through `ctx.wires.get` sees fresh
440    /// values. Writes to slots the kernel didn't allocate (the
441    /// closure-binding economy's DCE) silently no-op via
442    /// `WriteOutcome::NoSlot` — no overhead for ops whose
443    /// op-template kernel doesn't reference any magic extern.
444    ///
445    /// The optional `result_spec` adds *additional* dispenser-side
446    /// dispatch slots (legacy SRD-40b §5.1 path-expr / `count` /
447    /// `ok` map-shape forms). Kernel-driven entries (string-shape
448    /// source blocks, polydat-call entries) need no per-cycle code
449    /// here — `add_result_bindings` compiled them into the
450    /// op-template kernel; the magic-extern population this
451    /// wrapper always performs is what makes them resolve.
452    pub fn wrap(
453        inner: Arc<dyn OpDispenser>,
454        result_spec: Option<&nmbrs_workload::model::ResultSpec>,
455        interface_results: Option<&std::collections::BTreeMap<String, polydat::ast::PortType>>,
456    ) -> Arc<dyn OpDispenser> {
457        let mut specs: Vec<ResultSlot> = Vec::new();
458
459        // SRD-109 Part 3 — a wire filling an `abstract: results:`
460        // contract projects at exactly its declared type.
461        let target_for = |name: &str| -> Option<polydat::ast::PortType> {
462            interface_results?.get(name).copied()
463        };
464
465        if let Some(spec) = result_spec {
466            spec.walk_fragments(|frag| match frag {
467                nmbrs_workload::model::ResultFragment::Named { name, source } => {
468                    let raw = source.trim();
469                    if raw == "count" || raw == "ok" {
470                        if let Some(slot) = decode_slot(name, source, target_for(name)) {
471                            specs.push(slot);
472                        }
473                    } else if !raw.contains('(') {
474                        // Path expression — keep the legacy
475                        // JSON-path path for SRD-40b §5.1 back-compat.
476                        if let Some(slot) = decode_slot(name, source, target_for(name)) {
477                            specs.push(slot);
478                        }
479                    }
480                    // polydat-call entries (raw.contains('(')) are
481                    // kernel-driven; nothing per-cycle to do here.
482                }
483                nmbrs_workload::model::ResultFragment::Source(_source) => {
484                    // String-shape — fully kernel-driven. No
485                    // per-cycle code here.
486                }
487            });
488        }
489
490        // Stable order so wire-resolution warnings (and the
491        // per-cycle insertion order) are reproducible.
492        specs.sort_by(|a, b| a.wire.cmp(&b.wire));
493        Arc::new(Self {
494            inner,
495            specs,
496            // Magic-extern population always fires. The
497            // populate_kernel_inputs field is retained for the
498            // diagnostic-trace conditional below but its value
499            // is now always-true.
500            populate_kernel_inputs: true,
501        })
502    }
503
504    /// Compute the Polydat value for one slot from the cycle's result.
505    /// Returns `None` when the slot resolves to nothing and has no
506    /// default — caller logs at debug and moves on.
507    fn evaluate(slot: &ResultSlot, result: &OpResult) -> Option<polydat::ast::Value> {
508        match &slot.source {
509            ResultSource::Count => {
510                let n = result.body.as_ref().map(|b| b.element_count()).unwrap_or(0);
511                Some(polydat::ast::Value::U64(n))
512            }
513            ResultSource::Ok => {
514                // Reached only on Ok(_) from the inner adapter; a
515                // skipped op also counts as "not a failure" — we
516                // treat skip as ok=true, matching the SRD-40b §5
517                // intent that this is a binary success signal.
518                Some(polydat::ast::Value::Bool(true))
519            }
520            ResultSource::Path(segs) => {
521                let body = result.body.as_ref()?;
522                let json = body.to_json();
523                evaluate_path_value(&json, segs, slot.target).or_else(|| slot.default.clone())
524            }
525            ResultSource::PolydatCall(_) => slot.default.clone(),
526        }
527    }
528}
529
530impl WrappingDispenser for ResultDispenser {}
531
532impl OpDispenser for ResultDispenser {
533    fn execute<'a>(
534        &'a self,
535        cycle: u64,
536        ctx: &'a crate::fixture::ExecCtx<'a>,
537    ) -> std::pin::Pin<
538        Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
539    > {
540        Box::pin(async move {
541            let result = self.inner.execute(cycle, ctx).await?;
542            // Skipped ops carry no body; per SRD-40b §5.2 the
543            // metric pipeline doesn't fire on skips either. The
544            // Phase E wrappers observe `result.skipped` and bail
545            // before evaluating.
546            if result.skipped {
547                return Ok(result);
548            }
549            for slot in &self.specs {
550                if let Some(v) = Self::evaluate(slot, &result) {
551                    // Canonical write — lands directly on the op-template
552                    // kernel's input slot via ctx.wires. Subsequent
553                    // wrapper reads (e.g. MetricsDispenser) see the
554                    // fresh value through wires.get on the same cycle.
555                    let _ = ctx.wires.write(&slot.wire, v);
556                }
557                // Per-cycle missing-wire is silent. If a downstream
558                // consumer (e.g. MetricsDispenser) references a wire
559                // that didn't land on the kernel, that consumer
560                // surfaces the failure as a hard ExecutionError —
561                // logging it here would just add per-cycle session.log
562                // spam without telling the user anything actionable.
563            }
564
565            // SRD-67 Phase 5 — magic-extern population. When the
566            // op declares any kernel-driven result-bindings
567            // (string-shape OR map-shape polydat-call), inject the
568            // standard `body` / `count` / `ok` inputs through
569            // ctx.wires so the op-template kernel's input slots
570            // are populated before any wrapper above this one in
571            // the stack reads them. The closure-binding economy
572            // drops slots the kernel doesn't reference, so this
573            // is safe even if the user's source only references
574            // a subset — NoSlot writes are silently ignored.
575            // Under KernelOptLevel::Diagnostic every magic extern
576            // gets a slot, so all three always land.
577            if self.populate_kernel_inputs {
578                let count = result.body.as_ref().map(|b| b.element_count()).unwrap_or(0);
579                // SRD-66 §"Surface 4 §Open: body type" resolved
580                // to `Value::Json` — body rides the kernel as a
581                // structural value so `exactly_one_value(body)`
582                // can walk row × column shape (per
583                // `polydat::library::exactly_one`). For ops
584                // whose body has no structural projection the
585                // adapter's `to_json()` returns a JSON String,
586                // which `exactly_one_value` collapses to
587                // `Value::Str`.
588                let body_json = result
589                    .body
590                    .as_ref()
591                    .map(|b| b.to_json())
592                    .unwrap_or(serde_json::Value::Null);
593                let _ = ctx.wires.write(
594                    "body",
595                    polydat::ast::Value::Json(std::sync::Arc::new(body_json)),
596                );
597                let _ = ctx.wires.write("count", polydat::ast::Value::U64(count));
598                let _ = ctx.wires.write("ok", polydat::ast::Value::Bool(true));
599            }
600
601            let _ = cycle;
602            Ok(result)
603        })
604    }
605    fn inner_dispenser(&self) -> Option<&dyn OpDispenser> {
606        Some(self.inner.as_ref())
607    }
608}
609
610#[cfg(test)]
611mod tests {
612    use super::*;
613    use crate::adapter::{AdapterError, ExecutionError, OpResult, ResultBody};
614    use crate::fixture::{ExecCtx, ResolvedPulls};
615    use std::sync::Arc;
616
617    #[derive(Debug)]
618    struct ResultDispBody {
619        value: serde_json::Value,
620        count: u64,
621    }
622    impl ResultBody for ResultDispBody {
623        fn to_json(&self) -> serde_json::Value {
624            self.value.clone()
625        }
626        fn as_any(&self) -> &dyn std::any::Any {
627            self
628        }
629        fn element_count(&self) -> u64 {
630            self.count
631        }
632    }
633
634    struct FakeInner {
635        body: Option<ResultDispBody>,
636        error: Option<&'static str>,
637    }
638    impl OpDispenser for FakeInner {
639        fn execute<'a>(
640            &'a self,
641            _cycle: u64,
642            _ctx: &'a ExecCtx<'a>,
643        ) -> std::pin::Pin<
644            Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
645        > {
646            Box::pin(async move {
647                if let Some(msg) = self.error {
648                    return Err(ExecutionError::Op(AdapterError {
649                        error_name: "test".into(),
650                        message: msg.into(),
651                        retryable: false,
652                    }));
653                }
654                Ok(OpResult {
655                    body: self.body.as_ref().map(|b| {
656                        Box::new(ResultDispBody {
657                            value: b.value.clone(),
658                            count: b.count,
659                        }) as Box<dyn ResultBody>
660                    }),
661                    skipped: false,
662                })
663            })
664        }
665    }
666
667    fn empty_ctx() -> (crate::adapter::ResolvedFields, ResolvedPulls) {
668        let fields = crate::adapter::ResolvedFields::new(vec![], vec![]);
669        let pulls = ResolvedPulls::empty();
670        (fields, pulls)
671    }
672
673    fn kernel_with_extern_inputs(names: &[(&str, &str)]) -> crate::scope_kernel::ScopeKernel {
674        let mut src = String::from("input cycle: u64\n");
675        for (n, ty) in names {
676            src.push_str(&format!("extern {n}: {ty}\n"));
677        }
678        let mut k = crate::bindings::compile_scope_kernel(&src, &Default::default())
679            .expect("kernel_with_extern_inputs compile");
680        k.set_inputs(&[0]);
681        k
682    }
683
684    fn run_with_wires(
685        dispenser: Arc<dyn OpDispenser>,
686        kernel: &mut crate::scope_kernel::ScopeKernel,
687    ) -> Result<OpResult, ExecutionError> {
688        let fields = crate::adapter::ResolvedFields::new(vec![], vec![]);
689        let pulls = ResolvedPulls::empty();
690        let cw = crate::wires::CycleWires::new(kernel);
691        let ctx = ExecCtx::with_wires(&fields, &pulls, &cw);
692        let rt = tokio::runtime::Builder::new_current_thread()
693            .build()
694            .unwrap();
695        rt.block_on(dispenser.execute(0, &ctx))
696    }
697
698    #[test]
699    fn parse_path_dotted_and_bracketed_equivalent() {
700        let a = parse_path_expr("rows[0].value").unwrap();
701        let b = parse_path_expr("rows.0.value").unwrap();
702        assert_eq!(a.len(), 3);
703        assert_eq!(b.len(), 3);
704        match (&a[0], &b[0]) {
705            (PathSeg::Field(f1), PathSeg::Field(f2)) => assert_eq!(f1, f2),
706            _ => panic!("expected leading field"),
707        }
708        match (&a[1], &b[1]) {
709            (PathSeg::Index(0), PathSeg::Index(0)) => {}
710            _ => panic!("expected index 0"),
711        }
712    }
713
714    fn map_spec(entries: &[(&str, &str)]) -> nmbrs_workload::model::ResultSpec {
715        let mut m = std::collections::BTreeMap::new();
716        for (k, v) in entries {
717            m.insert((*k).to_string(), (*v).to_string());
718        }
719        nmbrs_workload::model::ResultSpec::Map(m)
720    }
721
722    #[test]
723    fn result_dispenser_count_and_path() {
724        let inner = Arc::new(FakeInner {
725            body: Some(ResultDispBody {
726                value: serde_json::json!({"rows": [{"value": 42}]}),
727                count: 1,
728            }),
729            error: None,
730        });
731        let decl = map_spec(&[("row_count", "count"), ("first_value", "rows[0].value")]);
732
733        let wrapped = ResultDispenser::wrap(inner, Some(&decl), None);
734        let mut kernel = kernel_with_extern_inputs(&[("row_count", "u64"), ("first_value", "u64")]);
735        let _ = run_with_wires(wrapped, &mut kernel).unwrap();
736
737        let cw = crate::wires::CycleWires::new(&mut kernel);
738        let w: &dyn crate::wires::WireSource = &cw;
739        assert_eq!(w.get("row_count").map(|v| v.as_u64()), Some(1));
740        assert_eq!(w.get("first_value").map(|v| v.as_u64()), Some(42));
741    }
742
743    #[test]
744    fn result_dispenser_ok_builtin_on_success() {
745        let inner = Arc::new(FakeInner {
746            body: Some(ResultDispBody {
747                value: serde_json::json!({}),
748                count: 0,
749            }),
750            error: None,
751        });
752        let decl = map_spec(&[("succeeded", "ok")]);
753
754        let wrapped = ResultDispenser::wrap(inner, Some(&decl), None);
755        let mut kernel = kernel_with_extern_inputs(&[("succeeded", "bool")]);
756        let _ = run_with_wires(wrapped, &mut kernel).unwrap();
757
758        let cw = crate::wires::CycleWires::new(&mut kernel);
759        let w: &dyn crate::wires::WireSource = &cw;
760        match w.get("succeeded") {
761            Some(polydat::ast::Value::Bool(b)) => assert!(b),
762            other => panic!("expected Bool(true), got {other:?}"),
763        }
764    }
765
766    #[test]
767    fn result_dispenser_error_propagates_no_capture_write() {
768        let inner = Arc::new(FakeInner {
769            body: None,
770            error: Some("boom"),
771        });
772        let decl = map_spec(&[("succeeded", "ok")]);
773
774        let wrapped = ResultDispenser::wrap(inner, Some(&decl), None);
775        let (fields, pulls) = empty_ctx();
776        let ctx = ExecCtx::new(&fields, &pulls);
777        let rt = tokio::runtime::Builder::new_current_thread()
778            .build()
779            .unwrap();
780        let err = rt.block_on(wrapped.execute(0, &ctx)).unwrap_err();
781        assert!(format!("{err}").contains("boom"));
782    }
783
784    #[test]
785    fn result_dispenser_unresolved_path_skips_silently() {
786        let inner = Arc::new(FakeInner {
787            body: Some(ResultDispBody {
788                value: serde_json::json!({"rows": []}),
789                count: 0,
790            }),
791            error: None,
792        });
793        let decl = map_spec(&[("missing", "rows[0].value")]);
794
795        let wrapped = ResultDispenser::wrap(inner, Some(&decl), None);
796        let mut kernel = kernel_with_extern_inputs(&[("missing", "u64")]);
797        let _ = run_with_wires(wrapped, &mut kernel).unwrap();
798
799        let cw = crate::wires::CycleWires::new(&mut kernel);
800        let w: &dyn crate::wires::WireSource = &cw;
801        assert!(matches!(
802            w.get("missing"),
803            Some(polydat::ast::Value::None) | None
804        ));
805    }
806
807    #[test]
808    fn result_dispenser_always_wraps_per_srd_40b() {
809        let inner: Arc<dyn OpDispenser> = Arc::new(FakeInner {
810            body: Some(ResultDispBody {
811                value: serde_json::json!({}),
812                count: 0,
813            }),
814            error: None,
815        });
816        let inner_ptr = Arc::as_ptr(&inner);
817        let wrapped = ResultDispenser::wrap(inner.clone(), None, None);
818        assert_ne!(
819            Arc::as_ptr(&wrapped),
820            inner_ptr,
821            "ResultDispenser must always wrap so magic-extern population fires"
822        );
823    }
824
825    #[test]
826    fn result_dispenser_skipped_op_writes_no_captures() {
827        struct SkipInner;
828        impl OpDispenser for SkipInner {
829            fn execute<'a>(
830                &'a self,
831                _cycle: u64,
832                _ctx: &'a ExecCtx<'a>,
833            ) -> std::pin::Pin<
834                Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
835            > {
836                Box::pin(async move { Ok(OpResult::skipped()) })
837            }
838        }
839        let decl = map_spec(&[("c", "count")]);
840        let wrapped = ResultDispenser::wrap(Arc::new(SkipInner), Some(&decl), None);
841        let mut kernel = kernel_with_extern_inputs(&[("c", "u64")]);
842        let result = run_with_wires(wrapped, &mut kernel).unwrap();
843        assert!(result.skipped);
844        let cw = crate::wires::CycleWires::new(&mut kernel);
845        let w: &dyn crate::wires::WireSource = &cw;
846        assert!(matches!(w.get("c"), Some(polydat::ast::Value::None) | None));
847    }
848
849    /// Silence dead-code warnings for `decode_slot` when only
850    /// the path-expr branch is exercised by the public tests.
851    #[test]
852    fn decode_slot_reachable() {
853        let slot = decode_slot("c", "count", None).expect("count slot decodes");
854        assert!(matches!(slot.source, ResultSource::Count));
855    }
856
857    // ── SRD-70 wildcard projection ──
858
859    #[test]
860    fn parse_wildcard_forms_and_reject_nested() {
861        for src in [
862            "rows[*].key",
863            "rows.*.key",
864            "[*].key",
865            "[*]",
866            "result[*].id",
867        ] {
868            let segs = parse_path_expr(src).unwrap_or_else(|e| panic!("'{src}' should parse: {e}"));
869            assert_eq!(
870                segs.iter()
871                    .filter(|s| matches!(s, PathSeg::Wildcard))
872                    .count(),
873                1,
874                "'{src}' carries one wildcard"
875            );
876        }
877        let err = parse_path_expr("rows[*].items[*].id").unwrap_err();
878        assert!(err.contains("at most one"), "err: {err}");
879    }
880
881    #[test]
882    fn projection_collects_column_as_target_type() {
883        let inner = Arc::new(FakeInner {
884            body: Some(ResultDispBody {
885                // Zero-padded numeric strings — the vector-suite
886                // key shape.
887                value: serde_json::json!([
888                    {"key": "000000000007"}, {"key": "000000000003"}]),
889                count: 2,
890            }),
891            error: None,
892        });
893        let decl = map_spec(&[("keys", "[*].key")]);
894        let mut iface = std::collections::BTreeMap::new();
895        iface.insert("keys".to_string(), polydat::ast::PortType::VecI64);
896
897        let wrapped = ResultDispenser::wrap(inner, Some(&decl), Some(&iface));
898        let mut kernel = kernel_with_extern_inputs(&[("keys", "vec_i64")]);
899        let _ = run_with_wires(wrapped, &mut kernel).unwrap();
900
901        let cw = crate::wires::CycleWires::new(&mut kernel);
902        let w: &dyn crate::wires::WireSource = &cw;
903        match w.get("keys") {
904            Some(polydat::ast::Value::VecI64(slice)) => assert_eq!(slice.as_slice(), &[7, 3]),
905            other => panic!("expected VecI64([7,3]), got {other:?}"),
906        }
907    }
908
909    #[test]
910    fn projection_nested_prefix_and_inference_ladder() {
911        let inner = Arc::new(FakeInner {
912            body: Some(ResultDispBody {
913                value: serde_json::json!({"result": [
914                    {"id": 12, "score": 0.9},
915                    {"id": 5,  "score": 0.7}]}),
916                count: 2,
917            }),
918            error: None,
919        });
920        // No interface types — the inference ladder applies.
921        let decl = map_spec(&[("ids", "result[*].id"), ("scores", "result[*].score")]);
922        let wrapped = ResultDispenser::wrap(inner, Some(&decl), None);
923        let mut kernel = kernel_with_extern_inputs(&[("ids", "vec_i64"), ("scores", "vec_f64")]);
924        let _ = run_with_wires(wrapped, &mut kernel).unwrap();
925
926        let cw = crate::wires::CycleWires::new(&mut kernel);
927        let w: &dyn crate::wires::WireSource = &cw;
928        match w.get("ids") {
929            Some(polydat::ast::Value::VecI64(slice)) => assert_eq!(slice.as_slice(), &[12, 5]),
930            other => panic!("expected VecI64, got {other:?}"),
931        }
932        match w.get("scores") {
933            Some(polydat::ast::Value::VecF64(slice)) => assert_eq!(slice.as_slice(), &[0.9, 0.7]),
934            other => panic!("expected VecF64, got {other:?}"),
935        }
936    }
937
938    #[test]
939    fn projection_on_missing_prefix_lands_empty_not_stale() {
940        let inner = Arc::new(FakeInner {
941            body: Some(ResultDispBody {
942                value: serde_json::json!({"error": "no result key"}),
943                count: 0,
944            }),
945            error: None,
946        });
947        let decl = map_spec(&[("keys", "result[*].id")]);
948        let mut iface = std::collections::BTreeMap::new();
949        iface.insert("keys".to_string(), polydat::ast::PortType::VecI64);
950        let wrapped = ResultDispenser::wrap(inner, Some(&decl), Some(&iface));
951        let mut kernel = kernel_with_extern_inputs(&[("keys", "vec_i64")]);
952        let _ = run_with_wires(wrapped, &mut kernel).unwrap();
953
954        let cw = crate::wires::CycleWires::new(&mut kernel);
955        let w: &dyn crate::wires::WireSource = &cw;
956        match w.get("keys") {
957            Some(polydat::ast::Value::VecI64(slice)) => assert!(
958                slice.as_slice().is_empty(),
959                "missing projection target must land the EMPTY typed form"
960            ),
961            other => panic!("expected empty VecI64, got {other:?}"),
962        }
963    }
964}