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