Skip to main content

nmbrs_runtime/
validation.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Result validation and relevancy measurement (SRD 47).
5//!
6//! Provides `ValidatingDispenser`, a composable op dispenser wrapper
7//! that verifies operation results against expected values and computes
8//! information retrieval metrics (recall@k, precision@k, etc.).
9//!
10//! Applied only to templates that declare `verify:` or `relevancy:`
11//! blocks — zero overhead for templates without validation.
12
13use std::collections::HashMap;
14use std::sync::Arc;
15use std::sync::atomic::{AtomicU64, Ordering};
16
17use nmbrs_metrics::labels::Labels;
18
19use crate::adapter::{ExecutionError, OpDispenser, OpResult, WrappingDispenser};
20use crate::relevancy::{self, RelevancyFn};
21use crate::wires::WireSource;
22use crate::wrapper_registry::{WrapperName, WrapperRegistration, WrapperSubject};
23
24/// SRD-32a wrapper name for the validation layer. Exposed at
25/// the module level so other wrappers' `forbids_outer` /
26/// `requires_inner` slices can reference it without depending
27/// on `wrapper_registrations` for the constant.
28pub const WRAPPER_NAME: WrapperName = WrapperName::new("validate");
29
30/// Trigger: op carries `verify:`, `relevancy:` or `admission:`.
31fn wrapper_triggers(s: WrapperSubject) -> bool {
32    let Some(template) = s.op() else {
33        return false;
34    };
35    template.params.contains_key("verify")
36        || template.params.contains_key("relevancy")
37        || template.params.contains_key(crate::admission::PARAM)
38}
39
40fn wrapper_describe_assignment(s: WrapperSubject) -> Option<String> {
41    let template = s.op()?;
42    let strict = template
43        .params
44        .get("strict")
45        .and_then(|v| nmbrs_workload::boolean::json_bool("strict", v).ok())
46        .unwrap_or(false);
47    let mut parts: Vec<String> = Vec::new();
48    if let Some(v) = template.params.get("verify") {
49        parts.push(format!(
50            "verify={}",
51            crate::wrapper_registrations::short_value(v)
52        ));
53    }
54    if let Some(v) = template.params.get("relevancy") {
55        parts.push(format!(
56            "relevancy={}",
57            crate::wrapper_registrations::short_value(v)
58        ));
59    }
60    if let Some(v) = template.params.get(crate::admission::PARAM) {
61        parts.push(format!(
62            "admission={}",
63            crate::wrapper_registrations::short_value(v)
64        ));
65    }
66    if parts.is_empty() {
67        return None;
68    }
69    let body = parts.join(", ");
70    Some(if strict {
71        format!("validate: {body} (strict)")
72    } else {
73        format!("validate: {body}")
74    })
75}
76
77inventory::submit! {
78    WrapperRegistration {
79        name: WRAPPER_NAME,
80        owned_fields: &["verify", "relevancy", "admission", "strict"],
81        triggers: wrapper_triggers,
82        requires_inner: &[crate::wrappers::traverse::NAME],
83        forbids_outer: &[],
84        mutually_exclusive_with: &[],
85        describe_assignment: wrapper_describe_assignment,
86        levels: &[crate::wrapper_registry::WrapperLevel::Op],
87    }
88}
89
90// =========================================================================
91// Validation configuration (parsed from workload YAML at init time)
92// =========================================================================
93
94/// Closed vocabulary of op-template `params:` keys the runtime
95/// itself consumes (validation, batching, polling, op weighting,
96/// adapter selection). Joined at validation time with
97/// `crate::runner::KNOWN_PARAMS` (workload/CLI-level keys that
98/// get blast-merged into every op's params during parse) and the
99/// adapter's
100/// [`crate::adapter::DriverAdapter::known_op_params`] declarations
101/// to form the full allow-list. Unknown keys are rejected at op
102/// setup time so silent-ignore traps like `evaluations: { relevancy: ... }`
103/// (a wrapper key the runtime never reads) cannot hide a
104/// misconfigured op.
105/// Core op-template params consumed directly by the runtime or the
106/// adapter layer that are NOT owned by any wrapper. Wrapper fields
107/// (`verify`, `poll`, `memo`, `readout`, `errors`, `tries`, `while`,
108/// `rate`, `fields`, …) are deliberately absent: the op
109/// closed-vocabulary guard accepts them via
110/// [`crate::wrapper_registry::WrapperRegistry::owns_field`], which
111/// derives the wrapper vocabulary structurally from each wrapper's
112/// `owned_fields` declaration. Keeping them out of this list is the
113/// point — one source of truth per field, so adding a wrapper never
114/// requires editing here. The drift-guard test
115/// `core_op_params_disjoint_from_owned_fields` fails if a wrapper
116/// field creeps back in.
117pub const CORE_OP_PARAMS: &[&str] = &[
118    // Batching (no wrapper owns these — consumed by the batch path).
119    "batch",
120    "batchtype",
121    "max_batch_size",
122    // Op weighting (activity-level dispatch weight, not a wrapper).
123    "ratio",
124    // Adapter selection.
125    "adapter",
126    // Daemon-op declaration. `daemon` marks an op for cycle-pool
127    // dispatch onto a daemon fiber (with per-op-name cap);
128    // `daemon_cancel_grace_ms` overrides the phase-exit drain budget.
129    // (The loop / rate primitives `while` / `rate` ARE wrapper-owned
130    // and come from the registry.)
131    "daemon",
132    "daemon_cancel_grace_ms",
133];
134
135/// Configuration for relevancy measurement on a single op template.
136#[derive(Debug, Clone)]
137pub struct RelevancyConfig {
138    /// Column/field name to extract actual result indices from.
139    pub actual_field: String,
140    /// Polydat binding name that produces ground truth indices.
141    pub expected_binding: String,
142    /// Recall window — number of top results used in the @k
143    /// metric computation. The first `k` of `actual` are
144    /// compared against the first `k` of `expected`.
145    pub k: usize,
146    /// Optional retrieval window. When set, declares "we
147    /// retrieved exactly `r` results, but score using only the
148    /// first `k` of them" (the "k-recall@r" semantic). Runtime
149    /// asserts `actual.len() == r`. When `None`, no separate
150    /// retrieval window is enforced — actual is truncated to
151    /// `k` for the comparison and any length is accepted (the
152    /// pre-`r` behavior).
153    pub r: Option<usize>,
154    /// Optional wire giving the number of rows the cycle's predicate
155    /// admits (SRD-115 §4.5). With it, an op that declares `r` must
156    /// return `min(r, admitted)` rows instead of exactly `r`: under a
157    /// predicate a target cannot return more rows than qualify.
158    pub admitted_binding: Option<String>,
159    /// Which functions to compute.
160    pub functions: Vec<RelevancyFn>,
161}
162
163/// A single field assertion from a `verify:` block.
164#[derive(Debug, Clone)]
165pub struct AssertionSpec {
166    /// Field name to check in the result.
167    pub field: String,
168    /// The predicate to apply.
169    pub predicate: AssertionPredicate,
170}
171
172/// Predicate for field assertion checks.
173#[derive(Debug, Clone)]
174pub enum AssertionPredicate {
175    /// Field must equal this value (string comparison).
176    Eq(String),
177    /// Field must not be null/absent.
178    NotNull,
179    /// Field must be null/absent.
180    IsNull,
181    /// Numeric: field >= threshold.
182    Gte(f64),
183    /// Numeric: field <= threshold.
184    Lte(f64),
185    /// String: field contains substring.
186    Contains(String),
187    /// A numeric bound (`gte:` / `lte:`) whose value is not a number.
188    ///
189    /// Carried rather than dropped, and ALWAYS fails: the previous
190    /// `as_f64().unwrap_or(0.0)` silently turned `lte: "5"` — or any
191    /// unresolved placeholder — into `<= 0`, which then failed against
192    /// perfectly good data with a message quoting a threshold the author
193    /// never wrote. A bound nobody can evaluate must say so, not pick zero.
194    MalformedBound { key: String, raw: String },
195    /// Body-level: result must contain at least N rows
196    /// (`element_count() >= N`). Use to make a SELECT
197    /// failsafe — empty result sets surface as a hard error
198    /// instead of silently passing per-row assertions vacuously.
199    /// Field name is ignored for this predicate.
200    MinRows(u64),
201}
202
203impl AssertionSpec {
204    /// Check this assertion against a result.
205    pub fn check(&self, result: &OpResult) -> bool {
206        // Body-level predicates are evaluated against the result's
207        // shape rather than a per-row field value. Handled before
208        // field extraction.
209        if let AssertionPredicate::MinRows(n) = &self.predicate {
210            let row_count = result.body.as_ref().map(|b| b.element_count()).unwrap_or(0);
211            return row_count >= *n;
212        }
213
214        let json = match &result.body {
215            Some(body) => body.to_json(),
216            // No body at all. A field predicate constrains the VALUE of
217            // something in the response, so with no response it is vacuous —
218            // it passes rather than failing. A succeeding op that returns
219            // nothing (HTTP 204, or `on_timeout: accept`, where the server is
220            // still working and the poll layer is the real observer) must not
221            // be failed by a `field: status, eq: 200` clause that was written
222            // to check a body when one arrives.
223            //
224            // Requiring a body is available, but must be ASKED for, and the
225            // two spellings already exist:
226            //   `is: not_null`  — this field must be present
227            //   `min_rows: 1`   — the result must carry at least one row
228            // Both of those constrain PRESENCE, not value, so both still fail
229            // here. That is the whole distinction: value predicates go quiet
230            // when there is nothing to read; presence predicates are exactly
231            // the ones that shouldn't.
232            None => {
233                return !matches!(
234                    self.predicate,
235                    AssertionPredicate::NotNull | AssertionPredicate::MalformedBound { .. }
236                );
237            }
238        };
239
240        let field_val = extract_field_from_json(&json, &self.field);
241
242        match &self.predicate {
243            AssertionPredicate::NotNull => field_val.is_some(),
244            AssertionPredicate::IsNull => field_val.is_none(),
245            AssertionPredicate::Eq(expected) => {
246                field_val.is_some_and(|v| json_value_as_string(v) == *expected)
247            }
248            AssertionPredicate::Gte(threshold) => field_val
249                .and_then(|v| v.as_f64())
250                .is_some_and(|v| v >= *threshold),
251            AssertionPredicate::Lte(threshold) => field_val
252                .and_then(|v| v.as_f64())
253                .is_some_and(|v| v <= *threshold),
254            AssertionPredicate::Contains(substr) => {
255                field_val.is_some_and(|v| json_value_as_string(v).contains(substr.as_str()))
256            }
257            AssertionPredicate::MalformedBound { .. } => false,
258            AssertionPredicate::MinRows(_) => unreachable!("MinRows handled in early-return above"),
259        }
260    }
261}
262
263// =========================================================================
264// ValidationMetrics
265// =========================================================================
266
267/// Running aggregate per relevancy metric. Holds both the all-time
268/// running mean and a bounded sliding window so progress views can
269/// show recent trend alongside the cumulative average.
270pub struct RunningAgg {
271    /// Sum of every score ever recorded (for all-time mean).
272    pub total_sum: f64,
273    /// Count of scores recorded (for all-time mean).
274    pub total_count: u64,
275    /// Recent scores, newest at the back. Capped at `window_size`.
276    pub window: std::collections::VecDeque<f64>,
277    /// Upper bound on `window` length.
278    pub window_size: usize,
279}
280
281impl RunningAgg {
282    pub fn new(window_size: usize) -> Self {
283        Self {
284            total_sum: 0.0,
285            total_count: 0,
286            window: std::collections::VecDeque::with_capacity(window_size),
287            window_size,
288        }
289    }
290
291    pub fn record(&mut self, score: f64) {
292        self.total_sum += score;
293        self.total_count += 1;
294        if self.window.len() == self.window_size {
295            self.window.pop_front();
296        }
297        self.window.push_back(score);
298    }
299
300    pub fn window_mean(&self) -> f64 {
301        if self.window.is_empty() {
302            0.0
303        } else {
304            self.window.iter().sum::<f64>() / self.window.len() as f64
305        }
306    }
307
308    pub fn total_mean(&self) -> f64 {
309        if self.total_count == 0 {
310            0.0
311        } else {
312            self.total_sum / self.total_count as f64
313        }
314    }
315}
316
317/// Default size of the moving-average window. Chosen to match the
318/// common recall@10 "last 10" semantic the user's workloads expect.
319pub const DEFAULT_RECALL_WINDOW: usize = 10;
320
321/// Live snapshot of a relevancy metric: window mean, all-time mean,
322/// how many scores have been recorded, and the current window size.
323#[derive(Debug, Clone)]
324pub struct RelevancyLive {
325    pub name: String,
326    pub window_mean: f64,
327    pub total_mean: f64,
328    pub total_count: u64,
329    pub window_len: usize,
330}
331
332/// Metrics for result validation, shared across fibers.
333pub struct ValidationMetrics {
334    pub validations_passed: AtomicU64,
335    pub validations_failed: AtomicU64,
336    /// Scored cycles whose ground-truth row held no neighbor at all
337    /// (every entry within `k` a sentinel). Such a row has no
338    /// attainable recall, so it adds nothing to `recall_attainable`;
339    /// this counts how many there were.
340    pub relevancy_empty_rows: AtomicU64,
341    /// Per-function lossless f64 statistics accumulators for relevancy scores.
342    /// Exact precision — no quantization, no bucket rounding.
343    pub relevancy_stats: HashMap<String, nmbrs_metrics::summaries::f64stats::F64Stats>,
344    /// Live aggregates (moving-window + all-time) per relevancy metric.
345    /// These read non-destructively, so progress views can sample them
346    /// every frame without disturbing the exact-precision stats above.
347    pub running_aggregates: HashMap<String, std::sync::Mutex<RunningAgg>>,
348    /// The cells the same measurements are also recorded in, when the
349    /// op places them by dimension (`cell:` on the op). `None` on a
350    /// cell's own metrics and on an op that declares no placement.
351    pub cells: Option<Arc<crate::op_cells::OpCells>>,
352}
353
354impl ValidationMetrics {
355    /// Create metrics for the given relevancy functions.
356    ///
357    /// The metric family name is the bare function name
358    /// (`recall`, `precision`, `f1`, …) — `k` and `r` are
359    /// carried as labels rather than baked into the
360    /// family identifier. This collapses every per-`k`
361    /// variant into a single family that consumers can
362    /// query with `recall{k="10",r="10"}` instead of the
363    /// awkward `recall_at_10` synthesised name. `r`
364    /// defaults to `k` when the relevancy config doesn't
365    /// declare it (`r:` was unset → first-k semantics).
366    pub fn new(labels: &Labels, functions: &[RelevancyFn], k: usize, r: Option<usize>) -> Self {
367        let r_value = r.unwrap_or(k);
368        let stats_labels = labels
369            .with("k", k.to_string())
370            .with("r", r_value.to_string());
371        let mut stats = HashMap::new();
372        let mut running = HashMap::new();
373        for func in functions {
374            let metric_name = func.metric_name().to_string();
375            stats.insert(
376                metric_name.clone(),
377                nmbrs_metrics::summaries::f64stats::F64Stats::new(
378                    stats_labels.with("name", &metric_name),
379                ),
380            );
381            running.insert(
382                metric_name.clone(),
383                std::sync::Mutex::new(RunningAgg::new(DEFAULT_RECALL_WINDOW)),
384            );
385        }
386        Self {
387            validations_passed: AtomicU64::new(0),
388            validations_failed: AtomicU64::new(0),
389            relevancy_empty_rows: AtomicU64::new(0),
390            relevancy_stats: stats,
391            running_aggregates: running,
392            cells: None,
393        }
394    }
395
396    /// Create metrics with no relevancy functions (assertions only).
397    pub fn assertions_only() -> Self {
398        Self {
399            validations_passed: AtomicU64::new(0),
400            validations_failed: AtomicU64::new(0),
401            relevancy_empty_rows: AtomicU64::new(0),
402            relevancy_stats: HashMap::new(),
403            running_aggregates: HashMap::new(),
404            cells: None,
405        }
406    }
407
408    /// Record a relevancy score for a named function. Updates both the
409    /// lossless stats accumulator and the live running aggregate.
410    pub fn record_relevancy(&self, metric_name: &str, score: f64) {
411        if let Some(stats) = self.relevancy_stats.get(metric_name) {
412            stats.record(score);
413        }
414        if let Some(agg) = self.running_aggregates.get(metric_name) {
415            let mut a = agg.lock().unwrap_or_else(|e| e.into_inner());
416            a.record(score);
417        }
418    }
419
420    /// Snapshot all live relevancy aggregates without disturbing the
421    /// accumulators. Safe to call every frame from the progress thread.
422    pub fn live_snapshot(&self) -> Vec<RelevancyLive> {
423        let mut out = Vec::with_capacity(self.running_aggregates.len());
424        for (name, agg) in &self.running_aggregates {
425            let a = agg.lock().unwrap_or_else(|e| e.into_inner());
426            out.push(RelevancyLive {
427                name: name.clone(),
428                window_mean: a.window_mean(),
429                total_mean: a.total_mean(),
430                total_count: a.total_count,
431                window_len: a.window.len(),
432            });
433        }
434        out.sort_by(|x, y| x.name.cmp(&y.name));
435        out
436    }
437
438    /// Get pass count.
439    pub fn passed(&self) -> u64 {
440        self.validations_passed.load(Ordering::Relaxed)
441    }
442
443    /// Get fail count.
444    pub fn failed(&self) -> u64 {
445        self.validations_failed.load(Ordering::Relaxed)
446    }
447
448    /// Scored cycles whose ground-truth row held no neighbor.
449    pub fn empty_rows(&self) -> u64 {
450        self.relevancy_empty_rows.load(Ordering::Relaxed)
451    }
452}
453
454// =========================================================================
455// ValidatingDispenser
456// =========================================================================
457
458/// Op dispenser wrapper that validates results after execution.
459///
460/// Applied only to templates that declare `verify:` or `relevancy:`
461/// blocks. Zero overhead for templates without validation.
462pub struct ValidatingDispenser {
463    inner: Arc<dyn OpDispenser>,
464    assertions: Vec<AssertionSpec>,
465    relevancy: Option<RelevancyConfig>,
466    /// Pre-stripped wire name for the relevancy `expected`
467    /// binding. The workload author writes either
468    /// `expected: ground_truth` (bare) or `expected: "{ground_truth}"`
469    /// (text-template legacy form, the braces are stripped at
470    /// wrap-time). Cycle-time reads go through
471    /// `ctx.wires.get(&expected_wire_name)` for a typed,
472    /// snapshot-free value — same canonical-scope contract the
473    /// MetricsDispenser uses. None when no `relevancy:` block.
474    expected_wire_name: Option<String>,
475    /// SRD-109 Part 3 — pre-parsed projection for `actual:` when
476    /// it names a result-binding path entry on this op (the
477    /// `results:` interface delivery). The validator evaluates it
478    /// directly from the op result: the `result` wrapper sits
479    /// OUTSIDE validation in the cascade, so its wire write lands
480    /// after this layer reads.
481    actual_projection: Option<ActualProjection>,
482    /// The admission check (SRD-115 §4.8), when the op declares one.
483    admission: Option<crate::admission::AdmissionConfig>,
484    /// The projection for the admission check's own `actual:`, built
485    /// as `actual_projection` is for relevancy's.
486    admission_projection: Option<ActualProjection>,
487    metrics: Arc<ValidationMetrics>,
488    /// The op's own cells, when it declares `cell:`: each cycle's
489    /// scores and outcome are recorded in the cycle's cell as well as
490    /// in `metrics`.
491    cells: Option<Arc<crate::op_cells::OpCells>>,
492    /// If true, assertion failures become ExecutionError::Op.
493    strict: bool,
494}
495
496/// Pre-parsed `actual:` projection: the result-binding path plus
497/// the interface-declared type (when the wire fills an
498/// `abstract: results:` contract).
499struct ActualProjection {
500    segs: Vec<crate::wrappers::result::PathSeg>,
501    target: Option<polydat::ast::PortType>,
502}
503
504/// Result of [`ValidatingDispenser::wrap`]: the (possibly-wrapped)
505/// dispenser plus the live [`ValidationMetrics`] handle when a
506/// `relevancy:` block was declared (`None` otherwise).
507type WrappedDispenser = (Arc<dyn OpDispenser>, Option<Arc<ValidationMetrics>>);
508
509impl ValidatingDispenser {
510    /// Wrap a dispenser with validation, registering the relevancy
511    /// `expected` binding into the supplied scope fixture.
512    ///
513    /// Returns the inner dispenser unchanged if none of `verify:`,
514    /// `relevancy:` and `admission:` is declared.
515    pub fn wrap(
516        inner: Arc<dyn OpDispenser>,
517        template: &nmbrs_workload::model::ParsedOp,
518        labels: &Labels,
519        program: Option<&polydat::kernel::PolydatProgram>,
520        fx: &mut crate::fixture::ScopeFixture,
521    ) -> Result<WrappedDispenser, String> {
522        Self::wrap_in_cells(inner, template, labels, program, fx, None)
523    }
524
525    /// As [`Self::wrap`], for an op that places its measurements in
526    /// cells (`cell:` on the op): every score and outcome is recorded
527    /// in the cycle's cell of `cells` as well as in the op's totals.
528    pub fn wrap_in_cells(
529        inner: Arc<dyn OpDispenser>,
530        template: &nmbrs_workload::model::ParsedOp,
531        labels: &Labels,
532        program: Option<&polydat::kernel::PolydatProgram>,
533        fx: &mut crate::fixture::ScopeFixture,
534        cells: Option<Arc<crate::op_cells::OpCells>>,
535    ) -> Result<WrappedDispenser, String> {
536        // SRD-68 Push 5c-cleanup: validation wrapper does its own
537        // construction-time resolution of `{name}` placeholders
538        // in op.params against the dispenser's canonical kernel.
539        // This replaces the legacy `resolve_placeholders_in_params_only`
540        // bulk pass at the executor layer — each wrapper now
541        // resolves against its own dispenser's canonical kernel
542        // rather than a shared activity-layer parent. Per-cycle
543        // binding names (e.g. `relevancy.expected = "{ground_truth}"`)
544        // pass through unchanged; the wrapper registers them on
545        // the fixture for cycle-time pulls below.
546        let template_owned: nmbrs_workload::model::ParsedOp;
547        let canonical_kernel = inner.canonical_kernel();
548        let template = if let Some(canonical) = &canonical_kernel {
549            let mut t = template.clone();
550            crate::scope::resolve_placeholders_in_op_params(&mut t, canonical.as_ref())?;
551            template_owned = t;
552            &template_owned
553        } else {
554            template
555        };
556        let assertions = parse_assertions(template);
557        // Bare wire-name forms in `k:` / `r:` resolve against the
558        // canonical kernel at wrap time (one-shot, same as the
559        // pre-existing `{k}` text-template substitution). The
560        // canonical kernel reads as a `WireSource` through
561        // `KernelWires` (SRD-68 Push 1); no per-cycle freshness because
562        // k / r are phase-constants by contract.
563        let canonical_wires = canonical_kernel
564            .as_ref()
565            .map(|k| crate::wires::KernelWires(k.as_ref()));
566        let wires_for_parse: Option<&dyn WireSource> =
567            canonical_wires.as_ref().map(|w| w as &dyn WireSource);
568        let relevancy = parse_relevancy(template, program, wires_for_parse)?;
569        let admission = crate::admission::parse_admission(template)?;
570        let strict = template.params.get("strict").map_or(Ok(false), |v| {
571            nmbrs_workload::boolean::json_bool("strict", v)
572        })?;
573
574        if assertions.is_empty() && relevancy.is_none() && admission.is_none() {
575            return Ok((inner, None));
576        }
577
578        // Validate at wrap-time that the relevancy `expected`
579        // binding exists on the op-template kernel — surfacing
580        // missing-wire diagnostics before any cycle runs. The
581        // returned PullHandle is unused (cycle-time reads go
582        // through ctx.wires.get on the bare wire name), so we
583        // only keep the name; same canonical-scope contract as
584        // the post-SRD-68 MetricsDispenser.
585        //
586        // Tolerate either `expected: ground_truth` (bare, the
587        // canonical post-refactor shape) or `expected: "{ground_truth}"`
588        // (the legacy text-template form — braces strip).
589        let expected_wire_name = match &relevancy {
590            Some(cfg) => {
591                let name = cfg
592                    .expected_binding
593                    .trim_matches(|c| c == '{' || c == '}')
594                    .to_string();
595                fx.register_pull(&name).map_err(|e| {
596                    format!("op '{op}' relevancy.expected: {e}", op = template.name,)
597                })?;
598                Some(name)
599            }
600            None => None,
601        };
602        // The wires the admitted-row count and the admitted list are
603        // read from each cycle: missing ones surface here, before any
604        // cycle runs.
605        if let Some(name) = relevancy.as_ref().and_then(|c| c.admitted_binding.as_ref()) {
606            fx.register_pull(name)
607                .map_err(|e| format!("op '{op}' relevancy.admitted: {e}", op = template.name))?;
608        }
609        if let Some(cfg) = &admission {
610            let wire = &cfg.admitted_wire;
611            crate::admission::require_admitted_rows(
612                &template.name,
613                wire,
614                program.and_then(|p| p.output_port_type(wire).or_else(|| p.input_port_type(wire))),
615            )?;
616            fx.register_pull(&cfg.admitted_wire)
617                .map_err(|e| format!("op '{op}' admission.admitted: {e}", op = template.name))?;
618        }
619
620        if let (Some(cells), Some(config)) = (&cells, &relevancy) {
621            cells.set_relevancy(&config.functions, config.k, config.r);
622        }
623        let mut totals = match &relevancy {
624            Some(config) => ValidationMetrics::new(labels, &config.functions, config.k, config.r),
625            None => ValidationMetrics::assertions_only(),
626        };
627        totals.cells = cells.clone();
628        let metrics = Arc::new(totals);
629
630        // SRD-109 Part 3 — when `actual:` names a result-binding
631        // path entry on this op, pre-parse the projection so the
632        // per-cycle read evaluates it directly from the result
633        // body (see the `actual_projection` field doc for why the
634        // wire write can't be read from this layer).
635        let actual_projection = match &relevancy {
636            Some(cfg) => actual_projection_for(template, "relevancy", &cfg.actual_field)?,
637            None => None,
638        };
639        let admission_projection = match &admission {
640            Some(cfg) => actual_projection_for(template, "admission", &cfg.actual_field)?,
641            None => None,
642        };
643
644        let wrapper = Arc::new(Self {
645            inner,
646            assertions,
647            relevancy,
648            expected_wire_name,
649            actual_projection,
650            admission,
651            admission_projection,
652            metrics: metrics.clone(),
653            cells,
654            strict,
655        });
656        Ok((wrapper, Some(metrics)))
657    }
658
659    /// The values an evaluation's `actual:` names, in result order.
660    ///
661    /// Resolution order (SRD-109 Part 3 / SRD-70): a result-binding
662    /// projection declared on this op, evaluated directly from the
663    /// result body (the `result` wrapper's wire write lands outside
664    /// this layer); then a live wire (captures and per-cycle bindings
665    /// are fresh here); then the legacy result-column walk for
666    /// workloads that predate the interface.
667    fn actual_values(
668        result: &OpResult,
669        ctx: &crate::fixture::ExecCtx<'_>,
670        field: &str,
671        projection: Option<&ActualProjection>,
672    ) -> Vec<i64> {
673        if let Some(proj) = projection {
674            let projected = result.body.as_ref().and_then(|b| {
675                crate::wrappers::result::evaluate_path_value(&b.to_json(), &proj.segs, proj.target)
676            });
677            return projected
678                .as_ref()
679                .map(resolve_expected_from_value)
680                .unwrap_or_default();
681        }
682        match ctx.wires.get(field) {
683            Some(v) if !matches!(v, polydat::ast::Value::None) => resolve_expected_from_value(&v),
684            _ => extract_actual_indices(result, field),
685        }
686    }
687}
688
689/// Pre-parse the projection for an evaluation's `actual:` when it
690/// names a result-binding path entry on this op (SRD-109 Part 3), so
691/// the per-cycle read evaluates it directly from the result body. See
692/// [`ValidatingDispenser::actual_projection`] for why the wire write
693/// cannot be read from this layer. `evaluation` names the block in
694/// the error.
695fn actual_projection_for(
696    template: &nmbrs_workload::model::ParsedOp,
697    evaluation: &str,
698    actual_field: &str,
699) -> Result<Option<ActualProjection>, String> {
700    let mut raw: Option<String> = None;
701    if let Some(spec) = template.result.as_ref() {
702        spec.walk_fragments(|frag| {
703            if let nmbrs_workload::model::ResultFragment::Named { name, source } = frag
704                && name == actual_field
705            {
706                let s = source.trim();
707                if s != "count" && s != "ok" && !s.contains('(') {
708                    raw = Some(s.to_string());
709                }
710            }
711        });
712    }
713    let Some(path) = raw else {
714        return Ok(None);
715    };
716    let segs = crate::wrappers::result::parse_path_expr(&path).map_err(|e| {
717        format!(
718            "op '{op}' {evaluation}.actual '{actual_field}': result binding path: {e}",
719            op = template.name,
720        )
721    })?;
722    let target = template
723        .abstract_interface
724        .as_ref()
725        .and_then(|i| i.results.get(actual_field))
726        .copied();
727    Ok(Some(ActualProjection { segs, target }))
728}
729
730impl WrappingDispenser for ValidatingDispenser {}
731
732impl OpDispenser for ValidatingDispenser {
733    /// Expose the wrapped dispenser so `describe()` can
734    /// walk through this layer to reach the adapter
735    /// (raw / prepared / batch). Without this override,
736    /// the default trait method returns `None`, the
737    /// describe walk stops here, and the error-context
738    /// dump loses the CQL statement text.
739    fn inner_dispenser(&self) -> Option<&dyn OpDispenser> {
740        Some(self.inner.as_ref())
741    }
742
743    fn execute<'a>(
744        &'a self,
745        cycle: u64,
746        ctx: &'a crate::fixture::ExecCtx<'a>,
747    ) -> std::pin::Pin<
748        Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
749    > {
750        Box::pin(async move {
751            let result = self.inner.execute(cycle, ctx).await?;
752
753            // Phase 1: Field assertions. Track failed predicates
754            // so the strict-mode error can say which check failed
755            // (especially helpful for body-level checks like
756            // `min_rows: 1` where the user gets clear feedback that
757            // the result was empty rather than a generic "validation
758            // failed" message).
759            let mut failed_assertions: Vec<String> = Vec::new();
760            for assertion in &self.assertions {
761                if !assertion.check(&result) {
762                    failed_assertions.push(describe_assertion_failure(assertion, &result));
763                }
764            }
765
766            // The cycle's cell, when the op places its measurements:
767            // read once, after the op ran, for everything recorded below.
768            let cell = match &self.cells {
769                Some(cells) => Some(cells.resolve(ctx.wires, cycle)?),
770                None => None,
771            };
772
773            // Phase 2: Relevancy metrics
774            if let Some(config) = &self.relevancy {
775                let actual_ordered = Self::actual_values(
776                    &result,
777                    ctx,
778                    &config.actual_field,
779                    self.actual_projection.as_ref(),
780                );
781                // Single read path: ground truth comes from
782                // `ctx.wires.get(name)` — a live, snapshot-free read
783                // through the per-fiber op-template kernel. The wire
784                // name was validated at wrap-time. Same canonical-scope
785                // contract MetricsDispenser uses.
786                let name = self.expected_wire_name.as_deref().expect(
787                    "ValidatingDispenser invariant violated: relevancy is \
788                     configured but expected_wire_name was not stored. \
789                     Construct via ValidatingDispenser::wrap.",
790                );
791                let raw_value = ctx.wires.get(name);
792                let expected_raw = raw_value
793                    .as_ref()
794                    .map(resolve_expected_from_value)
795                    .unwrap_or_default();
796
797                // A typed row of indices that is empty is a query with
798                // no neighbors to find: its predicate admits nothing
799                // (SRD-115 §4.5). It is counted below, not refused.
800                // Anything else that yields no indices (a missing
801                // wire, text that does not parse) is a workload
802                // defect and a hard error.
803                let is_index_row = matches!(
804                    raw_value,
805                    Some(polydat::ast::Value::VecI32(_) | polydat::ast::Value::VecI64(_))
806                );
807                if expected_raw.is_empty() && !is_index_row {
808                    let available: Vec<String> = ctx.wires.names().collect();
809                    return Err(ExecutionError::Op(crate::adapter::AdapterError {
810                        error_name: "relevancy_error".into(),
811                        message: format!(
812                            "relevancy: no ground truth for '{name}'. \
813                             Available wires: {available:?}. \
814                             Ensure the binding exists in the Polydat program.",
815                        ),
816                        retryable: false,
817                    }));
818                }
819                if actual_ordered.is_empty() && result.body.is_some() {
820                    // Log on first occurrence only
821                    if self.metrics.passed() + self.metrics.failed() == 0 {
822                        let indent = crate::scene_tree::running_phase_indent();
823                        crate::observer::log(
824                            crate::observer::LogLevel::Warn,
825                            &format!(
826                                "{indent}relevancy: no values extracted for field '{}' from result",
827                                config.actual_field
828                            ),
829                        );
830                        if let Some(body) = &result.body {
831                            let preview =
832                                serde_json::to_string(&body.to_json()).unwrap_or_default();
833                            crate::observer::log(
834                                crate::observer::LogLevel::Warn,
835                                &format!(
836                                    "{indent}  result preview: {}",
837                                    &preview[..preview.len().min(300)]
838                                ),
839                            );
840                        }
841                    }
842                }
843
844                // k-recall@r contract: when the workload declares
845                // `r:` in the relevancy block, it has asserted
846                // that the database query was sized to retrieve
847                // exactly that many results. Mismatch is a
848                // correctness signal — the recall measurement is
849                // only meaningful if the retrieval window matches
850                // what the operator asked for. Fail the op rather
851                // than silently producing a recall figure for an
852                // off-by-one retrieval window.
853                //
854                // Under a predicate the window is capped by what
855                // the predicate admits (SRD-115 §4.5): a target
856                // cannot return more rows than qualify, so an op
857                // that names its `admitted:` count must return
858                // `min(r, admitted)` rows. Fewer than that is a
859                // target dropping rows that qualify; more is a
860                // target returning rows that do not.
861                if let Some(r) = config.r {
862                    let admitted = match &config.admitted_binding {
863                        None => None,
864                        Some(wire) => {
865                            let count = ctx
866                                .wires
867                                .get(wire)
868                                .and_then(value_to_u64_for_count)
869                                .ok_or_else(|| {
870                                    ExecutionError::Op(crate::adapter::AdapterError {
871                                        error_name: "relevancy_error".into(),
872                                        message: format!(
873                                            "relevancy: `admitted: {wire}` did not yield a \
874                                             row count at cycle {cycle}",
875                                        ),
876                                        retryable: false,
877                                    })
878                                })?;
879                            Some(count)
880                        }
881                    };
882                    let required = relevancy::required_rows(r, admitted);
883                    if actual_ordered.len() != required {
884                        let message = match admitted {
885                            None => format!(
886                                "relevancy: expected exactly r={r} results from \
887                                 retrieval, got {} (k-recall@r contract). Either \
888                                 size the query LIMIT to {r}, or remove the `r:` \
889                                 declaration to fall back to first-k semantics.",
890                                actual_ordered.len(),
891                            ),
892                            Some(n) => format!(
893                                "relevancy: expected exactly {required} results from \
894                                 retrieval, got {} (k-recall@r contract: r={r}, and \
895                                 the predicate admits {n} rows, so min(r, admitted) = \
896                                 {required}).",
897                                actual_ordered.len(),
898                            ),
899                        };
900                        return Err(ExecutionError::Op(crate::adapter::AdapterError {
901                            error_name: "relevancy_error".into(),
902                            message,
903                            retryable: false,
904                        }));
905                    }
906                }
907
908                // k-recall@r semantics: the recall metric counts
909                // how many of the *top-k* ground-truth items appear
910                // anywhere in the *top-r* returned, divided by k.
911                // Truncating `actual` to `k` (the pre-`r:` shape)
912                // computes top-k ∩ top-k instead, which collapses
913                // to ~K/R when the server post-filters and the
914                // returned top-K rarely contains true neighbours —
915                // that's the "stuck at 0.1" symptom for r=10×k.
916                // When `r` is unset, fall back to k (the legacy
917                // "first-k" behaviour).
918                //
919                // `expected` is scored as given. A row with fewer
920                // than k neighbors arrives short when the workload
921                // binds the dataset layer's live neighbors
922                // (SRD-115 §4.5); its length is the live depth.
923                let r_window = config.r.unwrap_or(config.k);
924                let expected_sorted = relevancy::truncate_and_sort(&expected_raw, config.k);
925                let actual_sorted = relevancy::truncate_and_sort(&actual_ordered, r_window);
926                if expected_sorted.is_empty() {
927                    self.metrics
928                        .relevancy_empty_rows
929                        .fetch_add(1, Ordering::Relaxed);
930                    if let Some(cell) = &cell {
931                        cell.validation()
932                            .relevancy_empty_rows
933                            .fetch_add(1, Ordering::Relaxed);
934                    }
935                }
936
937                for func in &config.functions {
938                    // No score: this function has nothing to measure
939                    // on this row (attainable recall where no
940                    // neighbor exists). The row is counted above.
941                    let Some(score) =
942                        func.compute(&expected_sorted, &actual_sorted, &actual_ordered, config.k)
943                    else {
944                        continue;
945                    };
946                    self.metrics.record_relevancy(func.metric_name(), score);
947                    if let Some(cell) = &cell {
948                        cell.validation()
949                            .record_relevancy(func.metric_name(), score);
950                    }
951                    // Generic observability point: a relevancy
952                    // score has been computed. The trace fires
953                    // for ANY relevancy config (recall, precision,
954                    // F1, MRR, AP) — no knowledge of the
955                    // workload's domain. Labels carry whatever
956                    // dimensions the surrounding scope tree
957                    // pushed (phase, profile, optimize_for, k,
958                    // r), so `--trace=` routing/filtering is
959                    // entirely config-driven.
960                    if crate::observer::trace_enabled() {
961                        let intersect =
962                            crate::relevancy::intersection_count(&expected_sorted, &actual_sorted);
963                        let stats_labels = self
964                            .metrics
965                            .relevancy_stats
966                            .get(func.metric_name())
967                            .map(|s| s.labels().clone())
968                            .unwrap_or_default();
969                        crate::observer::trace(
970                            &stats_labels,
971                            &format!(
972                                "event=relevancy.score cycle={cycle} \
973                                 fn={func} k={k} r={r} \
974                                 gt_card={gt} actual_card={ac} \
975                                 intersect={inter} score={score:.6}",
976                                func = func.metric_name(),
977                                k = config.k,
978                                r = config.r.unwrap_or(config.k),
979                                gt = expected_sorted.len(),
980                                ac = actual_sorted.len(),
981                                inter = intersect,
982                            ),
983                        );
984                    }
985                }
986            }
987
988            // Phase 3: Admission. Every returned row must be one the
989            // cycle's predicate admits (SRD-115 §4.8). A violation is
990            // a failed validation like a failed assertion: counted,
991            // and an op error under `strict`.
992            if let Some(config) = &self.admission {
993                let returned = Self::actual_values(
994                    &result,
995                    ctx,
996                    &config.actual_field,
997                    self.admission_projection.as_ref(),
998                );
999                let wire = &config.admitted_wire;
1000                let admitted = ctx.wires.get(wire).ok_or_else(|| {
1001                    ExecutionError::Op(crate::adapter::AdapterError {
1002                        error_name: "admission_error".into(),
1003                        message: format!(
1004                            "admission: no admitted rows for '{wire}' at cycle {cycle}"
1005                        ),
1006                        retryable: false,
1007                    })
1008                })?;
1009                match crate::admission::first_not_admitted(&returned, &admitted) {
1010                    Ok(None) => {}
1011                    Ok(Some(key)) => failed_assertions.push(format!(
1012                        "admission: cycle {cycle} returned row {key}, which its predicate \
1013                         does not admit ({} rows returned)",
1014                        returned.len(),
1015                    )),
1016                    Err(why) => {
1017                        return Err(ExecutionError::Op(crate::adapter::AdapterError {
1018                            error_name: "admission_error".into(),
1019                            message: format!("admission: `admitted: {wire}` {why}"),
1020                            retryable: false,
1021                        }));
1022                    }
1023                }
1024            }
1025            let all_pass = failed_assertions.is_empty();
1026
1027            if all_pass {
1028                self.metrics
1029                    .validations_passed
1030                    .fetch_add(1, Ordering::Relaxed);
1031                if let Some(cell) = &cell {
1032                    cell.validation()
1033                        .validations_passed
1034                        .fetch_add(1, Ordering::Relaxed);
1035                }
1036            } else {
1037                self.metrics
1038                    .validations_failed
1039                    .fetch_add(1, Ordering::Relaxed);
1040                if let Some(cell) = &cell {
1041                    cell.validation()
1042                        .validations_failed
1043                        .fetch_add(1, Ordering::Relaxed);
1044                }
1045                if self.strict {
1046                    return Err(ExecutionError::Op(crate::adapter::AdapterError {
1047                        error_name: "validation_failed".into(),
1048                        message: format!(
1049                            "result validation failed (strict mode): {}",
1050                            failed_assertions.join("; "),
1051                        ),
1052                        retryable: false,
1053                    }));
1054                }
1055            }
1056
1057            Ok(result)
1058        })
1059    }
1060}
1061
1062// =========================================================================
1063// YAML parsing
1064// =========================================================================
1065
1066/// Render a one-line description of an assertion that failed
1067/// against `result`. Used by the strict-mode error message so
1068/// the workload author sees exactly which predicate fired,
1069/// what the resolved field value was (or why it couldn't be
1070/// resolved), AND the body excerpt — without all three the
1071/// operator has to manually re-run with logging cranked up
1072/// just to figure out what came back.
1073///
1074/// The body excerpt is suppressed when the body is `None` —
1075/// observed_field_repr's "<no body returned by op>" already
1076/// communicates that case, and a trailing `; body: <no body>`
1077/// duplicates the same signal.
1078fn describe_assertion_failure(assertion: &AssertionSpec, result: &OpResult) -> String {
1079    let body_tail = match &result.body {
1080        Some(_) => format!("; body: {}", body_excerpt(result)),
1081        None => String::new(),
1082    };
1083    let observed_repr = observed_field_repr(&assertion.field, result);
1084    match &assertion.predicate {
1085        AssertionPredicate::MinRows(n) => {
1086            let got = result.body.as_ref().map(|b| b.element_count()).unwrap_or(0);
1087            format!("min_rows: expected ≥{n}, got {got}{body_tail}")
1088        }
1089        AssertionPredicate::Eq(expected) => format!(
1090            "field '{}' eq '{}' failed (observed: {observed_repr}){body_tail}",
1091            assertion.field, expected
1092        ),
1093        AssertionPredicate::NotNull => format!(
1094            "field '{}' must not be null (observed: {observed_repr}){body_tail}",
1095            assertion.field
1096        ),
1097        AssertionPredicate::IsNull => format!(
1098            "field '{}' must be null (observed: {observed_repr}){body_tail}",
1099            assertion.field
1100        ),
1101        AssertionPredicate::Gte(t) => format!(
1102            "field '{}' >= {t} failed (observed: {observed_repr}){body_tail}",
1103            assertion.field
1104        ),
1105        AssertionPredicate::MalformedBound { key, raw } => format!(
1106            "field '{}': `{key}: {raw}` is not a number — a numeric bound \
1107                 must be a number (`{key}: 5`) or a string holding one \
1108                 (`{key}: \"5\"`). If that is a `{{placeholder}}`, it did not \
1109                 resolve.",
1110            assertion.field
1111        ),
1112        AssertionPredicate::Lte(t) => format!(
1113            "field '{}' <= {t} failed (observed: {observed_repr}){body_tail}",
1114            assertion.field
1115        ),
1116        AssertionPredicate::Contains(sub) => format!(
1117            "field '{}' contains '{}' failed (observed: {observed_repr}){body_tail}",
1118            assertion.field, sub
1119        ),
1120    }
1121}
1122
1123/// Best-effort description of the observed value of a field.
1124/// Returns the JSON-extracted value (string-quoted if it is a
1125/// JSON string) when the field is addressable; otherwise a
1126/// diagnostic that surfaces *why* the field couldn't be read,
1127/// so the operator can tell whether to fix the field name or
1128/// the upstream response shape:
1129///
1130/// - `<no body returned by op — verify clause cannot read
1131///   fields>` when the op produced no body at all. Often a
1132///   sign the verify clause is structurally wrong for this
1133///   op kind (DDL, flush, anything that doesn't return rows).
1134/// - `<field absent; body keys: [a, b, c]>` when the body is
1135///   a JSON object but doesn't contain the requested field —
1136///   shows what IS there so the author can pick a real name.
1137/// - `<field absent; body is a JSON array of N elements>`
1138///   when the body is an array (`field:` addresses the first
1139///   element by convention; if the array is empty there's
1140///   nothing to address).
1141/// - `<not-json: {short repr}>` when the body parses to a
1142///   scalar or non-addressable JSON value (e.g. an HTML error
1143///   page or a plain-text response). Shows the first chars
1144///   so the operator can recognise the upstream's actual
1145///   payload.
1146/// - The extracted value otherwise, truncated for log
1147///   readability.
1148fn observed_field_repr(field: &str, result: &OpResult) -> String {
1149    let Some(body) = &result.body else {
1150        return "<no body returned by op — verify clause cannot read fields>".to_string();
1151    };
1152    let json = body.to_json();
1153    if let Some(v) = extract_field_from_json(&json, field) {
1154        let repr = match v {
1155            serde_json::Value::String(s) => format!("\"{s}\""),
1156            other => other.to_string(),
1157        };
1158        return truncate_for_message(&repr, 160);
1159    }
1160    // Field couldn't be resolved. The "why" guides the fix —
1161    // either the field name is wrong (the body has different
1162    // keys) or the response shape is wrong (not a structured
1163    // JSON object at all).
1164    match &json {
1165        serde_json::Value::Object(map) => {
1166            let keys: Vec<&str> = map.keys().map(|s| s.as_str()).collect();
1167            if keys.is_empty() {
1168                "<field absent; body is an empty JSON object>".to_string()
1169            } else {
1170                format!("<field absent; body keys: {keys:?}>")
1171            }
1172        }
1173        serde_json::Value::Array(arr) => {
1174            format!(
1175                "<field absent; body is a JSON array of {} element{}>",
1176                arr.len(),
1177                if arr.len() == 1 { "" } else { "s" },
1178            )
1179        }
1180        serde_json::Value::Null => "<field absent; body is JSON null>".to_string(),
1181        other => {
1182            let short = truncate_for_message(&other.to_string(), 80);
1183            format!("<not-json: {short}>")
1184        }
1185    }
1186}
1187
1188/// A short excerpt of the response body, embedded in
1189/// assertion-failure messages so the operator can see what
1190/// actually came back. Caller is responsible for skipping the
1191/// excerpt when `result.body` is `None` — see
1192/// `describe_assertion_failure`.
1193fn body_excerpt(result: &OpResult) -> String {
1194    let Some(body) = &result.body else {
1195        return "<no body>".to_string();
1196    };
1197    truncate_for_message(&body.to_text(), 512)
1198}
1199
1200/// Truncate a string to `max` chars with an ellipsis tail so
1201/// failure messages stay readable. Avoids splitting inside a
1202/// UTF-8 codepoint by using `char_indices`.
1203fn truncate_for_message(s: &str, max: usize) -> String {
1204    if s.chars().count() <= max {
1205        return s.to_string();
1206    }
1207    let cut: String = s.chars().take(max.saturating_sub(1)).collect();
1208    format!("{cut}…")
1209}
1210
1211/// Parse `verify:` block from a ParsedOp's params.
1212///
1213/// Expected YAML structure:
1214/// ```yaml
1215/// verify:
1216///   - field: name
1217///     is: not_null
1218///   - field: balance
1219///     gte: 0
1220///   - field: data
1221///     eq: "expected_value"
1222///   - min_rows: 1     # body-level: result must have ≥1 row
1223/// ```
1224///
1225/// Most predicates target a named field within each result row
1226/// and require `field:`. The body-level `min_rows:` predicate is
1227/// the exception — it asserts on the result's row count rather
1228/// than any specific field, so it has no `field:` key.
1229/// A `gte:` / `lte:` threshold, from either a JSON number or a string
1230/// holding one.
1231///
1232/// YAML makes the string form easy to reach by accident — quoting, or a
1233/// `{placeholder}` that substitutes to text — and the two spellings plainly
1234/// mean the same bound, so both are accepted. What is NOT accepted is
1235/// anything else: `None` here becomes a
1236/// [`AssertionPredicate::MalformedBound`] that fails loudly, rather than the
1237/// old silent `0.0`.
1238fn numeric_bound(v: &serde_json::Value) -> Option<f64> {
1239    v.as_f64()
1240        .or_else(|| v.as_str().and_then(|s| s.trim().parse::<f64>().ok()))
1241}
1242
1243fn parse_assertions(template: &nmbrs_workload::model::ParsedOp) -> Vec<AssertionSpec> {
1244    let Some(verify) = template.params.get("verify") else {
1245        return Vec::new();
1246    };
1247
1248    let Some(items) = verify.as_array() else {
1249        return Vec::new();
1250    };
1251
1252    let mut assertions = Vec::new();
1253    for item in items {
1254        let Some(obj) = item.as_object() else {
1255            continue;
1256        };
1257
1258        // Body-level predicates first: `min_rows: N` doesn't take
1259        // a `field:` because it asserts on the body's row count.
1260        if let Some(v) = obj.get("min_rows") {
1261            let n = v.as_u64().unwrap_or(0);
1262            assertions.push(AssertionSpec {
1263                field: String::new(), // ignored for MinRows
1264                predicate: AssertionPredicate::MinRows(n),
1265            });
1266            continue;
1267        }
1268
1269        let Some(field) = obj.get("field").and_then(|v| v.as_str()) else {
1270            continue;
1271        };
1272
1273        let predicate = if let Some(v) = obj.get("eq") {
1274            AssertionPredicate::Eq(json_value_as_string(v))
1275        } else if let Some(v) = obj.get("gte") {
1276            match numeric_bound(v) {
1277                Some(t) => AssertionPredicate::Gte(t),
1278                None => AssertionPredicate::MalformedBound {
1279                    key: "gte".into(),
1280                    raw: json_value_as_string(v),
1281                },
1282            }
1283        } else if let Some(v) = obj.get("lte") {
1284            match numeric_bound(v) {
1285                Some(t) => AssertionPredicate::Lte(t),
1286                None => AssertionPredicate::MalformedBound {
1287                    key: "lte".into(),
1288                    raw: json_value_as_string(v),
1289                },
1290            }
1291        } else if let Some(v) = obj.get("contains") {
1292            AssertionPredicate::Contains(json_value_as_string(v))
1293        } else if let Some(v) = obj.get("is") {
1294            match v.as_str().unwrap_or("").to_lowercase().as_str() {
1295                "not_null" | "notnull" => AssertionPredicate::NotNull,
1296                "null" => AssertionPredicate::IsNull,
1297                _ => continue,
1298            }
1299        } else {
1300            continue;
1301        };
1302
1303        assertions.push(AssertionSpec {
1304            field: field.to_string(),
1305            predicate,
1306        });
1307    }
1308    assertions
1309}
1310
1311/// Allowed sub-keys under `relevancy:`. Anything outside this
1312/// vocabulary is a hard error — silent acceptance of typos
1313/// (e.g. `relevency:`) is exactly the failure mode SRD-15 §
1314/// "Strict mode" rules out.
1315const RELEVANCY_VOCAB: &[&str] = &["actual", "expected", "k", "r", "admitted", "functions"];
1316
1317/// Parse `relevancy:` block from a ParsedOp's params.
1318///
1319/// **Strict.** Required fields (`actual`, `expected`) missing →
1320/// error. Unknown sub-keys → error. Non-numeric `k`/`r` → error.
1321/// Surviving `{name}` placeholders → error (they should already
1322/// have been resolved by the SRD-16 single read path before this
1323/// function runs).
1324///
1325/// Expected YAML structure:
1326/// ```yaml
1327/// relevancy:
1328///   actual: key
1329///   expected: "{ground_truth}"
1330///   k: 10                       # or "{k}" — resolved beforehand
1331///   r: 64                       # optional
1332///   admitted: admitted_count    # optional wire; requires r
1333///   functions: [recall, …]
1334/// ```
1335fn parse_relevancy(
1336    template: &nmbrs_workload::model::ParsedOp,
1337    _program: Option<&polydat::kernel::PolydatProgram>,
1338    wires: Option<&dyn WireSource>,
1339) -> Result<Option<RelevancyConfig>, String> {
1340    let Some(rel) = template.params.get("relevancy") else {
1341        return Ok(None);
1342    };
1343    let obj = rel.as_object().ok_or_else(|| {
1344        format!(
1345            "op '{}': relevancy: expected a mapping, got {kind}",
1346            template.name,
1347            kind = match rel {
1348                serde_json::Value::Null => "null",
1349                serde_json::Value::Bool(_) => "boolean",
1350                serde_json::Value::Number(_) => "number",
1351                serde_json::Value::String(_) => "string",
1352                serde_json::Value::Array(_) => "array",
1353                _ => "unknown",
1354            },
1355        )
1356    })?;
1357
1358    // Closed-vocabulary check.
1359    for k in obj.keys() {
1360        if !RELEVANCY_VOCAB.contains(&k.as_str()) {
1361            return Err(format!(
1362                "op '{op}' relevancy: unknown key '{k}'. Allowed: [{vocab}]",
1363                op = template.name,
1364                vocab = RELEVANCY_VOCAB.join(", "),
1365            ));
1366        }
1367    }
1368
1369    let actual_field = obj
1370        .get("actual")
1371        .and_then(|v| v.as_str())
1372        .ok_or_else(|| {
1373            format!(
1374                "op '{}' relevancy: missing required field 'actual' (string column name)",
1375                template.name,
1376            )
1377        })?
1378        .to_string();
1379    let expected_binding = obj
1380        .get("expected")
1381        .and_then(|v| v.as_str())
1382        .ok_or_else(|| {
1383            format!(
1384                "op '{}' relevancy: missing required field 'expected' (binding reference)",
1385                template.name,
1386            )
1387        })?
1388        .to_string();
1389
1390    let k_label = format!("op '{}' relevancy.k", template.name);
1391    let k = parse_count_param(obj.get("k"), &k_label, wires)?.ok_or_else(|| {
1392        format!(
1393            "op '{}' relevancy: missing required field 'k' (integer)",
1394            template.name,
1395        )
1396    })? as usize;
1397
1398    let r_label = format!("op '{}' relevancy.r", template.name);
1399    let r: Option<usize> = parse_count_param(obj.get("r"), &r_label, wires)?.map(|n| n as usize);
1400
1401    if let Some(rv) = r
1402        && rv < k
1403    {
1404        return Err(format!(
1405            "op '{op}' relevancy: r={rv} is smaller than k={k}; \
1406                 the k-recall@r contract requires r >= k",
1407            op = template.name,
1408        ));
1409    }
1410
1411    // `admitted:` names the wire that says how many rows the
1412    // cycle's predicate admits. It only ever relaxes the `r`
1413    // contract, so without `r:` it would be read and do nothing.
1414    let admitted_binding: Option<String> = match obj.get("admitted") {
1415        None => None,
1416        Some(v) => {
1417            let name = v
1418                .as_str()
1419                .map(|s| s.trim().trim_matches(|c| c == '{' || c == '}').trim())
1420                .filter(|s| is_bare_ident(s))
1421                .ok_or_else(|| {
1422                    format!(
1423                        "op '{op}' relevancy.admitted: expected the name of a wire \
1424                         holding the number of rows the predicate admits",
1425                        op = template.name,
1426                    )
1427                })?;
1428            if r.is_none() {
1429                return Err(format!(
1430                    "op '{op}' relevancy: `admitted: {name}` caps the retrieval window \
1431                     `r:`, and this op declares no `r:`. Declare `r:` or remove `admitted:`.",
1432                    op = template.name,
1433                ));
1434            }
1435            Some(name.to_string())
1436        }
1437    };
1438
1439    let functions: Vec<RelevancyFn> = match obj.get("functions") {
1440        None => vec![RelevancyFn::Recall],
1441        Some(serde_json::Value::Array(arr)) => {
1442            let mut out: Vec<RelevancyFn> = Vec::new();
1443            for (i, v) in arr.iter().enumerate() {
1444                let name = v.as_str().ok_or_else(|| {
1445                    format!(
1446                        "op '{op}' relevancy.functions[{i}]: expected a string, got {kind}",
1447                        op = template.name,
1448                        kind = match v {
1449                            serde_json::Value::Null => "null",
1450                            serde_json::Value::Bool(_) => "boolean",
1451                            serde_json::Value::Number(_) => "number",
1452                            serde_json::Value::Array(_) => "array",
1453                            serde_json::Value::Object(_) => "object",
1454                            _ => "unknown",
1455                        },
1456                    )
1457                })?;
1458                let func = RelevancyFn::parse(name).ok_or_else(|| {
1459                    format!(
1460                        "op '{op}' relevancy.functions[{i}]: unknown function '{name}'",
1461                        op = template.name,
1462                    )
1463                })?;
1464                out.push(func);
1465            }
1466            if out.is_empty() {
1467                return Err(format!(
1468                    "op '{op}' relevancy.functions: empty list — declare at least one \
1469                     function or remove the field to default to [recall]",
1470                    op = template.name,
1471                ));
1472            }
1473            out
1474        }
1475        Some(_) => {
1476            return Err(format!(
1477                "op '{op}' relevancy.functions: expected an array of strings",
1478                op = template.name,
1479            ));
1480        }
1481    };
1482
1483    Ok(Some(RelevancyConfig {
1484        actual_field,
1485        expected_binding,
1486        k,
1487        r,
1488        admitted_binding,
1489        functions,
1490    }))
1491}
1492
1493/// Parse a YAML count parameter (`k:` or `r:`) — strict.
1494/// Accepts only a JSON integer or a literal numeric string.
1495/// `{name}` placeholders are *not* resolved here: the SRD-16
1496/// single read path means every placeholder must already have
1497/// been resolved by
1498/// [`crate::scope::resolve_placeholders_in_op_params`] (called
1499/// from `ValidatingDispenser::wrap` against the dispenser's own
1500/// canonical kernel — SRD-68 Push 5c-cleanup). Surviving `{…}`
1501/// shapes are a workload bug and surface as `Err`. The caller
1502/// decides whether the parameter is required or optional —
1503/// `None` here means "absent," not "unresolvable."
1504fn parse_count_param(
1505    val: Option<&serde_json::Value>,
1506    field_label: &str,
1507    wires: Option<&dyn WireSource>,
1508) -> Result<Option<u64>, String> {
1509    let Some(v) = val else {
1510        return Ok(None);
1511    };
1512    if let Some(n) = v.as_u64() {
1513        return Ok(Some(n));
1514    }
1515    let s = match v.as_str() {
1516        Some(s) => s,
1517        None => {
1518            return Err(format!(
1519                "{field_label}: expected an integer or numeric string, got {kind}",
1520                kind = match v {
1521                    serde_json::Value::Null => "null",
1522                    serde_json::Value::Bool(_) => "boolean",
1523                    serde_json::Value::Array(_) => "array",
1524                    serde_json::Value::Object(_) => "object",
1525                    _ => "unsupported value",
1526                },
1527            ));
1528        }
1529    };
1530    let trimmed = s.trim();
1531    if trimmed.starts_with('{') && trimmed.ends_with('}') {
1532        return Err(format!(
1533            "{field_label}: '{trimmed}' was not resolved before parameter parsing — \
1534             this is a placeholder-resolution bug, not a config-time issue. The \
1535             single-read-path resolver should have substituted it from the kernel."
1536        ));
1537    }
1538    // Bare wire-name form: post-SRD-68 follow-up. When `k:` or `r:`
1539    // names a bare identifier and the canonical kernel knows it,
1540    // read the value at wrap time. Same one-shot evaluation as the
1541    // legacy `{k}` text-template form, but without the placeholder
1542    // wrapper. Numeric strings ("100") fall through to the parse
1543    // below — they're literals, not wire references.
1544    if let Some(wires) = wires
1545        && is_bare_ident(trimmed)
1546        && let Some(value) = wires.get(trimmed)
1547    {
1548        return value_to_u64_for_count(value)
1549            .ok_or_else(|| {
1550                format!(
1551                    "{field_label}: wire '{trimmed}' resolved but its value is not \
1552             coercible to a non-negative integer"
1553                )
1554            })
1555            .map(Some);
1556    }
1557    match trimmed.parse::<u64>() {
1558        Ok(n) => Ok(Some(n)),
1559        Err(_) => Err(format!(
1560            "{field_label}: '{trimmed}' is not a valid non-negative integer \
1561             (and not declared as a wire name on the op-template kernel)"
1562        )),
1563    }
1564}
1565
1566/// Predicate for a bare Polydat identifier (single ident-shaped token).
1567/// Inlined locally to avoid pulling the `crate::wires::is_bare_ident`
1568/// pub-but-unexported helper into this file's surface.
1569fn is_bare_ident(s: &str) -> bool {
1570    let mut chars = s.chars();
1571    match chars.next() {
1572        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
1573        _ => return false,
1574    }
1575    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
1576}
1577
1578/// Coerce a kernel `Value` to a non-negative integer suitable for
1579/// `k:` / `r:` count fields. U64 / F64 (non-negative) accepted;
1580/// other variants signal a type mismatch the caller surfaces.
1581pub(crate) fn value_to_u64_for_count(value: polydat::ast::Value) -> Option<u64> {
1582    use polydat::ast::Value;
1583    match value {
1584        Value::U64(n) => Some(n),
1585        Value::I64(n) => u64::try_from(n).ok(),
1586        Value::Str(s) => crate::runner::parse_count(&s),
1587        Value::F64(f) if f.is_finite() && f >= 0.0 => Some(f as u64),
1588        Value::Bool(true) => Some(1),
1589        Value::Bool(false) => Some(0),
1590        _ => None,
1591    }
1592}
1593
1594// =========================================================================
1595// Result extraction
1596// =========================================================================
1597
1598/// Extract integer indices from a result body for relevancy comparison.
1599///
1600/// Tries adapter-native downcast first, then falls back to JSON extraction.
1601fn extract_actual_indices(result: &OpResult, field: &str) -> Vec<i64> {
1602    let Some(body) = &result.body else {
1603        return Vec::new();
1604    };
1605    extract_indices_from_json(&body.to_json(), field)
1606}
1607
1608/// Extract integer values for a named field from JSON result structure.
1609fn extract_indices_from_json(json: &serde_json::Value, field: &str) -> Vec<i64> {
1610    match json {
1611        serde_json::Value::Array(rows) => rows
1612            .iter()
1613            .filter_map(|row| json_field_as_i64(row.get(field)?))
1614            .collect(),
1615        serde_json::Value::Object(obj) => {
1616            if let Some(rows) = obj.get("rows") {
1617                return extract_indices_from_json(rows, field);
1618            }
1619            obj.get(field)
1620                .and_then(json_field_as_i64)
1621                .into_iter()
1622                .collect()
1623        }
1624        _ => Vec::new(),
1625    }
1626}
1627
1628/// Coerce a JSON value to i64: native integer, or parse from string.
1629fn json_field_as_i64(v: &serde_json::Value) -> Option<i64> {
1630    v.as_i64().or_else(|| v.as_str()?.parse().ok())
1631}
1632
1633/// Extract integer ground-truth indices from a typed `Value`.
1634///
1635/// Single read path: at cycle time, [`ValidatingDispenser::execute`]
1636/// reads the value via `ctx.wires.get(name)` (a live read through
1637/// the per-fiber op-template kernel — same canonical-scope contract
1638/// MetricsDispenser uses), then hands it here for type-aware
1639/// extraction.
1640///
1641/// Fast path for the typed-array vector data path (SRD 53
1642/// §"Native vector PortType"): when the binding produces
1643/// `Value::VecI32` / `Value::VecF32` (the shape
1644/// `neighbor_indices_at` and friends emit), the slice is read
1645/// directly with no string round-trip. String fallback covers
1646/// legacy bindings that emit `Value::Str("[1, 5, 12, ...]")` or
1647/// `Value::Str("1,5,12,...")`.
1648fn resolve_expected_from_value(value: &polydat::ast::Value) -> Vec<i64> {
1649    match value {
1650        // Typed-slice fast paths — zero-copy read, no parse.
1651        polydat::ast::Value::VecI32(slice) => slice.as_slice().iter().map(|&x| x as i64).collect(),
1652        polydat::ast::Value::VecI64(slice) => slice.as_slice().to_vec(),
1653        polydat::ast::Value::VecF32(slice) => {
1654            // Vector ground-truth indices are integer-valued
1655            // by domain. Truncating fractional parts is the
1656            // correct semantic; anything else would mean the
1657            // dataset's index column is mis-typed at the source.
1658            slice.as_slice().iter().map(|&x| x as i64).collect()
1659        }
1660        polydat::ast::Value::VecF64(slice) => slice.as_slice().iter().map(|&x| x as i64).collect(),
1661        // SRD-70 projection landed as structural JSON (mixed or
1662        // string-typed columns): integer-valued leaves extract,
1663        // numeric strings parse, anything else drops.
1664        polydat::ast::Value::Json(j) => match &**j {
1665            serde_json::Value::Array(elems) => elems.iter().filter_map(json_field_as_i64).collect(),
1666            other => json_field_as_i64(other).into_iter().collect(),
1667        },
1668        polydat::ast::Value::Str(s) => parse_int_array(s),
1669        polydat::ast::Value::U64(v) => vec![*v as i64],
1670        _ => {
1671            // Display-string fallback for anything else.
1672            let s = value.to_display_string();
1673            parse_int_array(&s)
1674        }
1675    }
1676}
1677
1678/// Parse a string containing integers into a Vec<i64>.
1679///
1680/// Handles formats: `[1, 5, 12]`, `1,5,12`, `1 5 12`.
1681fn parse_int_array(s: &str) -> Vec<i64> {
1682    let trimmed = s.trim().trim_start_matches('[').trim_end_matches(']');
1683    trimmed
1684        .split(|c: char| c == ',' || c.is_whitespace())
1685        .filter(|s| !s.is_empty())
1686        .filter_map(|s| s.trim().parse::<i64>().ok())
1687        .collect()
1688}
1689
1690/// Extract a field from JSON by name, checking both top-level and row arrays.
1691fn extract_field_from_json<'a>(
1692    json: &'a serde_json::Value,
1693    field: &str,
1694) -> Option<&'a serde_json::Value> {
1695    match json {
1696        serde_json::Value::Object(obj) => obj.get(field).or_else(|| {
1697            obj.get("rows")
1698                .and_then(|r| r.as_array())
1699                .and_then(|rows| rows.first())
1700                .and_then(|row| row.get(field))
1701        }),
1702        serde_json::Value::Array(rows) => rows.first().and_then(|row| row.get(field)),
1703        _ => None,
1704    }
1705}
1706
1707/// Convert a JSON value to its string representation for comparison.
1708fn json_value_as_string(v: &serde_json::Value) -> String {
1709    match v {
1710        serde_json::Value::String(s) => s.clone(),
1711        other => other.to_string(),
1712    }
1713}
1714
1715#[cfg(test)]
1716mod tests {
1717    use super::*;
1718    use crate::adapter::ResultBody;
1719    use std::any::Any;
1720
1721    #[derive(Debug)]
1722    struct JsonBody(serde_json::Value);
1723    impl ResultBody for JsonBody {
1724        fn to_json(&self) -> serde_json::Value {
1725            self.0.clone()
1726        }
1727        fn as_any(&self) -> &dyn Any {
1728            self
1729        }
1730    }
1731
1732    #[test]
1733    fn parse_int_array_bracket_format() {
1734        assert_eq!(parse_int_array("[1, 5, 12, 23]"), vec![1, 5, 12, 23]);
1735    }
1736
1737    /// SRD-32a unification drift-guard: `CORE_OP_PARAMS` is the
1738    /// NON-wrapper core vocabulary. Wrapper fields are accepted by the
1739    /// op closed-vocab guard via the registry's `owns_field`, so a
1740    /// wrapper field appearing in `CORE_OP_PARAMS` is duplication that
1741    /// reintroduces the very two-lists-to-maintain trap this unification
1742    /// removed. Fail loudly if one creeps back in.
1743    #[test]
1744    fn core_op_params_disjoint_from_owned_fields() {
1745        let registry = crate::wrapper_registry::WrapperRegistry::from_inventory();
1746        let owned = registry.all_owned_fields();
1747        let dupes: Vec<&str> = CORE_OP_PARAMS
1748            .iter()
1749            .copied()
1750            .filter(|p| owned.contains(p))
1751            .collect();
1752        assert!(
1753            dupes.is_empty(),
1754            "these CORE_OP_PARAMS are already wrapper-owned (remove them — \
1755             the guard accepts them via WrapperRegistry::owns_field): {dupes:?}",
1756        );
1757    }
1758
1759    /// The type-safe replacement for the CLI-coincidence hole: a
1760    /// wrapper field that is NEITHER a CLI param NOR in CORE_OP_PARAMS
1761    /// must still be recognized, purely because a wrapper declares it.
1762    /// `readout` is exactly such a field (opt-in op status, never CLI-
1763    /// settable), so it is the live regression witness.
1764    #[test]
1765    fn wrapper_field_accepted_without_cli_or_core_membership() {
1766        let registry = crate::wrapper_registry::WrapperRegistry::from_inventory();
1767        assert!(
1768            registry.owns_field("readout"),
1769            "readout must be registry-owned"
1770        );
1771        assert!(
1772            registry.owns_field("errors"),
1773            "errors must be registry-owned (was riding the CLI hatch)"
1774        );
1775        assert!(
1776            registry.owns_field("tries"),
1777            "tries must be registry-owned (was riding the CLI hatch)"
1778        );
1779        assert!(
1780            !CORE_OP_PARAMS.contains(&"readout"),
1781            "readout should NOT be in CORE_OP_PARAMS — it's wrapper-owned"
1782        );
1783    }
1784
1785    #[test]
1786    fn parse_int_array_comma_format() {
1787        assert_eq!(parse_int_array("1,5,12,23"), vec![1, 5, 12, 23]);
1788    }
1789
1790    #[test]
1791    fn parse_int_array_space_format() {
1792        assert_eq!(parse_int_array("1 5 12 23"), vec![1, 5, 12, 23]);
1793    }
1794
1795    #[test]
1796    fn parse_int_array_empty() {
1797        assert_eq!(parse_int_array("[]"), Vec::<i64>::new());
1798        assert_eq!(parse_int_array(""), Vec::<i64>::new());
1799    }
1800
1801    #[test]
1802    fn extract_indices_from_json_array() {
1803        let json = serde_json::json!([
1804            {"key": 5, "distance": 0.1},
1805            {"key": 12, "distance": 0.2},
1806            {"key": 3, "distance": 0.3},
1807        ]);
1808        assert_eq!(extract_indices_from_json(&json, "key"), vec![5, 12, 3]);
1809    }
1810
1811    #[test]
1812    fn extract_indices_from_json_rows_wrapper() {
1813        let json = serde_json::json!({
1814            "rows": [
1815                {"key": 5},
1816                {"key": 12},
1817            ]
1818        });
1819        assert_eq!(extract_indices_from_json(&json, "key"), vec![5, 12]);
1820    }
1821
1822    #[test]
1823    fn assertion_not_null() {
1824        let result = OpResult {
1825            body: Some(Box::new(JsonBody(serde_json::json!({"name": "alice"})))),
1826            skipped: false,
1827        };
1828        let spec = AssertionSpec {
1829            field: "name".into(),
1830            predicate: AssertionPredicate::NotNull,
1831        };
1832        assert!(spec.check(&result));
1833
1834        let spec_missing = AssertionSpec {
1835            field: "age".into(),
1836            predicate: AssertionPredicate::NotNull,
1837        };
1838        assert!(!spec_missing.check(&result));
1839    }
1840
1841    #[test]
1842    fn assertion_eq() {
1843        let result = OpResult {
1844            body: Some(Box::new(JsonBody(serde_json::json!({"status": "ok"})))),
1845            skipped: false,
1846        };
1847        let spec = AssertionSpec {
1848            field: "status".into(),
1849            predicate: AssertionPredicate::Eq("ok".into()),
1850        };
1851        assert!(spec.check(&result));
1852
1853        let spec_fail = AssertionSpec {
1854            field: "status".into(),
1855            predicate: AssertionPredicate::Eq("error".into()),
1856        };
1857        assert!(!spec_fail.check(&result));
1858    }
1859
1860    #[test]
1861    fn assertion_gte() {
1862        let result = OpResult {
1863            body: Some(Box::new(JsonBody(serde_json::json!({"balance": 42.5})))),
1864            skipped: false,
1865        };
1866        let spec = AssertionSpec {
1867            field: "balance".into(),
1868            predicate: AssertionPredicate::Gte(0.0),
1869        };
1870        assert!(spec.check(&result));
1871
1872        let spec_fail = AssertionSpec {
1873            field: "balance".into(),
1874            predicate: AssertionPredicate::Gte(100.0),
1875        };
1876        assert!(!spec_fail.check(&result));
1877    }
1878
1879    #[test]
1880    fn assertion_no_body() {
1881        let result = OpResult {
1882            body: None,
1883            skipped: false,
1884        };
1885        let spec = AssertionSpec {
1886            field: "anything".into(),
1887            predicate: AssertionPredicate::IsNull,
1888        };
1889        assert!(spec.check(&result));
1890
1891        let spec_not_null = AssertionSpec {
1892            field: "anything".into(),
1893            predicate: AssertionPredicate::NotNull,
1894        };
1895        assert!(!spec_not_null.check(&result));
1896    }
1897
1898    /// Body whose `element_count()` reflects the number of items
1899    /// in a JSON array — exercises body-level predicates like
1900    /// `MinRows` that read from `element_count` rather than
1901    /// inspecting fields.
1902    #[derive(Debug)]
1903    struct CountedBody {
1904        rows: Vec<serde_json::Value>,
1905    }
1906    impl ResultBody for CountedBody {
1907        fn to_json(&self) -> serde_json::Value {
1908            serde_json::Value::Array(self.rows.clone())
1909        }
1910        fn as_any(&self) -> &dyn Any {
1911            self
1912        }
1913        fn element_count(&self) -> u64 {
1914            self.rows.len() as u64
1915        }
1916    }
1917
1918    #[test]
1919    fn assertion_min_rows_passes_when_threshold_met() {
1920        let result = OpResult {
1921            body: Some(Box::new(CountedBody {
1922                rows: vec![
1923                    serde_json::json!({"index_name": "vec_idx"}),
1924                    serde_json::json!({"index_name": "meta_idx"}),
1925                ],
1926            })),
1927            skipped: false,
1928        };
1929        let spec = AssertionSpec {
1930            field: String::new(),
1931            predicate: AssertionPredicate::MinRows(1),
1932        };
1933        assert!(spec.check(&result));
1934
1935        let spec_two = AssertionSpec {
1936            field: String::new(),
1937            predicate: AssertionPredicate::MinRows(2),
1938        };
1939        assert!(spec_two.check(&result));
1940    }
1941
1942    #[test]
1943    fn assertion_min_rows_fails_when_below_threshold() {
1944        // Empty array: element_count = 0, MinRows(1) must fail.
1945        let result = OpResult {
1946            body: Some(Box::new(CountedBody { rows: Vec::new() })),
1947            skipped: false,
1948        };
1949        let spec = AssertionSpec {
1950            field: String::new(),
1951            predicate: AssertionPredicate::MinRows(1),
1952        };
1953        assert!(!spec.check(&result));
1954
1955        // No body at all: element_count defaults to 0 → MinRows(1) fails.
1956        let result_none = OpResult {
1957            body: None,
1958            skipped: false,
1959        };
1960        assert!(!spec.check(&result_none));
1961    }
1962
1963    #[test]
1964    fn parse_assertions_min_rows_from_yaml() {
1965        // SRD-40b-shaped failsafe verify form:
1966        //   verify:
1967        //     - min_rows: 1
1968        let mut template = nmbrs_workload::model::ParsedOp::simple("await", "test");
1969        template.params.insert(
1970            "verify".into(),
1971            serde_json::json!([
1972                {"min_rows": 1},
1973            ]),
1974        );
1975        let assertions = parse_assertions(&template);
1976        assert_eq!(assertions.len(), 1);
1977        match &assertions[0].predicate {
1978            AssertionPredicate::MinRows(n) => assert_eq!(*n, 1),
1979            other => panic!("expected MinRows(1), got {other:?}"),
1980        }
1981    }
1982
1983    #[test]
1984    fn eq_failure_includes_body_and_distinguishes_absent_vs_not_json() {
1985        // JSON body that has fields but lacks the one we asked
1986        // for: observed reads `<field absent; …>` and lists the
1987        // keys that ARE present so the operator can pick a real
1988        // field name without re-running the workload.
1989        let result = OpResult {
1990            body: Some(Box::new(JsonBody(serde_json::json!({
1991                "value": null, "request": {"type": "exec"}
1992            })))),
1993            skipped: false,
1994        };
1995        let spec = AssertionSpec {
1996            field: "status".into(),
1997            predicate: AssertionPredicate::Eq("200".into()),
1998        };
1999        let msg = describe_assertion_failure(&spec, &result);
2000        assert!(
2001            msg.contains("field absent"),
2002            "json-without-field should mark observed as absent, got: {msg}"
2003        );
2004        assert!(
2005            msg.contains("body keys"),
2006            "absent message should enumerate present keys, got: {msg}"
2007        );
2008        assert!(
2009            msg.contains("\"value\"") && msg.contains("\"request\""),
2010            "key list should include both present keys, got: {msg}"
2011        );
2012        assert!(msg.contains("body: "), "body excerpt missing: {msg}");
2013        assert!(
2014            msg.contains("\"request\""),
2015            "body excerpt should echo the actual JSON: {msg}"
2016        );
2017
2018        // Plain-text body: observed reads `<not-json: …>` with a
2019        // short preview so the operator can recognise the actual
2020        // payload (HTML error page, plain-text response, etc.).
2021        #[derive(Debug)]
2022        struct PlainBody(String);
2023        impl ResultBody for PlainBody {
2024            fn to_json(&self) -> serde_json::Value {
2025                serde_json::Value::String(self.0.clone())
2026            }
2027            fn as_any(&self) -> &dyn Any {
2028                self
2029            }
2030            fn to_text(&self) -> String {
2031                self.0.clone()
2032            }
2033        }
2034        let text_result = OpResult {
2035            body: Some(Box::new(PlainBody(
2036                "<html><body>404 Not Found</body></html>".into(),
2037            ))),
2038            skipped: false,
2039        };
2040        let msg2 = describe_assertion_failure(&spec, &text_result);
2041        assert!(
2042            msg2.contains("not-json"),
2043            "text body should mark observed as not-json, got: {msg2}"
2044        );
2045        assert!(
2046            msg2.contains("404 Not Found"),
2047            "body excerpt should include the text: {msg2}"
2048        );
2049    }
2050
2051    /// When the op produced no body at all, the message must
2052    /// communicate that clearly (not just '<no body>' twice),
2053    /// AND must NOT duplicate the same '<no body>' phrase in
2054    /// both the observed-field slot and the body excerpt.
2055    #[test]
2056    fn eq_failure_with_no_body_explains_situation() {
2057        let result = OpResult {
2058            body: None,
2059            skipped: false,
2060        };
2061        let spec = AssertionSpec {
2062            field: "status".into(),
2063            predicate: AssertionPredicate::Eq("200".into()),
2064        };
2065        let msg = describe_assertion_failure(&spec, &result);
2066        assert!(
2067            msg.contains("no body returned by op"),
2068            "no-body case should explain why the field can't be read, got: {msg}"
2069        );
2070        assert!(
2071            !msg.contains("body: "),
2072            "no-body case should suppress the redundant body excerpt, got: {msg}"
2073        );
2074    }
2075
2076    #[test]
2077    fn min_rows_failure_describes_actual_vs_expected() {
2078        // Strict-mode error renderer should name the predicate
2079        // and the actual count so the user sees "expected ≥1, got 0"
2080        // rather than a generic "validation failed".
2081        let result = OpResult {
2082            body: Some(Box::new(CountedBody { rows: Vec::new() })),
2083            skipped: false,
2084        };
2085        let spec = AssertionSpec {
2086            field: String::new(),
2087            predicate: AssertionPredicate::MinRows(1),
2088        };
2089        let msg = describe_assertion_failure(&spec, &result);
2090        assert!(msg.contains("min_rows"), "got: {msg}");
2091        assert!(msg.contains("≥1"), "got: {msg}");
2092        assert!(msg.contains("got 0"), "got: {msg}");
2093    }
2094
2095    #[test]
2096    fn validation_metrics_record_relevancy() {
2097        let labels = Labels::of("activity", "test");
2098        let metrics = ValidationMetrics::new(
2099            &labels,
2100            &[RelevancyFn::Recall, RelevancyFn::Precision],
2101            10,
2102            Some(20),
2103        );
2104        // Family names are bare function names; `k` and
2105        // `r` ride on the F64Stats's labels so consumers
2106        // can query e.g. `recall{k="10",r="20"}`.
2107        assert!(metrics.relevancy_stats.contains_key("recall"));
2108        assert!(metrics.relevancy_stats.contains_key("precision"));
2109        assert!(!metrics.relevancy_stats.contains_key("f1"));
2110
2111        // The F64Stats labels carry k and r.
2112        let recall_labels = metrics.relevancy_stats["recall"].labels();
2113        assert_eq!(recall_labels.get("k"), Some("10"));
2114        assert_eq!(recall_labels.get("r"), Some("20"));
2115
2116        metrics.record_relevancy("recall", 0.85);
2117        metrics.record_relevancy("recall", 0.90);
2118        let snap = metrics.relevancy_stats["recall"].snapshot();
2119        assert_eq!(snap.len(), 2);
2120    }
2121
2122    #[test]
2123    fn validation_metrics_r_defaults_to_k() {
2124        let labels = Labels::of("activity", "test");
2125        // No `r:` in the relevancy config → the metric's
2126        // `r` label equals `k` (legacy first-k semantics).
2127        let metrics = ValidationMetrics::new(&labels, &[RelevancyFn::Recall], 100, None);
2128        let l = metrics.relevancy_stats["recall"].labels();
2129        assert_eq!(l.get("k"), Some("100"));
2130        assert_eq!(l.get("r"), Some("100"));
2131    }
2132
2133    #[test]
2134    fn resolve_expected_string_array_form() {
2135        let v = polydat::ast::Value::Str("[1, 5, 12, 23]".into());
2136        assert_eq!(resolve_expected_from_value(&v), vec![1, 5, 12, 23]);
2137    }
2138
2139    #[test]
2140    fn resolve_expected_string_csv_form() {
2141        let v = polydat::ast::Value::Str("1,5,12".into());
2142        assert_eq!(resolve_expected_from_value(&v), vec![1, 5, 12]);
2143    }
2144
2145    #[test]
2146    fn resolve_expected_native_veci32_fast_path() {
2147        // The fast path the dataset accessors emit
2148        // (`neighbor_indices_at` etc. → Value::VecI32). No
2149        // string round-trip happens; the slice is read directly.
2150        use polydat::ast::{SliceArc, Value};
2151        let slice = SliceArc::<i32>::from_vec(vec![1, 5, 12, 23, 100]);
2152        let v = Value::VecI32(slice);
2153        assert_eq!(resolve_expected_from_value(&v), vec![1, 5, 12, 23, 100]);
2154    }
2155
2156    #[test]
2157    fn resolve_expected_native_vecf32_fast_path() {
2158        // VecF32 ground truth (rare but legal — some datasets
2159        // store ranks as floats). Truncates to i64.
2160        use polydat::ast::{SliceArc, Value};
2161        let slice = SliceArc::<f32>::from_vec(vec![1.0, 2.0, 3.0]);
2162        let v = Value::VecF32(slice);
2163        assert_eq!(resolve_expected_from_value(&v), vec![1, 2, 3]);
2164    }
2165
2166    #[test]
2167    fn parse_relevancy_from_params() {
2168        let mut template = nmbrs_workload::model::ParsedOp::simple("test", "SELECT key FROM t");
2169        template.params.insert(
2170            "relevancy".into(),
2171            serde_json::json!({
2172                "actual": "key",
2173                "expected": "{ground_truth}",
2174                "k": 10,
2175                "functions": ["recall", "precision", "f1"]
2176            }),
2177        );
2178        let config = parse_relevancy(&template, None, None).unwrap().unwrap();
2179        assert_eq!(config.actual_field, "key");
2180        assert_eq!(config.expected_binding, "{ground_truth}");
2181        assert_eq!(config.k, 10);
2182        assert!(config.r.is_none(), "r should default to None when absent");
2183        assert_eq!(config.functions.len(), 3);
2184        assert_eq!(config.functions[0], RelevancyFn::Recall);
2185        assert_eq!(config.functions[1], RelevancyFn::Precision);
2186        assert_eq!(config.functions[2], RelevancyFn::F1);
2187    }
2188
2189    #[test]
2190    fn parse_relevancy_with_r_for_k_recall_at_r() {
2191        // 10-recall@100: retrieve 100, score against the first
2192        // 10. The `r` field is parsed alongside `k` from the
2193        // same numeric/`{name}` shapes.
2194        let mut template = nmbrs_workload::model::ParsedOp::simple("test", "SELECT key FROM t");
2195        template.params.insert(
2196            "relevancy".into(),
2197            serde_json::json!({
2198                "actual": "key",
2199                "expected": "{ground_truth}",
2200                "k": 10,
2201                "r": 100,
2202                "functions": ["recall"],
2203            }),
2204        );
2205        let config = parse_relevancy(&template, None, None).unwrap().unwrap();
2206        assert_eq!(config.k, 10);
2207        assert_eq!(config.r, Some(100));
2208    }
2209
2210    #[test]
2211    fn parse_relevancy_r_accepts_string_form() {
2212        let mut template = nmbrs_workload::model::ParsedOp::simple("test", "SELECT key FROM t");
2213        template.params.insert(
2214            "relevancy".into(),
2215            serde_json::json!({
2216                "actual": "key",
2217                "expected": "{ground_truth}",
2218                "k": "10",
2219                "r": "100",
2220            }),
2221        );
2222        let config = parse_relevancy(&template, None, None).unwrap().unwrap();
2223        assert_eq!(config.k, 10);
2224        assert_eq!(config.r, Some(100));
2225    }
2226
2227    #[test]
2228    fn parse_relevancy_missing() {
2229        let template = nmbrs_workload::model::ParsedOp::simple("test", "INSERT");
2230        assert!(parse_relevancy(&template, None, None).unwrap().is_none());
2231    }
2232
2233    #[test]
2234    fn parse_relevancy_k_and_r_accept_bare_wire_names() {
2235        // Post-SRD-68 follow-up: `k: k` (bare wire-name) resolves
2236        // against the canonical kernel at wrap time. Same one-shot
2237        // evaluation as the `{k}` text-template form but without
2238        // the placeholder braces.
2239        let kernel = crate::scope_kernel::ScopeKernel::compile(
2240            "input cycle: u64\n\
2241             const k := 10\n\
2242             const limit := 100\n",
2243        )
2244        .expect("compile scope kernel wires");
2245        let wires: &dyn WireSource = &kernel;
2246
2247        let mut template = nmbrs_workload::model::ParsedOp::simple("test", "SELECT key FROM t");
2248        template.params.insert(
2249            "relevancy".into(),
2250            serde_json::json!({
2251                "actual": "key",
2252                "expected": "{ground_truth}",
2253                "k": "k",            // bare wire-name
2254                "r": "limit",        // bare wire-name
2255                "functions": ["recall"],
2256            }),
2257        );
2258        let config = parse_relevancy(&template, None, Some(wires))
2259            .unwrap()
2260            .unwrap();
2261        assert_eq!(config.k, 10, "bare `k:` resolved through wires");
2262        assert_eq!(config.r, Some(100), "bare `r:` resolved through wires");
2263    }
2264
2265    #[test]
2266    fn parse_relevancy_bare_name_falls_through_to_int_parse_when_no_kernel() {
2267        // Without a canonical kernel (no wires available), a bare
2268        // identifier in `k:` errors clearly — it can't be a wire
2269        // reference and isn't a valid integer either.
2270        let mut template = nmbrs_workload::model::ParsedOp::simple("test", "SELECT key FROM t");
2271        template.params.insert(
2272            "relevancy".into(),
2273            serde_json::json!({
2274                "actual": "key",
2275                "expected": "{ground_truth}",
2276                "k": "k",
2277                "functions": ["recall"],
2278            }),
2279        );
2280        let err = parse_relevancy(&template, None, None).unwrap_err();
2281        assert!(
2282            err.contains("'k' is not a valid non-negative integer"),
2283            "diagnostic should describe the parse failure: {err}"
2284        );
2285    }
2286
2287    /// A succeeding op that returns NO body must not be failed by a value
2288    /// predicate. `on_timeout: accept` (the server is still working; the poll
2289    /// layer observes it) and HTTP 204 both land here, and a
2290    /// `field: status, eq: 200` clause written for the normal response was
2291    /// failing them — it cost a live benchmark run at tier 6.
2292    #[test]
2293    fn value_predicates_are_vacuous_without_a_body() {
2294        let result = OpResult {
2295            body: None,
2296            ..Default::default()
2297        };
2298        for predicate in [
2299            AssertionPredicate::Eq("200".into()),
2300            AssertionPredicate::Lte(5.0),
2301            AssertionPredicate::Gte(1.0),
2302            AssertionPredicate::Contains("ok".into()),
2303            AssertionPredicate::IsNull,
2304        ] {
2305            let spec = AssertionSpec {
2306                field: "status".into(),
2307                predicate,
2308            };
2309            assert!(
2310                spec.check(&result),
2311                "a value predicate has nothing to contradict it: {:?}",
2312                spec.predicate
2313            );
2314        }
2315    }
2316
2317    /// Presence predicates are the explicit "a body is required" spelling, so
2318    /// they must still fail when none arrives — otherwise there would be no
2319    /// way to demand one.
2320    #[test]
2321    fn presence_predicates_still_fail_without_a_body() {
2322        let result = OpResult {
2323            body: None,
2324            ..Default::default()
2325        };
2326        let not_null = AssertionSpec {
2327            field: "status".into(),
2328            predicate: AssertionPredicate::NotNull,
2329        };
2330        assert!(
2331            !not_null.check(&result),
2332            "`is: not_null` is how an author demands the field exist"
2333        );
2334        let min_rows = AssertionSpec {
2335            field: String::new(),
2336            predicate: AssertionPredicate::MinRows(1),
2337        };
2338        assert!(
2339            !min_rows.check(&result),
2340            "`min_rows: 1` is how an author demands a non-empty result"
2341        );
2342    }
2343
2344    /// A malformed bound can never pass, body or no body — otherwise a typo
2345    /// would turn into a silently-skipped check on exactly the ops that
2346    /// return nothing.
2347    #[test]
2348    fn malformed_bounds_fail_even_without_a_body() {
2349        let result = OpResult {
2350            body: None,
2351            ..Default::default()
2352        };
2353        let spec = AssertionSpec {
2354            field: "value".into(),
2355            predicate: AssertionPredicate::MalformedBound {
2356                key: "lte".into(),
2357                raw: "{unresolved}".into(),
2358            },
2359        };
2360        assert!(!spec.check(&result));
2361    }
2362
2363    /// A quoted numeric bound means the same as an unquoted one. YAML makes
2364    /// the string form easy to reach — quoting, or a `{placeholder}` that
2365    /// substitutes to text — and it used to silently become `<= 0`, failing
2366    /// good data against a threshold nobody wrote. Cost a live benchmark run.
2367    #[test]
2368    fn numeric_bounds_accept_quoted_numbers() {
2369        let mut template = nmbrs_workload::model::ParsedOp::simple("t", "noop");
2370        template.params.insert(
2371            "verify".into(),
2372            serde_json::json!([
2373                {"field": "value", "lte": "5"},
2374                {"field": "value", "gte": " 2 "},
2375                {"field": "other", "lte": 7},
2376            ]),
2377        );
2378        let a = parse_assertions(&template);
2379        assert!(
2380            matches!(a[0].predicate, AssertionPredicate::Lte(t) if t == 5.0),
2381            "quoted lte must parse: {:?}",
2382            a[0].predicate
2383        );
2384        assert!(
2385            matches!(a[1].predicate, AssertionPredicate::Gte(t) if t == 2.0),
2386            "surrounding whitespace is not a malformed bound: {:?}",
2387            a[1].predicate
2388        );
2389        assert!(
2390            matches!(a[2].predicate, AssertionPredicate::Lte(t) if t == 7.0),
2391            "the unquoted form is unchanged: {:?}",
2392            a[2].predicate
2393        );
2394    }
2395
2396    /// A bound that is not a number at all must FAIL LOUDLY and name itself —
2397    /// never default to zero, which reads as a real threshold in the failure
2398    /// message and sends the reader hunting for a data problem that does not
2399    /// exist.
2400    #[test]
2401    fn non_numeric_bounds_are_malformed_not_zero() {
2402        let mut template = nmbrs_workload::model::ParsedOp::simple("t", "noop");
2403        template.params.insert(
2404            "verify".into(),
2405            serde_json::json!([
2406                {"field": "value", "lte": "{unresolved}"},
2407                {"field": "value", "gte": "abc"},
2408            ]),
2409        );
2410        let a = parse_assertions(&template);
2411        for spec in &a {
2412            match &spec.predicate {
2413                AssertionPredicate::MalformedBound { raw, .. } => {
2414                    assert!(
2415                        !raw.is_empty(),
2416                        "the offending text is carried for the message"
2417                    );
2418                }
2419                other => panic!("expected MalformedBound, got {other:?}"),
2420            }
2421        }
2422        // And the rendered failure names the malformed bound rather than
2423        // quoting a threshold the author never wrote.
2424        let msg = format!("{:?}", a[0].predicate);
2425        assert!(
2426            msg.contains("MalformedBound"),
2427            "the predicate stays malformed all the way to reporting: {msg}"
2428        );
2429    }
2430
2431    #[test]
2432    fn parse_assertions_from_params() {
2433        let mut template = nmbrs_workload::model::ParsedOp::simple("test", "SELECT");
2434        template.params.insert(
2435            "verify".into(),
2436            serde_json::json!([
2437                {"field": "name", "is": "not_null"},
2438                {"field": "balance", "gte": 0},
2439                {"field": "status", "eq": "active"},
2440            ]),
2441        );
2442        let assertions = parse_assertions(&template);
2443        assert_eq!(assertions.len(), 3);
2444        assert_eq!(assertions[0].field, "name");
2445        assert!(matches!(
2446            assertions[0].predicate,
2447            AssertionPredicate::NotNull
2448        ));
2449        assert_eq!(assertions[1].field, "balance");
2450        assert!(matches!(assertions[1].predicate, AssertionPredicate::Gte(v) if v == 0.0));
2451        assert_eq!(assertions[2].field, "status");
2452        assert!(matches!(&assertions[2].predicate, AssertionPredicate::Eq(s) if s == "active"));
2453    }
2454
2455    #[test]
2456    fn parse_assertions_missing() {
2457        let template = nmbrs_workload::model::ParsedOp::simple("test", "INSERT");
2458        assert!(parse_assertions(&template).is_empty());
2459    }
2460}