1use 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
24pub const WRAPPER_NAME: WrapperName = WrapperName::new("validate");
29
30fn wrapper_triggers(s: WrapperSubject) -> bool {
32 let Some(template) = s.op() else {
33 return false;
34 };
35 template.params.contains_key("verify")
36 || template.params.contains_key("relevancy")
37 || template.params.contains_key(crate::admission::PARAM)
38}
39
40fn wrapper_describe_assignment(s: WrapperSubject) -> Option<String> {
41 let template = s.op()?;
42 let strict = template
43 .params
44 .get("strict")
45 .and_then(|v| nmbrs_workload::boolean::json_bool("strict", v).ok())
46 .unwrap_or(false);
47 let mut parts: Vec<String> = Vec::new();
48 if let Some(v) = template.params.get("verify") {
49 parts.push(format!(
50 "verify={}",
51 crate::wrapper_registrations::short_value(v)
52 ));
53 }
54 if let Some(v) = template.params.get("relevancy") {
55 parts.push(format!(
56 "relevancy={}",
57 crate::wrapper_registrations::short_value(v)
58 ));
59 }
60 if let Some(v) = template.params.get(crate::admission::PARAM) {
61 parts.push(format!(
62 "admission={}",
63 crate::wrapper_registrations::short_value(v)
64 ));
65 }
66 if parts.is_empty() {
67 return None;
68 }
69 let body = parts.join(", ");
70 Some(if strict {
71 format!("validate: {body} (strict)")
72 } else {
73 format!("validate: {body}")
74 })
75}
76
77inventory::submit! {
78 WrapperRegistration {
79 name: WRAPPER_NAME,
80 owned_fields: &["verify", "relevancy", "admission", "strict"],
81 triggers: wrapper_triggers,
82 requires_inner: &[crate::wrappers::traverse::NAME],
83 forbids_outer: &[],
84 mutually_exclusive_with: &[],
85 describe_assignment: wrapper_describe_assignment,
86 levels: &[crate::wrapper_registry::WrapperLevel::Op],
87 }
88}
89
90pub const CORE_OP_PARAMS: &[&str] = &[
118 "batch",
120 "batchtype",
121 "max_batch_size",
122 "ratio",
124 "adapter",
126 "daemon",
132 "daemon_cancel_grace_ms",
133];
134
135#[derive(Debug, Clone)]
137pub struct RelevancyConfig {
138 pub actual_field: String,
140 pub expected_binding: String,
142 pub k: usize,
146 pub r: Option<usize>,
154 pub admitted_binding: Option<String>,
159 pub functions: Vec<RelevancyFn>,
161}
162
163#[derive(Debug, Clone)]
165pub struct AssertionSpec {
166 pub field: String,
168 pub predicate: AssertionPredicate,
170}
171
172#[derive(Debug, Clone)]
174pub enum AssertionPredicate {
175 Eq(String),
177 NotNull,
179 IsNull,
181 Gte(f64),
183 Lte(f64),
185 Contains(String),
187 MalformedBound { key: String, raw: String },
195 MinRows(u64),
201}
202
203impl AssertionSpec {
204 pub fn check(&self, result: &OpResult) -> bool {
206 if let AssertionPredicate::MinRows(n) = &self.predicate {
210 let row_count = result.body.as_ref().map(|b| b.element_count()).unwrap_or(0);
211 return row_count >= *n;
212 }
213
214 let json = match &result.body {
215 Some(body) => body.to_json(),
216 None => {
233 return !matches!(
234 self.predicate,
235 AssertionPredicate::NotNull | AssertionPredicate::MalformedBound { .. }
236 );
237 }
238 };
239
240 let field_val = extract_field_from_json(&json, &self.field);
241
242 match &self.predicate {
243 AssertionPredicate::NotNull => field_val.is_some(),
244 AssertionPredicate::IsNull => field_val.is_none(),
245 AssertionPredicate::Eq(expected) => {
246 field_val.is_some_and(|v| json_value_as_string(v) == *expected)
247 }
248 AssertionPredicate::Gte(threshold) => field_val
249 .and_then(|v| v.as_f64())
250 .is_some_and(|v| v >= *threshold),
251 AssertionPredicate::Lte(threshold) => field_val
252 .and_then(|v| v.as_f64())
253 .is_some_and(|v| v <= *threshold),
254 AssertionPredicate::Contains(substr) => {
255 field_val.is_some_and(|v| json_value_as_string(v).contains(substr.as_str()))
256 }
257 AssertionPredicate::MalformedBound { .. } => false,
258 AssertionPredicate::MinRows(_) => unreachable!("MinRows handled in early-return above"),
259 }
260 }
261}
262
263pub struct RunningAgg {
271 pub total_sum: f64,
273 pub total_count: u64,
275 pub window: std::collections::VecDeque<f64>,
277 pub window_size: usize,
279}
280
281impl RunningAgg {
282 pub fn new(window_size: usize) -> Self {
283 Self {
284 total_sum: 0.0,
285 total_count: 0,
286 window: std::collections::VecDeque::with_capacity(window_size),
287 window_size,
288 }
289 }
290
291 pub fn record(&mut self, score: f64) {
292 self.total_sum += score;
293 self.total_count += 1;
294 if self.window.len() == self.window_size {
295 self.window.pop_front();
296 }
297 self.window.push_back(score);
298 }
299
300 pub fn window_mean(&self) -> f64 {
301 if self.window.is_empty() {
302 0.0
303 } else {
304 self.window.iter().sum::<f64>() / self.window.len() as f64
305 }
306 }
307
308 pub fn total_mean(&self) -> f64 {
309 if self.total_count == 0 {
310 0.0
311 } else {
312 self.total_sum / self.total_count as f64
313 }
314 }
315}
316
317pub const DEFAULT_RECALL_WINDOW: usize = 10;
320
321#[derive(Debug, Clone)]
324pub struct RelevancyLive {
325 pub name: String,
326 pub window_mean: f64,
327 pub total_mean: f64,
328 pub total_count: u64,
329 pub window_len: usize,
330}
331
332pub struct ValidationMetrics {
334 pub validations_passed: AtomicU64,
335 pub validations_failed: AtomicU64,
336 pub relevancy_empty_rows: AtomicU64,
341 pub relevancy_stats: HashMap<String, nmbrs_metrics::summaries::f64stats::F64Stats>,
344 pub running_aggregates: HashMap<String, std::sync::Mutex<RunningAgg>>,
348 pub cells: Option<Arc<crate::op_cells::OpCells>>,
352}
353
354impl ValidationMetrics {
355 pub fn new(labels: &Labels, functions: &[RelevancyFn], k: usize, r: Option<usize>) -> Self {
367 let r_value = r.unwrap_or(k);
368 let stats_labels = labels
369 .with("k", k.to_string())
370 .with("r", r_value.to_string());
371 let mut stats = HashMap::new();
372 let mut running = HashMap::new();
373 for func in functions {
374 let metric_name = func.metric_name().to_string();
375 stats.insert(
376 metric_name.clone(),
377 nmbrs_metrics::summaries::f64stats::F64Stats::new(
378 stats_labels.with("name", &metric_name),
379 ),
380 );
381 running.insert(
382 metric_name.clone(),
383 std::sync::Mutex::new(RunningAgg::new(DEFAULT_RECALL_WINDOW)),
384 );
385 }
386 Self {
387 validations_passed: AtomicU64::new(0),
388 validations_failed: AtomicU64::new(0),
389 relevancy_empty_rows: AtomicU64::new(0),
390 relevancy_stats: stats,
391 running_aggregates: running,
392 cells: None,
393 }
394 }
395
396 pub fn assertions_only() -> Self {
398 Self {
399 validations_passed: AtomicU64::new(0),
400 validations_failed: AtomicU64::new(0),
401 relevancy_empty_rows: AtomicU64::new(0),
402 relevancy_stats: HashMap::new(),
403 running_aggregates: HashMap::new(),
404 cells: None,
405 }
406 }
407
408 pub fn record_relevancy(&self, metric_name: &str, score: f64) {
411 if let Some(stats) = self.relevancy_stats.get(metric_name) {
412 stats.record(score);
413 }
414 if let Some(agg) = self.running_aggregates.get(metric_name) {
415 let mut a = agg.lock().unwrap_or_else(|e| e.into_inner());
416 a.record(score);
417 }
418 }
419
420 pub fn live_snapshot(&self) -> Vec<RelevancyLive> {
423 let mut out = Vec::with_capacity(self.running_aggregates.len());
424 for (name, agg) in &self.running_aggregates {
425 let a = agg.lock().unwrap_or_else(|e| e.into_inner());
426 out.push(RelevancyLive {
427 name: name.clone(),
428 window_mean: a.window_mean(),
429 total_mean: a.total_mean(),
430 total_count: a.total_count,
431 window_len: a.window.len(),
432 });
433 }
434 out.sort_by(|x, y| x.name.cmp(&y.name));
435 out
436 }
437
438 pub fn passed(&self) -> u64 {
440 self.validations_passed.load(Ordering::Relaxed)
441 }
442
443 pub fn failed(&self) -> u64 {
445 self.validations_failed.load(Ordering::Relaxed)
446 }
447
448 pub fn empty_rows(&self) -> u64 {
450 self.relevancy_empty_rows.load(Ordering::Relaxed)
451 }
452}
453
454pub struct ValidatingDispenser {
463 inner: Arc<dyn OpDispenser>,
464 assertions: Vec<AssertionSpec>,
465 relevancy: Option<RelevancyConfig>,
466 expected_wire_name: Option<String>,
475 actual_projection: Option<ActualProjection>,
482 admission: Option<crate::admission::AdmissionConfig>,
484 admission_projection: Option<ActualProjection>,
487 metrics: Arc<ValidationMetrics>,
488 cells: Option<Arc<crate::op_cells::OpCells>>,
492 strict: bool,
494}
495
496struct ActualProjection {
500 segs: Vec<crate::wrappers::result::PathSeg>,
501 target: Option<polydat::ast::PortType>,
502}
503
504type WrappedDispenser = (Arc<dyn OpDispenser>, Option<Arc<ValidationMetrics>>);
508
509impl ValidatingDispenser {
510 pub fn wrap(
516 inner: Arc<dyn OpDispenser>,
517 template: &nmbrs_workload::model::ParsedOp,
518 labels: &Labels,
519 program: Option<&polydat::kernel::PolydatProgram>,
520 fx: &mut crate::fixture::ScopeFixture,
521 ) -> Result<WrappedDispenser, String> {
522 Self::wrap_in_cells(inner, template, labels, program, fx, None)
523 }
524
525 pub fn wrap_in_cells(
529 inner: Arc<dyn OpDispenser>,
530 template: &nmbrs_workload::model::ParsedOp,
531 labels: &Labels,
532 program: Option<&polydat::kernel::PolydatProgram>,
533 fx: &mut crate::fixture::ScopeFixture,
534 cells: Option<Arc<crate::op_cells::OpCells>>,
535 ) -> Result<WrappedDispenser, String> {
536 let template_owned: nmbrs_workload::model::ParsedOp;
547 let canonical_kernel = inner.canonical_kernel();
548 let template = if let Some(canonical) = &canonical_kernel {
549 let mut t = template.clone();
550 crate::scope::resolve_placeholders_in_op_params(&mut t, canonical.as_ref())?;
551 template_owned = t;
552 &template_owned
553 } else {
554 template
555 };
556 let assertions = parse_assertions(template);
557 let canonical_wires = canonical_kernel
564 .as_ref()
565 .map(|k| crate::wires::KernelWires(k.as_ref()));
566 let wires_for_parse: Option<&dyn WireSource> =
567 canonical_wires.as_ref().map(|w| w as &dyn WireSource);
568 let relevancy = parse_relevancy(template, program, wires_for_parse)?;
569 let admission = crate::admission::parse_admission(template)?;
570 let strict = template.params.get("strict").map_or(Ok(false), |v| {
571 nmbrs_workload::boolean::json_bool("strict", v)
572 })?;
573
574 if assertions.is_empty() && relevancy.is_none() && admission.is_none() {
575 return Ok((inner, None));
576 }
577
578 let expected_wire_name = match &relevancy {
590 Some(cfg) => {
591 let name = cfg
592 .expected_binding
593 .trim_matches(|c| c == '{' || c == '}')
594 .to_string();
595 fx.register_pull(&name).map_err(|e| {
596 format!("op '{op}' relevancy.expected: {e}", op = template.name,)
597 })?;
598 Some(name)
599 }
600 None => None,
601 };
602 if let Some(name) = relevancy.as_ref().and_then(|c| c.admitted_binding.as_ref()) {
606 fx.register_pull(name)
607 .map_err(|e| format!("op '{op}' relevancy.admitted: {e}", op = template.name))?;
608 }
609 if let Some(cfg) = &admission {
610 let wire = &cfg.admitted_wire;
611 crate::admission::require_admitted_rows(
612 &template.name,
613 wire,
614 program.and_then(|p| p.output_port_type(wire).or_else(|| p.input_port_type(wire))),
615 )?;
616 fx.register_pull(&cfg.admitted_wire)
617 .map_err(|e| format!("op '{op}' admission.admitted: {e}", op = template.name))?;
618 }
619
620 if let (Some(cells), Some(config)) = (&cells, &relevancy) {
621 cells.set_relevancy(&config.functions, config.k, config.r);
622 }
623 let mut totals = match &relevancy {
624 Some(config) => ValidationMetrics::new(labels, &config.functions, config.k, config.r),
625 None => ValidationMetrics::assertions_only(),
626 };
627 totals.cells = cells.clone();
628 let metrics = Arc::new(totals);
629
630 let actual_projection = match &relevancy {
636 Some(cfg) => actual_projection_for(template, "relevancy", &cfg.actual_field)?,
637 None => None,
638 };
639 let admission_projection = match &admission {
640 Some(cfg) => actual_projection_for(template, "admission", &cfg.actual_field)?,
641 None => None,
642 };
643
644 let wrapper = Arc::new(Self {
645 inner,
646 assertions,
647 relevancy,
648 expected_wire_name,
649 actual_projection,
650 admission,
651 admission_projection,
652 metrics: metrics.clone(),
653 cells,
654 strict,
655 });
656 Ok((wrapper, Some(metrics)))
657 }
658
659 fn actual_values(
668 result: &OpResult,
669 ctx: &crate::fixture::ExecCtx<'_>,
670 field: &str,
671 projection: Option<&ActualProjection>,
672 ) -> Vec<i64> {
673 if let Some(proj) = projection {
674 let projected = result.body.as_ref().and_then(|b| {
675 crate::wrappers::result::evaluate_path_value(&b.to_json(), &proj.segs, proj.target)
676 });
677 return projected
678 .as_ref()
679 .map(resolve_expected_from_value)
680 .unwrap_or_default();
681 }
682 match ctx.wires.get(field) {
683 Some(v) if !matches!(v, polydat::ast::Value::None) => resolve_expected_from_value(&v),
684 _ => extract_actual_indices(result, field),
685 }
686 }
687}
688
689fn actual_projection_for(
696 template: &nmbrs_workload::model::ParsedOp,
697 evaluation: &str,
698 actual_field: &str,
699) -> Result<Option<ActualProjection>, String> {
700 let mut raw: Option<String> = None;
701 if let Some(spec) = template.result.as_ref() {
702 spec.walk_fragments(|frag| {
703 if let nmbrs_workload::model::ResultFragment::Named { name, source } = frag
704 && name == actual_field
705 {
706 let s = source.trim();
707 if s != "count" && s != "ok" && !s.contains('(') {
708 raw = Some(s.to_string());
709 }
710 }
711 });
712 }
713 let Some(path) = raw else {
714 return Ok(None);
715 };
716 let segs = crate::wrappers::result::parse_path_expr(&path).map_err(|e| {
717 format!(
718 "op '{op}' {evaluation}.actual '{actual_field}': result binding path: {e}",
719 op = template.name,
720 )
721 })?;
722 let target = template
723 .abstract_interface
724 .as_ref()
725 .and_then(|i| i.results.get(actual_field))
726 .copied();
727 Ok(Some(ActualProjection { segs, target }))
728}
729
730impl WrappingDispenser for ValidatingDispenser {}
731
732impl OpDispenser for ValidatingDispenser {
733 fn inner_dispenser(&self) -> Option<&dyn OpDispenser> {
740 Some(self.inner.as_ref())
741 }
742
743 fn execute<'a>(
744 &'a self,
745 cycle: u64,
746 ctx: &'a crate::fixture::ExecCtx<'a>,
747 ) -> std::pin::Pin<
748 Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
749 > {
750 Box::pin(async move {
751 let result = self.inner.execute(cycle, ctx).await?;
752
753 let mut failed_assertions: Vec<String> = Vec::new();
760 for assertion in &self.assertions {
761 if !assertion.check(&result) {
762 failed_assertions.push(describe_assertion_failure(assertion, &result));
763 }
764 }
765
766 let cell = match &self.cells {
769 Some(cells) => Some(cells.resolve(ctx.wires, cycle)?),
770 None => None,
771 };
772
773 if let Some(config) = &self.relevancy {
775 let actual_ordered = Self::actual_values(
776 &result,
777 ctx,
778 &config.actual_field,
779 self.actual_projection.as_ref(),
780 );
781 let name = self.expected_wire_name.as_deref().expect(
787 "ValidatingDispenser invariant violated: relevancy is \
788 configured but expected_wire_name was not stored. \
789 Construct via ValidatingDispenser::wrap.",
790 );
791 let raw_value = ctx.wires.get(name);
792 let expected_raw = raw_value
793 .as_ref()
794 .map(resolve_expected_from_value)
795 .unwrap_or_default();
796
797 let is_index_row = matches!(
804 raw_value,
805 Some(polydat::ast::Value::VecI32(_) | polydat::ast::Value::VecI64(_))
806 );
807 if expected_raw.is_empty() && !is_index_row {
808 let available: Vec<String> = ctx.wires.names().collect();
809 return Err(ExecutionError::Op(crate::adapter::AdapterError {
810 error_name: "relevancy_error".into(),
811 message: format!(
812 "relevancy: no ground truth for '{name}'. \
813 Available wires: {available:?}. \
814 Ensure the binding exists in the Polydat program.",
815 ),
816 retryable: false,
817 }));
818 }
819 if actual_ordered.is_empty() && result.body.is_some() {
820 if self.metrics.passed() + self.metrics.failed() == 0 {
822 let indent = crate::scene_tree::running_phase_indent();
823 crate::observer::log(
824 crate::observer::LogLevel::Warn,
825 &format!(
826 "{indent}relevancy: no values extracted for field '{}' from result",
827 config.actual_field
828 ),
829 );
830 if let Some(body) = &result.body {
831 let preview =
832 serde_json::to_string(&body.to_json()).unwrap_or_default();
833 crate::observer::log(
834 crate::observer::LogLevel::Warn,
835 &format!(
836 "{indent} result preview: {}",
837 &preview[..preview.len().min(300)]
838 ),
839 );
840 }
841 }
842 }
843
844 if let Some(r) = config.r {
862 let admitted = match &config.admitted_binding {
863 None => None,
864 Some(wire) => {
865 let count = ctx
866 .wires
867 .get(wire)
868 .and_then(value_to_u64_for_count)
869 .ok_or_else(|| {
870 ExecutionError::Op(crate::adapter::AdapterError {
871 error_name: "relevancy_error".into(),
872 message: format!(
873 "relevancy: `admitted: {wire}` did not yield a \
874 row count at cycle {cycle}",
875 ),
876 retryable: false,
877 })
878 })?;
879 Some(count)
880 }
881 };
882 let required = relevancy::required_rows(r, admitted);
883 if actual_ordered.len() != required {
884 let message = match admitted {
885 None => format!(
886 "relevancy: expected exactly r={r} results from \
887 retrieval, got {} (k-recall@r contract). Either \
888 size the query LIMIT to {r}, or remove the `r:` \
889 declaration to fall back to first-k semantics.",
890 actual_ordered.len(),
891 ),
892 Some(n) => format!(
893 "relevancy: expected exactly {required} results from \
894 retrieval, got {} (k-recall@r contract: r={r}, and \
895 the predicate admits {n} rows, so min(r, admitted) = \
896 {required}).",
897 actual_ordered.len(),
898 ),
899 };
900 return Err(ExecutionError::Op(crate::adapter::AdapterError {
901 error_name: "relevancy_error".into(),
902 message,
903 retryable: false,
904 }));
905 }
906 }
907
908 let r_window = config.r.unwrap_or(config.k);
924 let expected_sorted = relevancy::truncate_and_sort(&expected_raw, config.k);
925 let actual_sorted = relevancy::truncate_and_sort(&actual_ordered, r_window);
926 if expected_sorted.is_empty() {
927 self.metrics
928 .relevancy_empty_rows
929 .fetch_add(1, Ordering::Relaxed);
930 if let Some(cell) = &cell {
931 cell.validation()
932 .relevancy_empty_rows
933 .fetch_add(1, Ordering::Relaxed);
934 }
935 }
936
937 for func in &config.functions {
938 let Some(score) =
942 func.compute(&expected_sorted, &actual_sorted, &actual_ordered, config.k)
943 else {
944 continue;
945 };
946 self.metrics.record_relevancy(func.metric_name(), score);
947 if let Some(cell) = &cell {
948 cell.validation()
949 .record_relevancy(func.metric_name(), score);
950 }
951 if crate::observer::trace_enabled() {
961 let intersect =
962 crate::relevancy::intersection_count(&expected_sorted, &actual_sorted);
963 let stats_labels = self
964 .metrics
965 .relevancy_stats
966 .get(func.metric_name())
967 .map(|s| s.labels().clone())
968 .unwrap_or_default();
969 crate::observer::trace(
970 &stats_labels,
971 &format!(
972 "event=relevancy.score cycle={cycle} \
973 fn={func} k={k} r={r} \
974 gt_card={gt} actual_card={ac} \
975 intersect={inter} score={score:.6}",
976 func = func.metric_name(),
977 k = config.k,
978 r = config.r.unwrap_or(config.k),
979 gt = expected_sorted.len(),
980 ac = actual_sorted.len(),
981 inter = intersect,
982 ),
983 );
984 }
985 }
986 }
987
988 if let Some(config) = &self.admission {
993 let returned = Self::actual_values(
994 &result,
995 ctx,
996 &config.actual_field,
997 self.admission_projection.as_ref(),
998 );
999 let wire = &config.admitted_wire;
1000 let admitted = ctx.wires.get(wire).ok_or_else(|| {
1001 ExecutionError::Op(crate::adapter::AdapterError {
1002 error_name: "admission_error".into(),
1003 message: format!(
1004 "admission: no admitted rows for '{wire}' at cycle {cycle}"
1005 ),
1006 retryable: false,
1007 })
1008 })?;
1009 match crate::admission::first_not_admitted(&returned, &admitted) {
1010 Ok(None) => {}
1011 Ok(Some(key)) => failed_assertions.push(format!(
1012 "admission: cycle {cycle} returned row {key}, which its predicate \
1013 does not admit ({} rows returned)",
1014 returned.len(),
1015 )),
1016 Err(why) => {
1017 return Err(ExecutionError::Op(crate::adapter::AdapterError {
1018 error_name: "admission_error".into(),
1019 message: format!("admission: `admitted: {wire}` {why}"),
1020 retryable: false,
1021 }));
1022 }
1023 }
1024 }
1025 let all_pass = failed_assertions.is_empty();
1026
1027 if all_pass {
1028 self.metrics
1029 .validations_passed
1030 .fetch_add(1, Ordering::Relaxed);
1031 if let Some(cell) = &cell {
1032 cell.validation()
1033 .validations_passed
1034 .fetch_add(1, Ordering::Relaxed);
1035 }
1036 } else {
1037 self.metrics
1038 .validations_failed
1039 .fetch_add(1, Ordering::Relaxed);
1040 if let Some(cell) = &cell {
1041 cell.validation()
1042 .validations_failed
1043 .fetch_add(1, Ordering::Relaxed);
1044 }
1045 if self.strict {
1046 return Err(ExecutionError::Op(crate::adapter::AdapterError {
1047 error_name: "validation_failed".into(),
1048 message: format!(
1049 "result validation failed (strict mode): {}",
1050 failed_assertions.join("; "),
1051 ),
1052 retryable: false,
1053 }));
1054 }
1055 }
1056
1057 Ok(result)
1058 })
1059 }
1060}
1061
1062fn describe_assertion_failure(assertion: &AssertionSpec, result: &OpResult) -> String {
1079 let body_tail = match &result.body {
1080 Some(_) => format!("; body: {}", body_excerpt(result)),
1081 None => String::new(),
1082 };
1083 let observed_repr = observed_field_repr(&assertion.field, result);
1084 match &assertion.predicate {
1085 AssertionPredicate::MinRows(n) => {
1086 let got = result.body.as_ref().map(|b| b.element_count()).unwrap_or(0);
1087 format!("min_rows: expected ≥{n}, got {got}{body_tail}")
1088 }
1089 AssertionPredicate::Eq(expected) => format!(
1090 "field '{}' eq '{}' failed (observed: {observed_repr}){body_tail}",
1091 assertion.field, expected
1092 ),
1093 AssertionPredicate::NotNull => format!(
1094 "field '{}' must not be null (observed: {observed_repr}){body_tail}",
1095 assertion.field
1096 ),
1097 AssertionPredicate::IsNull => format!(
1098 "field '{}' must be null (observed: {observed_repr}){body_tail}",
1099 assertion.field
1100 ),
1101 AssertionPredicate::Gte(t) => format!(
1102 "field '{}' >= {t} failed (observed: {observed_repr}){body_tail}",
1103 assertion.field
1104 ),
1105 AssertionPredicate::MalformedBound { key, raw } => format!(
1106 "field '{}': `{key}: {raw}` is not a number — a numeric bound \
1107 must be a number (`{key}: 5`) or a string holding one \
1108 (`{key}: \"5\"`). If that is a `{{placeholder}}`, it did not \
1109 resolve.",
1110 assertion.field
1111 ),
1112 AssertionPredicate::Lte(t) => format!(
1113 "field '{}' <= {t} failed (observed: {observed_repr}){body_tail}",
1114 assertion.field
1115 ),
1116 AssertionPredicate::Contains(sub) => format!(
1117 "field '{}' contains '{}' failed (observed: {observed_repr}){body_tail}",
1118 assertion.field, sub
1119 ),
1120 }
1121}
1122
1123fn observed_field_repr(field: &str, result: &OpResult) -> String {
1149 let Some(body) = &result.body else {
1150 return "<no body returned by op — verify clause cannot read fields>".to_string();
1151 };
1152 let json = body.to_json();
1153 if let Some(v) = extract_field_from_json(&json, field) {
1154 let repr = match v {
1155 serde_json::Value::String(s) => format!("\"{s}\""),
1156 other => other.to_string(),
1157 };
1158 return truncate_for_message(&repr, 160);
1159 }
1160 match &json {
1165 serde_json::Value::Object(map) => {
1166 let keys: Vec<&str> = map.keys().map(|s| s.as_str()).collect();
1167 if keys.is_empty() {
1168 "<field absent; body is an empty JSON object>".to_string()
1169 } else {
1170 format!("<field absent; body keys: {keys:?}>")
1171 }
1172 }
1173 serde_json::Value::Array(arr) => {
1174 format!(
1175 "<field absent; body is a JSON array of {} element{}>",
1176 arr.len(),
1177 if arr.len() == 1 { "" } else { "s" },
1178 )
1179 }
1180 serde_json::Value::Null => "<field absent; body is JSON null>".to_string(),
1181 other => {
1182 let short = truncate_for_message(&other.to_string(), 80);
1183 format!("<not-json: {short}>")
1184 }
1185 }
1186}
1187
1188fn body_excerpt(result: &OpResult) -> String {
1194 let Some(body) = &result.body else {
1195 return "<no body>".to_string();
1196 };
1197 truncate_for_message(&body.to_text(), 512)
1198}
1199
1200fn truncate_for_message(s: &str, max: usize) -> String {
1204 if s.chars().count() <= max {
1205 return s.to_string();
1206 }
1207 let cut: String = s.chars().take(max.saturating_sub(1)).collect();
1208 format!("{cut}…")
1209}
1210
1211fn numeric_bound(v: &serde_json::Value) -> Option<f64> {
1239 v.as_f64()
1240 .or_else(|| v.as_str().and_then(|s| s.trim().parse::<f64>().ok()))
1241}
1242
1243fn parse_assertions(template: &nmbrs_workload::model::ParsedOp) -> Vec<AssertionSpec> {
1244 let Some(verify) = template.params.get("verify") else {
1245 return Vec::new();
1246 };
1247
1248 let Some(items) = verify.as_array() else {
1249 return Vec::new();
1250 };
1251
1252 let mut assertions = Vec::new();
1253 for item in items {
1254 let Some(obj) = item.as_object() else {
1255 continue;
1256 };
1257
1258 if let Some(v) = obj.get("min_rows") {
1261 let n = v.as_u64().unwrap_or(0);
1262 assertions.push(AssertionSpec {
1263 field: String::new(), predicate: AssertionPredicate::MinRows(n),
1265 });
1266 continue;
1267 }
1268
1269 let Some(field) = obj.get("field").and_then(|v| v.as_str()) else {
1270 continue;
1271 };
1272
1273 let predicate = if let Some(v) = obj.get("eq") {
1274 AssertionPredicate::Eq(json_value_as_string(v))
1275 } else if let Some(v) = obj.get("gte") {
1276 match numeric_bound(v) {
1277 Some(t) => AssertionPredicate::Gte(t),
1278 None => AssertionPredicate::MalformedBound {
1279 key: "gte".into(),
1280 raw: json_value_as_string(v),
1281 },
1282 }
1283 } else if let Some(v) = obj.get("lte") {
1284 match numeric_bound(v) {
1285 Some(t) => AssertionPredicate::Lte(t),
1286 None => AssertionPredicate::MalformedBound {
1287 key: "lte".into(),
1288 raw: json_value_as_string(v),
1289 },
1290 }
1291 } else if let Some(v) = obj.get("contains") {
1292 AssertionPredicate::Contains(json_value_as_string(v))
1293 } else if let Some(v) = obj.get("is") {
1294 match v.as_str().unwrap_or("").to_lowercase().as_str() {
1295 "not_null" | "notnull" => AssertionPredicate::NotNull,
1296 "null" => AssertionPredicate::IsNull,
1297 _ => continue,
1298 }
1299 } else {
1300 continue;
1301 };
1302
1303 assertions.push(AssertionSpec {
1304 field: field.to_string(),
1305 predicate,
1306 });
1307 }
1308 assertions
1309}
1310
1311const RELEVANCY_VOCAB: &[&str] = &["actual", "expected", "k", "r", "admitted", "functions"];
1316
1317fn parse_relevancy(
1336 template: &nmbrs_workload::model::ParsedOp,
1337 _program: Option<&polydat::kernel::PolydatProgram>,
1338 wires: Option<&dyn WireSource>,
1339) -> Result<Option<RelevancyConfig>, String> {
1340 let Some(rel) = template.params.get("relevancy") else {
1341 return Ok(None);
1342 };
1343 let obj = rel.as_object().ok_or_else(|| {
1344 format!(
1345 "op '{}': relevancy: expected a mapping, got {kind}",
1346 template.name,
1347 kind = match rel {
1348 serde_json::Value::Null => "null",
1349 serde_json::Value::Bool(_) => "boolean",
1350 serde_json::Value::Number(_) => "number",
1351 serde_json::Value::String(_) => "string",
1352 serde_json::Value::Array(_) => "array",
1353 _ => "unknown",
1354 },
1355 )
1356 })?;
1357
1358 for k in obj.keys() {
1360 if !RELEVANCY_VOCAB.contains(&k.as_str()) {
1361 return Err(format!(
1362 "op '{op}' relevancy: unknown key '{k}'. Allowed: [{vocab}]",
1363 op = template.name,
1364 vocab = RELEVANCY_VOCAB.join(", "),
1365 ));
1366 }
1367 }
1368
1369 let actual_field = obj
1370 .get("actual")
1371 .and_then(|v| v.as_str())
1372 .ok_or_else(|| {
1373 format!(
1374 "op '{}' relevancy: missing required field 'actual' (string column name)",
1375 template.name,
1376 )
1377 })?
1378 .to_string();
1379 let expected_binding = obj
1380 .get("expected")
1381 .and_then(|v| v.as_str())
1382 .ok_or_else(|| {
1383 format!(
1384 "op '{}' relevancy: missing required field 'expected' (binding reference)",
1385 template.name,
1386 )
1387 })?
1388 .to_string();
1389
1390 let k_label = format!("op '{}' relevancy.k", template.name);
1391 let k = parse_count_param(obj.get("k"), &k_label, wires)?.ok_or_else(|| {
1392 format!(
1393 "op '{}' relevancy: missing required field 'k' (integer)",
1394 template.name,
1395 )
1396 })? as usize;
1397
1398 let r_label = format!("op '{}' relevancy.r", template.name);
1399 let r: Option<usize> = parse_count_param(obj.get("r"), &r_label, wires)?.map(|n| n as usize);
1400
1401 if let Some(rv) = r
1402 && rv < k
1403 {
1404 return Err(format!(
1405 "op '{op}' relevancy: r={rv} is smaller than k={k}; \
1406 the k-recall@r contract requires r >= k",
1407 op = template.name,
1408 ));
1409 }
1410
1411 let admitted_binding: Option<String> = match obj.get("admitted") {
1415 None => None,
1416 Some(v) => {
1417 let name = v
1418 .as_str()
1419 .map(|s| s.trim().trim_matches(|c| c == '{' || c == '}').trim())
1420 .filter(|s| is_bare_ident(s))
1421 .ok_or_else(|| {
1422 format!(
1423 "op '{op}' relevancy.admitted: expected the name of a wire \
1424 holding the number of rows the predicate admits",
1425 op = template.name,
1426 )
1427 })?;
1428 if r.is_none() {
1429 return Err(format!(
1430 "op '{op}' relevancy: `admitted: {name}` caps the retrieval window \
1431 `r:`, and this op declares no `r:`. Declare `r:` or remove `admitted:`.",
1432 op = template.name,
1433 ));
1434 }
1435 Some(name.to_string())
1436 }
1437 };
1438
1439 let functions: Vec<RelevancyFn> = match obj.get("functions") {
1440 None => vec![RelevancyFn::Recall],
1441 Some(serde_json::Value::Array(arr)) => {
1442 let mut out: Vec<RelevancyFn> = Vec::new();
1443 for (i, v) in arr.iter().enumerate() {
1444 let name = v.as_str().ok_or_else(|| {
1445 format!(
1446 "op '{op}' relevancy.functions[{i}]: expected a string, got {kind}",
1447 op = template.name,
1448 kind = match v {
1449 serde_json::Value::Null => "null",
1450 serde_json::Value::Bool(_) => "boolean",
1451 serde_json::Value::Number(_) => "number",
1452 serde_json::Value::Array(_) => "array",
1453 serde_json::Value::Object(_) => "object",
1454 _ => "unknown",
1455 },
1456 )
1457 })?;
1458 let func = RelevancyFn::parse(name).ok_or_else(|| {
1459 format!(
1460 "op '{op}' relevancy.functions[{i}]: unknown function '{name}'",
1461 op = template.name,
1462 )
1463 })?;
1464 out.push(func);
1465 }
1466 if out.is_empty() {
1467 return Err(format!(
1468 "op '{op}' relevancy.functions: empty list — declare at least one \
1469 function or remove the field to default to [recall]",
1470 op = template.name,
1471 ));
1472 }
1473 out
1474 }
1475 Some(_) => {
1476 return Err(format!(
1477 "op '{op}' relevancy.functions: expected an array of strings",
1478 op = template.name,
1479 ));
1480 }
1481 };
1482
1483 Ok(Some(RelevancyConfig {
1484 actual_field,
1485 expected_binding,
1486 k,
1487 r,
1488 admitted_binding,
1489 functions,
1490 }))
1491}
1492
1493fn parse_count_param(
1505 val: Option<&serde_json::Value>,
1506 field_label: &str,
1507 wires: Option<&dyn WireSource>,
1508) -> Result<Option<u64>, String> {
1509 let Some(v) = val else {
1510 return Ok(None);
1511 };
1512 if let Some(n) = v.as_u64() {
1513 return Ok(Some(n));
1514 }
1515 let s = match v.as_str() {
1516 Some(s) => s,
1517 None => {
1518 return Err(format!(
1519 "{field_label}: expected an integer or numeric string, got {kind}",
1520 kind = match v {
1521 serde_json::Value::Null => "null",
1522 serde_json::Value::Bool(_) => "boolean",
1523 serde_json::Value::Array(_) => "array",
1524 serde_json::Value::Object(_) => "object",
1525 _ => "unsupported value",
1526 },
1527 ));
1528 }
1529 };
1530 let trimmed = s.trim();
1531 if trimmed.starts_with('{') && trimmed.ends_with('}') {
1532 return Err(format!(
1533 "{field_label}: '{trimmed}' was not resolved before parameter parsing — \
1534 this is a placeholder-resolution bug, not a config-time issue. The \
1535 single-read-path resolver should have substituted it from the kernel."
1536 ));
1537 }
1538 if let Some(wires) = wires
1545 && is_bare_ident(trimmed)
1546 && let Some(value) = wires.get(trimmed)
1547 {
1548 return value_to_u64_for_count(value)
1549 .ok_or_else(|| {
1550 format!(
1551 "{field_label}: wire '{trimmed}' resolved but its value is not \
1552 coercible to a non-negative integer"
1553 )
1554 })
1555 .map(Some);
1556 }
1557 match trimmed.parse::<u64>() {
1558 Ok(n) => Ok(Some(n)),
1559 Err(_) => Err(format!(
1560 "{field_label}: '{trimmed}' is not a valid non-negative integer \
1561 (and not declared as a wire name on the op-template kernel)"
1562 )),
1563 }
1564}
1565
1566fn is_bare_ident(s: &str) -> bool {
1570 let mut chars = s.chars();
1571 match chars.next() {
1572 Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
1573 _ => return false,
1574 }
1575 chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
1576}
1577
1578pub(crate) fn value_to_u64_for_count(value: polydat::ast::Value) -> Option<u64> {
1582 use polydat::ast::Value;
1583 match value {
1584 Value::U64(n) => Some(n),
1585 Value::I64(n) => u64::try_from(n).ok(),
1586 Value::Str(s) => crate::runner::parse_count(&s),
1587 Value::F64(f) if f.is_finite() && f >= 0.0 => Some(f as u64),
1588 Value::Bool(true) => Some(1),
1589 Value::Bool(false) => Some(0),
1590 _ => None,
1591 }
1592}
1593
1594fn extract_actual_indices(result: &OpResult, field: &str) -> Vec<i64> {
1602 let Some(body) = &result.body else {
1603 return Vec::new();
1604 };
1605 extract_indices_from_json(&body.to_json(), field)
1606}
1607
1608fn extract_indices_from_json(json: &serde_json::Value, field: &str) -> Vec<i64> {
1610 match json {
1611 serde_json::Value::Array(rows) => rows
1612 .iter()
1613 .filter_map(|row| json_field_as_i64(row.get(field)?))
1614 .collect(),
1615 serde_json::Value::Object(obj) => {
1616 if let Some(rows) = obj.get("rows") {
1617 return extract_indices_from_json(rows, field);
1618 }
1619 obj.get(field)
1620 .and_then(json_field_as_i64)
1621 .into_iter()
1622 .collect()
1623 }
1624 _ => Vec::new(),
1625 }
1626}
1627
1628fn json_field_as_i64(v: &serde_json::Value) -> Option<i64> {
1630 v.as_i64().or_else(|| v.as_str()?.parse().ok())
1631}
1632
1633fn resolve_expected_from_value(value: &polydat::ast::Value) -> Vec<i64> {
1649 match value {
1650 polydat::ast::Value::VecI32(slice) => slice.as_slice().iter().map(|&x| x as i64).collect(),
1652 polydat::ast::Value::VecI64(slice) => slice.as_slice().to_vec(),
1653 polydat::ast::Value::VecF32(slice) => {
1654 slice.as_slice().iter().map(|&x| x as i64).collect()
1659 }
1660 polydat::ast::Value::VecF64(slice) => slice.as_slice().iter().map(|&x| x as i64).collect(),
1661 polydat::ast::Value::Json(j) => match &**j {
1665 serde_json::Value::Array(elems) => elems.iter().filter_map(json_field_as_i64).collect(),
1666 other => json_field_as_i64(other).into_iter().collect(),
1667 },
1668 polydat::ast::Value::Str(s) => parse_int_array(s),
1669 polydat::ast::Value::U64(v) => vec![*v as i64],
1670 _ => {
1671 let s = value.to_display_string();
1673 parse_int_array(&s)
1674 }
1675 }
1676}
1677
1678fn parse_int_array(s: &str) -> Vec<i64> {
1682 let trimmed = s.trim().trim_start_matches('[').trim_end_matches(']');
1683 trimmed
1684 .split(|c: char| c == ',' || c.is_whitespace())
1685 .filter(|s| !s.is_empty())
1686 .filter_map(|s| s.trim().parse::<i64>().ok())
1687 .collect()
1688}
1689
1690fn extract_field_from_json<'a>(
1692 json: &'a serde_json::Value,
1693 field: &str,
1694) -> Option<&'a serde_json::Value> {
1695 match json {
1696 serde_json::Value::Object(obj) => obj.get(field).or_else(|| {
1697 obj.get("rows")
1698 .and_then(|r| r.as_array())
1699 .and_then(|rows| rows.first())
1700 .and_then(|row| row.get(field))
1701 }),
1702 serde_json::Value::Array(rows) => rows.first().and_then(|row| row.get(field)),
1703 _ => None,
1704 }
1705}
1706
1707fn json_value_as_string(v: &serde_json::Value) -> String {
1709 match v {
1710 serde_json::Value::String(s) => s.clone(),
1711 other => other.to_string(),
1712 }
1713}
1714
1715#[cfg(test)]
1716mod tests {
1717 use super::*;
1718 use crate::adapter::ResultBody;
1719 use std::any::Any;
1720
1721 #[derive(Debug)]
1722 struct JsonBody(serde_json::Value);
1723 impl ResultBody for JsonBody {
1724 fn to_json(&self) -> serde_json::Value {
1725 self.0.clone()
1726 }
1727 fn as_any(&self) -> &dyn Any {
1728 self
1729 }
1730 }
1731
1732 #[test]
1733 fn parse_int_array_bracket_format() {
1734 assert_eq!(parse_int_array("[1, 5, 12, 23]"), vec![1, 5, 12, 23]);
1735 }
1736
1737 #[test]
1744 fn core_op_params_disjoint_from_owned_fields() {
1745 let registry = crate::wrapper_registry::WrapperRegistry::from_inventory();
1746 let owned = registry.all_owned_fields();
1747 let dupes: Vec<&str> = CORE_OP_PARAMS
1748 .iter()
1749 .copied()
1750 .filter(|p| owned.contains(p))
1751 .collect();
1752 assert!(
1753 dupes.is_empty(),
1754 "these CORE_OP_PARAMS are already wrapper-owned (remove them — \
1755 the guard accepts them via WrapperRegistry::owns_field): {dupes:?}",
1756 );
1757 }
1758
1759 #[test]
1765 fn wrapper_field_accepted_without_cli_or_core_membership() {
1766 let registry = crate::wrapper_registry::WrapperRegistry::from_inventory();
1767 assert!(
1768 registry.owns_field("readout"),
1769 "readout must be registry-owned"
1770 );
1771 assert!(
1772 registry.owns_field("errors"),
1773 "errors must be registry-owned (was riding the CLI hatch)"
1774 );
1775 assert!(
1776 registry.owns_field("tries"),
1777 "tries must be registry-owned (was riding the CLI hatch)"
1778 );
1779 assert!(
1780 !CORE_OP_PARAMS.contains(&"readout"),
1781 "readout should NOT be in CORE_OP_PARAMS — it's wrapper-owned"
1782 );
1783 }
1784
1785 #[test]
1786 fn parse_int_array_comma_format() {
1787 assert_eq!(parse_int_array("1,5,12,23"), vec![1, 5, 12, 23]);
1788 }
1789
1790 #[test]
1791 fn parse_int_array_space_format() {
1792 assert_eq!(parse_int_array("1 5 12 23"), vec![1, 5, 12, 23]);
1793 }
1794
1795 #[test]
1796 fn parse_int_array_empty() {
1797 assert_eq!(parse_int_array("[]"), Vec::<i64>::new());
1798 assert_eq!(parse_int_array(""), Vec::<i64>::new());
1799 }
1800
1801 #[test]
1802 fn extract_indices_from_json_array() {
1803 let json = serde_json::json!([
1804 {"key": 5, "distance": 0.1},
1805 {"key": 12, "distance": 0.2},
1806 {"key": 3, "distance": 0.3},
1807 ]);
1808 assert_eq!(extract_indices_from_json(&json, "key"), vec![5, 12, 3]);
1809 }
1810
1811 #[test]
1812 fn extract_indices_from_json_rows_wrapper() {
1813 let json = serde_json::json!({
1814 "rows": [
1815 {"key": 5},
1816 {"key": 12},
1817 ]
1818 });
1819 assert_eq!(extract_indices_from_json(&json, "key"), vec![5, 12]);
1820 }
1821
1822 #[test]
1823 fn assertion_not_null() {
1824 let result = OpResult {
1825 body: Some(Box::new(JsonBody(serde_json::json!({"name": "alice"})))),
1826 skipped: false,
1827 };
1828 let spec = AssertionSpec {
1829 field: "name".into(),
1830 predicate: AssertionPredicate::NotNull,
1831 };
1832 assert!(spec.check(&result));
1833
1834 let spec_missing = AssertionSpec {
1835 field: "age".into(),
1836 predicate: AssertionPredicate::NotNull,
1837 };
1838 assert!(!spec_missing.check(&result));
1839 }
1840
1841 #[test]
1842 fn assertion_eq() {
1843 let result = OpResult {
1844 body: Some(Box::new(JsonBody(serde_json::json!({"status": "ok"})))),
1845 skipped: false,
1846 };
1847 let spec = AssertionSpec {
1848 field: "status".into(),
1849 predicate: AssertionPredicate::Eq("ok".into()),
1850 };
1851 assert!(spec.check(&result));
1852
1853 let spec_fail = AssertionSpec {
1854 field: "status".into(),
1855 predicate: AssertionPredicate::Eq("error".into()),
1856 };
1857 assert!(!spec_fail.check(&result));
1858 }
1859
1860 #[test]
1861 fn assertion_gte() {
1862 let result = OpResult {
1863 body: Some(Box::new(JsonBody(serde_json::json!({"balance": 42.5})))),
1864 skipped: false,
1865 };
1866 let spec = AssertionSpec {
1867 field: "balance".into(),
1868 predicate: AssertionPredicate::Gte(0.0),
1869 };
1870 assert!(spec.check(&result));
1871
1872 let spec_fail = AssertionSpec {
1873 field: "balance".into(),
1874 predicate: AssertionPredicate::Gte(100.0),
1875 };
1876 assert!(!spec_fail.check(&result));
1877 }
1878
1879 #[test]
1880 fn assertion_no_body() {
1881 let result = OpResult {
1882 body: None,
1883 skipped: false,
1884 };
1885 let spec = AssertionSpec {
1886 field: "anything".into(),
1887 predicate: AssertionPredicate::IsNull,
1888 };
1889 assert!(spec.check(&result));
1890
1891 let spec_not_null = AssertionSpec {
1892 field: "anything".into(),
1893 predicate: AssertionPredicate::NotNull,
1894 };
1895 assert!(!spec_not_null.check(&result));
1896 }
1897
1898 #[derive(Debug)]
1903 struct CountedBody {
1904 rows: Vec<serde_json::Value>,
1905 }
1906 impl ResultBody for CountedBody {
1907 fn to_json(&self) -> serde_json::Value {
1908 serde_json::Value::Array(self.rows.clone())
1909 }
1910 fn as_any(&self) -> &dyn Any {
1911 self
1912 }
1913 fn element_count(&self) -> u64 {
1914 self.rows.len() as u64
1915 }
1916 }
1917
1918 #[test]
1919 fn assertion_min_rows_passes_when_threshold_met() {
1920 let result = OpResult {
1921 body: Some(Box::new(CountedBody {
1922 rows: vec![
1923 serde_json::json!({"index_name": "vec_idx"}),
1924 serde_json::json!({"index_name": "meta_idx"}),
1925 ],
1926 })),
1927 skipped: false,
1928 };
1929 let spec = AssertionSpec {
1930 field: String::new(),
1931 predicate: AssertionPredicate::MinRows(1),
1932 };
1933 assert!(spec.check(&result));
1934
1935 let spec_two = AssertionSpec {
1936 field: String::new(),
1937 predicate: AssertionPredicate::MinRows(2),
1938 };
1939 assert!(spec_two.check(&result));
1940 }
1941
1942 #[test]
1943 fn assertion_min_rows_fails_when_below_threshold() {
1944 let result = OpResult {
1946 body: Some(Box::new(CountedBody { rows: Vec::new() })),
1947 skipped: false,
1948 };
1949 let spec = AssertionSpec {
1950 field: String::new(),
1951 predicate: AssertionPredicate::MinRows(1),
1952 };
1953 assert!(!spec.check(&result));
1954
1955 let result_none = OpResult {
1957 body: None,
1958 skipped: false,
1959 };
1960 assert!(!spec.check(&result_none));
1961 }
1962
1963 #[test]
1964 fn parse_assertions_min_rows_from_yaml() {
1965 let mut template = nmbrs_workload::model::ParsedOp::simple("await", "test");
1969 template.params.insert(
1970 "verify".into(),
1971 serde_json::json!([
1972 {"min_rows": 1},
1973 ]),
1974 );
1975 let assertions = parse_assertions(&template);
1976 assert_eq!(assertions.len(), 1);
1977 match &assertions[0].predicate {
1978 AssertionPredicate::MinRows(n) => assert_eq!(*n, 1),
1979 other => panic!("expected MinRows(1), got {other:?}"),
1980 }
1981 }
1982
1983 #[test]
1984 fn eq_failure_includes_body_and_distinguishes_absent_vs_not_json() {
1985 let result = OpResult {
1990 body: Some(Box::new(JsonBody(serde_json::json!({
1991 "value": null, "request": {"type": "exec"}
1992 })))),
1993 skipped: false,
1994 };
1995 let spec = AssertionSpec {
1996 field: "status".into(),
1997 predicate: AssertionPredicate::Eq("200".into()),
1998 };
1999 let msg = describe_assertion_failure(&spec, &result);
2000 assert!(
2001 msg.contains("field absent"),
2002 "json-without-field should mark observed as absent, got: {msg}"
2003 );
2004 assert!(
2005 msg.contains("body keys"),
2006 "absent message should enumerate present keys, got: {msg}"
2007 );
2008 assert!(
2009 msg.contains("\"value\"") && msg.contains("\"request\""),
2010 "key list should include both present keys, got: {msg}"
2011 );
2012 assert!(msg.contains("body: "), "body excerpt missing: {msg}");
2013 assert!(
2014 msg.contains("\"request\""),
2015 "body excerpt should echo the actual JSON: {msg}"
2016 );
2017
2018 #[derive(Debug)]
2022 struct PlainBody(String);
2023 impl ResultBody for PlainBody {
2024 fn to_json(&self) -> serde_json::Value {
2025 serde_json::Value::String(self.0.clone())
2026 }
2027 fn as_any(&self) -> &dyn Any {
2028 self
2029 }
2030 fn to_text(&self) -> String {
2031 self.0.clone()
2032 }
2033 }
2034 let text_result = OpResult {
2035 body: Some(Box::new(PlainBody(
2036 "<html><body>404 Not Found</body></html>".into(),
2037 ))),
2038 skipped: false,
2039 };
2040 let msg2 = describe_assertion_failure(&spec, &text_result);
2041 assert!(
2042 msg2.contains("not-json"),
2043 "text body should mark observed as not-json, got: {msg2}"
2044 );
2045 assert!(
2046 msg2.contains("404 Not Found"),
2047 "body excerpt should include the text: {msg2}"
2048 );
2049 }
2050
2051 #[test]
2056 fn eq_failure_with_no_body_explains_situation() {
2057 let result = OpResult {
2058 body: None,
2059 skipped: false,
2060 };
2061 let spec = AssertionSpec {
2062 field: "status".into(),
2063 predicate: AssertionPredicate::Eq("200".into()),
2064 };
2065 let msg = describe_assertion_failure(&spec, &result);
2066 assert!(
2067 msg.contains("no body returned by op"),
2068 "no-body case should explain why the field can't be read, got: {msg}"
2069 );
2070 assert!(
2071 !msg.contains("body: "),
2072 "no-body case should suppress the redundant body excerpt, got: {msg}"
2073 );
2074 }
2075
2076 #[test]
2077 fn min_rows_failure_describes_actual_vs_expected() {
2078 let result = OpResult {
2082 body: Some(Box::new(CountedBody { rows: Vec::new() })),
2083 skipped: false,
2084 };
2085 let spec = AssertionSpec {
2086 field: String::new(),
2087 predicate: AssertionPredicate::MinRows(1),
2088 };
2089 let msg = describe_assertion_failure(&spec, &result);
2090 assert!(msg.contains("min_rows"), "got: {msg}");
2091 assert!(msg.contains("≥1"), "got: {msg}");
2092 assert!(msg.contains("got 0"), "got: {msg}");
2093 }
2094
2095 #[test]
2096 fn validation_metrics_record_relevancy() {
2097 let labels = Labels::of("activity", "test");
2098 let metrics = ValidationMetrics::new(
2099 &labels,
2100 &[RelevancyFn::Recall, RelevancyFn::Precision],
2101 10,
2102 Some(20),
2103 );
2104 assert!(metrics.relevancy_stats.contains_key("recall"));
2108 assert!(metrics.relevancy_stats.contains_key("precision"));
2109 assert!(!metrics.relevancy_stats.contains_key("f1"));
2110
2111 let recall_labels = metrics.relevancy_stats["recall"].labels();
2113 assert_eq!(recall_labels.get("k"), Some("10"));
2114 assert_eq!(recall_labels.get("r"), Some("20"));
2115
2116 metrics.record_relevancy("recall", 0.85);
2117 metrics.record_relevancy("recall", 0.90);
2118 let snap = metrics.relevancy_stats["recall"].snapshot();
2119 assert_eq!(snap.len(), 2);
2120 }
2121
2122 #[test]
2123 fn validation_metrics_r_defaults_to_k() {
2124 let labels = Labels::of("activity", "test");
2125 let metrics = ValidationMetrics::new(&labels, &[RelevancyFn::Recall], 100, None);
2128 let l = metrics.relevancy_stats["recall"].labels();
2129 assert_eq!(l.get("k"), Some("100"));
2130 assert_eq!(l.get("r"), Some("100"));
2131 }
2132
2133 #[test]
2134 fn resolve_expected_string_array_form() {
2135 let v = polydat::ast::Value::Str("[1, 5, 12, 23]".into());
2136 assert_eq!(resolve_expected_from_value(&v), vec![1, 5, 12, 23]);
2137 }
2138
2139 #[test]
2140 fn resolve_expected_string_csv_form() {
2141 let v = polydat::ast::Value::Str("1,5,12".into());
2142 assert_eq!(resolve_expected_from_value(&v), vec![1, 5, 12]);
2143 }
2144
2145 #[test]
2146 fn resolve_expected_native_veci32_fast_path() {
2147 use polydat::ast::{SliceArc, Value};
2151 let slice = SliceArc::<i32>::from_vec(vec![1, 5, 12, 23, 100]);
2152 let v = Value::VecI32(slice);
2153 assert_eq!(resolve_expected_from_value(&v), vec![1, 5, 12, 23, 100]);
2154 }
2155
2156 #[test]
2157 fn resolve_expected_native_vecf32_fast_path() {
2158 use polydat::ast::{SliceArc, Value};
2161 let slice = SliceArc::<f32>::from_vec(vec![1.0, 2.0, 3.0]);
2162 let v = Value::VecF32(slice);
2163 assert_eq!(resolve_expected_from_value(&v), vec![1, 2, 3]);
2164 }
2165
2166 #[test]
2167 fn parse_relevancy_from_params() {
2168 let mut template = nmbrs_workload::model::ParsedOp::simple("test", "SELECT key FROM t");
2169 template.params.insert(
2170 "relevancy".into(),
2171 serde_json::json!({
2172 "actual": "key",
2173 "expected": "{ground_truth}",
2174 "k": 10,
2175 "functions": ["recall", "precision", "f1"]
2176 }),
2177 );
2178 let config = parse_relevancy(&template, None, None).unwrap().unwrap();
2179 assert_eq!(config.actual_field, "key");
2180 assert_eq!(config.expected_binding, "{ground_truth}");
2181 assert_eq!(config.k, 10);
2182 assert!(config.r.is_none(), "r should default to None when absent");
2183 assert_eq!(config.functions.len(), 3);
2184 assert_eq!(config.functions[0], RelevancyFn::Recall);
2185 assert_eq!(config.functions[1], RelevancyFn::Precision);
2186 assert_eq!(config.functions[2], RelevancyFn::F1);
2187 }
2188
2189 #[test]
2190 fn parse_relevancy_with_r_for_k_recall_at_r() {
2191 let mut template = nmbrs_workload::model::ParsedOp::simple("test", "SELECT key FROM t");
2195 template.params.insert(
2196 "relevancy".into(),
2197 serde_json::json!({
2198 "actual": "key",
2199 "expected": "{ground_truth}",
2200 "k": 10,
2201 "r": 100,
2202 "functions": ["recall"],
2203 }),
2204 );
2205 let config = parse_relevancy(&template, None, None).unwrap().unwrap();
2206 assert_eq!(config.k, 10);
2207 assert_eq!(config.r, Some(100));
2208 }
2209
2210 #[test]
2211 fn parse_relevancy_r_accepts_string_form() {
2212 let mut template = nmbrs_workload::model::ParsedOp::simple("test", "SELECT key FROM t");
2213 template.params.insert(
2214 "relevancy".into(),
2215 serde_json::json!({
2216 "actual": "key",
2217 "expected": "{ground_truth}",
2218 "k": "10",
2219 "r": "100",
2220 }),
2221 );
2222 let config = parse_relevancy(&template, None, None).unwrap().unwrap();
2223 assert_eq!(config.k, 10);
2224 assert_eq!(config.r, Some(100));
2225 }
2226
2227 #[test]
2228 fn parse_relevancy_missing() {
2229 let template = nmbrs_workload::model::ParsedOp::simple("test", "INSERT");
2230 assert!(parse_relevancy(&template, None, None).unwrap().is_none());
2231 }
2232
2233 #[test]
2234 fn parse_relevancy_k_and_r_accept_bare_wire_names() {
2235 let kernel = crate::scope_kernel::ScopeKernel::compile(
2240 "input cycle: u64\n\
2241 const k := 10\n\
2242 const limit := 100\n",
2243 )
2244 .expect("compile scope kernel wires");
2245 let wires: &dyn WireSource = &kernel;
2246
2247 let mut template = nmbrs_workload::model::ParsedOp::simple("test", "SELECT key FROM t");
2248 template.params.insert(
2249 "relevancy".into(),
2250 serde_json::json!({
2251 "actual": "key",
2252 "expected": "{ground_truth}",
2253 "k": "k", "r": "limit", "functions": ["recall"],
2256 }),
2257 );
2258 let config = parse_relevancy(&template, None, Some(wires))
2259 .unwrap()
2260 .unwrap();
2261 assert_eq!(config.k, 10, "bare `k:` resolved through wires");
2262 assert_eq!(config.r, Some(100), "bare `r:` resolved through wires");
2263 }
2264
2265 #[test]
2266 fn parse_relevancy_bare_name_falls_through_to_int_parse_when_no_kernel() {
2267 let mut template = nmbrs_workload::model::ParsedOp::simple("test", "SELECT key FROM t");
2271 template.params.insert(
2272 "relevancy".into(),
2273 serde_json::json!({
2274 "actual": "key",
2275 "expected": "{ground_truth}",
2276 "k": "k",
2277 "functions": ["recall"],
2278 }),
2279 );
2280 let err = parse_relevancy(&template, None, None).unwrap_err();
2281 assert!(
2282 err.contains("'k' is not a valid non-negative integer"),
2283 "diagnostic should describe the parse failure: {err}"
2284 );
2285 }
2286
2287 #[test]
2293 fn value_predicates_are_vacuous_without_a_body() {
2294 let result = OpResult {
2295 body: None,
2296 ..Default::default()
2297 };
2298 for predicate in [
2299 AssertionPredicate::Eq("200".into()),
2300 AssertionPredicate::Lte(5.0),
2301 AssertionPredicate::Gte(1.0),
2302 AssertionPredicate::Contains("ok".into()),
2303 AssertionPredicate::IsNull,
2304 ] {
2305 let spec = AssertionSpec {
2306 field: "status".into(),
2307 predicate,
2308 };
2309 assert!(
2310 spec.check(&result),
2311 "a value predicate has nothing to contradict it: {:?}",
2312 spec.predicate
2313 );
2314 }
2315 }
2316
2317 #[test]
2321 fn presence_predicates_still_fail_without_a_body() {
2322 let result = OpResult {
2323 body: None,
2324 ..Default::default()
2325 };
2326 let not_null = AssertionSpec {
2327 field: "status".into(),
2328 predicate: AssertionPredicate::NotNull,
2329 };
2330 assert!(
2331 !not_null.check(&result),
2332 "`is: not_null` is how an author demands the field exist"
2333 );
2334 let min_rows = AssertionSpec {
2335 field: String::new(),
2336 predicate: AssertionPredicate::MinRows(1),
2337 };
2338 assert!(
2339 !min_rows.check(&result),
2340 "`min_rows: 1` is how an author demands a non-empty result"
2341 );
2342 }
2343
2344 #[test]
2348 fn malformed_bounds_fail_even_without_a_body() {
2349 let result = OpResult {
2350 body: None,
2351 ..Default::default()
2352 };
2353 let spec = AssertionSpec {
2354 field: "value".into(),
2355 predicate: AssertionPredicate::MalformedBound {
2356 key: "lte".into(),
2357 raw: "{unresolved}".into(),
2358 },
2359 };
2360 assert!(!spec.check(&result));
2361 }
2362
2363 #[test]
2368 fn numeric_bounds_accept_quoted_numbers() {
2369 let mut template = nmbrs_workload::model::ParsedOp::simple("t", "noop");
2370 template.params.insert(
2371 "verify".into(),
2372 serde_json::json!([
2373 {"field": "value", "lte": "5"},
2374 {"field": "value", "gte": " 2 "},
2375 {"field": "other", "lte": 7},
2376 ]),
2377 );
2378 let a = parse_assertions(&template);
2379 assert!(
2380 matches!(a[0].predicate, AssertionPredicate::Lte(t) if t == 5.0),
2381 "quoted lte must parse: {:?}",
2382 a[0].predicate
2383 );
2384 assert!(
2385 matches!(a[1].predicate, AssertionPredicate::Gte(t) if t == 2.0),
2386 "surrounding whitespace is not a malformed bound: {:?}",
2387 a[1].predicate
2388 );
2389 assert!(
2390 matches!(a[2].predicate, AssertionPredicate::Lte(t) if t == 7.0),
2391 "the unquoted form is unchanged: {:?}",
2392 a[2].predicate
2393 );
2394 }
2395
2396 #[test]
2401 fn non_numeric_bounds_are_malformed_not_zero() {
2402 let mut template = nmbrs_workload::model::ParsedOp::simple("t", "noop");
2403 template.params.insert(
2404 "verify".into(),
2405 serde_json::json!([
2406 {"field": "value", "lte": "{unresolved}"},
2407 {"field": "value", "gte": "abc"},
2408 ]),
2409 );
2410 let a = parse_assertions(&template);
2411 for spec in &a {
2412 match &spec.predicate {
2413 AssertionPredicate::MalformedBound { raw, .. } => {
2414 assert!(
2415 !raw.is_empty(),
2416 "the offending text is carried for the message"
2417 );
2418 }
2419 other => panic!("expected MalformedBound, got {other:?}"),
2420 }
2421 }
2422 let msg = format!("{:?}", a[0].predicate);
2425 assert!(
2426 msg.contains("MalformedBound"),
2427 "the predicate stays malformed all the way to reporting: {msg}"
2428 );
2429 }
2430
2431 #[test]
2432 fn parse_assertions_from_params() {
2433 let mut template = nmbrs_workload::model::ParsedOp::simple("test", "SELECT");
2434 template.params.insert(
2435 "verify".into(),
2436 serde_json::json!([
2437 {"field": "name", "is": "not_null"},
2438 {"field": "balance", "gte": 0},
2439 {"field": "status", "eq": "active"},
2440 ]),
2441 );
2442 let assertions = parse_assertions(&template);
2443 assert_eq!(assertions.len(), 3);
2444 assert_eq!(assertions[0].field, "name");
2445 assert!(matches!(
2446 assertions[0].predicate,
2447 AssertionPredicate::NotNull
2448 ));
2449 assert_eq!(assertions[1].field, "balance");
2450 assert!(matches!(assertions[1].predicate, AssertionPredicate::Gte(v) if v == 0.0));
2451 assert_eq!(assertions[2].field, "status");
2452 assert!(matches!(&assertions[2].predicate, AssertionPredicate::Eq(s) if s == "active"));
2453 }
2454
2455 #[test]
2456 fn parse_assertions_missing() {
2457 let template = nmbrs_workload::model::ParsedOp::simple("test", "INSERT");
2458 assert!(parse_assertions(&template).is_empty());
2459 }
2460}