1use std::collections::HashMap;
11use std::sync::Arc;
12
13use crate::adapter::WrappingDispenser;
14use crate::adapter::{ExecutionError, OpDispenser, OpResult};
15use crate::wrapper_registry::{WrapperName, WrapperRegistration, WrapperSubject};
16
17pub const NAME: WrapperName = WrapperName::new("metrics");
19
20fn triggers(s: WrapperSubject) -> bool {
22 let Some(template) = s.op() else {
23 return false;
24 };
25 !template.metrics.is_empty()
26}
27
28fn describe_assignment(s: WrapperSubject) -> Option<String> {
29 let template = s.op()?;
30 if template.metrics.is_empty() {
31 return None;
32 }
33 let mut names: Vec<&str> = template.metrics.keys().map(|s| s.as_str()).collect();
34 names.sort();
35 Some(format!("metrics: emits {}", names.join(", ")))
36}
37
38const FORBIDS_OUTER: &[WrapperName] = &[
45 super::traverse::NAME,
46 super::delay::NAME,
47 crate::validation::WRAPPER_NAME,
48 super::poll::NAME,
49 super::r#if::NAME,
50 super::result::NAME,
57];
58
59inventory::submit! {
60 WrapperRegistration {
61 name: NAME,
62 owned_fields: &[],
66 triggers,
67 requires_inner: &[],
68 forbids_outer: FORBIDS_OUTER,
69 mutually_exclusive_with: &[],
70 describe_assignment,
71 levels: &[crate::wrapper_registry::WrapperLevel::Op],
72 }
73}
74
75pub struct MetricsDispenser {
113 inner: Arc<dyn OpDispenser>,
114 slots: Arc<Vec<MetricSlot>>,
118}
119
120pub(crate) fn publish_gauges_lenient(slots: &[MetricSlot], wires: &dyn crate::wires::WireSource) {
130 for slot in slots {
131 let Some(MetricInstrument::Gauge(g)) = &slot.instrument else {
135 continue;
136 };
137 let Some(value) = wires.get(&slot.binding_name) else {
138 crate::diag!(
139 crate::observer::LogLevel::Debug,
140 "poll gauge '{}': binding '{}' unresolved this iteration",
141 slot.family,
142 slot.binding_name
143 );
144 continue;
145 };
146 let Some(raw) = value_to_f64(&value) else {
147 crate::diag!(
148 crate::observer::LogLevel::Debug,
149 "poll gauge '{}': '{}' non-numeric this iteration",
150 slot.family,
151 slot.value_expr
152 );
153 continue;
154 };
155 let sanitised = slot.format.as_ref().map(|f| f.apply(raw)).unwrap_or(raw);
156 g.set(sanitised);
157 }
158}
159
160pub(crate) struct MetricSlot {
163 family: String,
166 value_expr: String,
171 binding_name: String,
176 format: Option<nmbrs_workload::metric_format::FormatSpec>,
179 instrument: Option<MetricInstrument>,
186 placement: Option<CellPlacement>,
188}
189
190pub(crate) struct CellPlacement {
196 dims: Vec<(String, String)>,
200 parent: Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
202 kind: nmbrs_workload::model::MetricKind,
203 unit: Option<String>,
204 instances: std::sync::Mutex<std::collections::HashMap<String, MetricInstrument>>,
208}
209
210#[derive(Clone)]
219enum MetricInstrument {
220 Gauge(Arc<nmbrs_metrics::instruments::gauge::ValueGauge>),
221 Histogram(Arc<nmbrs_metrics::instruments::histogram::Histogram>),
222 Counter(Arc<nmbrs_metrics::instruments::counter::Counter>),
223}
224
225impl MetricInstrument {
226 fn as_ref(&self) -> nmbrs_metrics::component::InstrumentRef {
229 match self {
230 MetricInstrument::Gauge(g) => nmbrs_metrics::component::InstrumentRef::Gauge(g.clone()),
231 MetricInstrument::Histogram(h) => {
232 nmbrs_metrics::component::InstrumentRef::Histogram(h.clone())
233 }
234 MetricInstrument::Counter(c) => {
235 nmbrs_metrics::component::InstrumentRef::Counter(c.clone())
236 }
237 }
238 }
239}
240
241fn value_to_f64(v: &polydat::ast::Value) -> Option<f64> {
246 match v {
247 polydat::ast::Value::F64(f) => Some(*f),
248 polydat::ast::Value::U64(u) => Some(*u as f64),
249 polydat::ast::Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
250 _ => None,
251 }
252}
253
254pub(crate) struct MetricsWrap {
259 pub(crate) dispenser: Arc<dyn OpDispenser>,
260 pub(crate) slots: Option<Arc<Vec<MetricSlot>>>,
261}
262
263impl MetricsDispenser {
264 pub fn wrap(
283 inner: Arc<dyn OpDispenser>,
284 metrics: &HashMap<String, nmbrs_workload::model::MetricSpec>,
285 component: &mut nmbrs_metrics::component::Component,
286 component_arc: &Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
287 fx: &mut crate::fixture::ScopeFixture,
288 ) -> Result<Arc<dyn OpDispenser>, String> {
289 Self::wrap_with_slots(inner, metrics, component, component_arc, fx).map(|w| w.dispenser)
290 }
291
292 pub(crate) fn wrap_with_slots(
298 inner: Arc<dyn OpDispenser>,
299 metrics: &HashMap<String, nmbrs_workload::model::MetricSpec>,
300 component: &mut nmbrs_metrics::component::Component,
301 component_arc: &Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
305 fx: &mut crate::fixture::ScopeFixture,
306 ) -> Result<MetricsWrap, String> {
307 if metrics.is_empty() {
308 return Ok(MetricsWrap {
309 dispenser: inner,
310 slots: None,
311 });
312 }
313 let mut entries: Vec<_> = metrics.iter().collect();
316 entries.sort_by(|a, b| a.0.cmp(b.0));
317
318 let component_labels = component.effective_labels().clone();
319 let mut slots = Vec::with_capacity(entries.len());
320 for (name, spec) in entries {
321 let family = spec.family.clone().unwrap_or_else(|| name.clone());
322
323 let format = match &spec.format {
324 Some(s) => Some(
325 nmbrs_workload::metric_format::parse_format_spec(s)
326 .map_err(|e| format!("metric '{name}' format: {e}"))?,
327 ),
328 None => None,
329 };
330
331 let kind = spec.kind.unwrap_or_default();
332 let instr_labels = component_labels.with("family", family.clone());
338 let instrument = match kind {
339 nmbrs_workload::model::MetricKind::Gauge => MetricInstrument::Gauge(Arc::new(
340 nmbrs_metrics::instruments::gauge::ValueGauge::new(instr_labels),
341 )),
342 nmbrs_workload::model::MetricKind::Histogram => {
343 MetricInstrument::Histogram(Arc::new(
344 nmbrs_metrics::instruments::histogram::Histogram::new(instr_labels),
345 ))
346 }
347 nmbrs_workload::model::MetricKind::Counter => MetricInstrument::Counter(Arc::new(
348 nmbrs_metrics::instruments::counter::Counter::new(instr_labels),
349 )),
350 };
351
352 let binding_name = crate::scope::synthesize_metric_binding_name(name);
365 let _ = fx.register_pull(&binding_name).map_err(|e| {
366 format!(
367 "metric '{name}' value '{value}': {e} (synthesised binding \
368 '{binding_name}' should have been registered by the \
369 op-template kernel synthesiser — this is a bug)",
370 value = spec.value,
371 )
372 })?;
373
374 let placement = if spec.cell.is_empty() {
387 component.register_instrument_with_unit(
388 family.clone(),
389 spec.unit.clone(),
390 instrument.as_ref(),
391 )?;
392 None
393 } else {
394 let mut dims = Vec::with_capacity(spec.cell.len());
395 for dim in spec.cell.keys() {
396 let wire = crate::scope::synthesize_cell_binding_name(name, dim);
397 let _ = fx.register_pull(&wire).map_err(|e| {
398 format!(
399 "metric '{name}' cell '{dim}': {e} (synthesised \
400 coordinate binding '{wire}' should have been \
401 registered by the op-template kernel synthesiser \
402 — this is a bug)"
403 )
404 })?;
405 dims.push((dim.clone(), wire));
406 }
407 Some(CellPlacement {
408 dims,
409 parent: component_arc.clone(),
410 kind,
411 unit: spec.unit.clone(),
412 instances: std::sync::Mutex::new(std::collections::HashMap::new()),
413 })
414 };
415
416 slots.push(MetricSlot {
417 family,
418 value_expr: spec.value.clone(),
419 binding_name,
420 format,
421 instrument: if placement.is_some() {
422 None
423 } else {
424 Some(instrument)
425 },
426 placement,
427 });
428 }
429
430 let slots = Arc::new(slots);
431 Ok(MetricsWrap {
432 dispenser: Arc::new(Self {
433 inner,
434 slots: slots.clone(),
435 }),
436 slots: Some(slots),
437 })
438 }
439}
440
441impl CellPlacement {
442 fn resolve(
449 &self,
450 wires: &dyn crate::wires::WireSource,
451 family: &str,
452 cycle: u64,
453 ) -> Result<MetricInstrument, ExecutionError> {
454 let mut coord = nmbrs_metrics::labels::Labels::default();
455 for (dim, wire) in &self.dims {
456 let Some(value) = wires.get(wire) else {
457 return Err(ExecutionError::Op(crate::adapter::AdapterError {
458 error_name: "metric_cell_unresolved".into(),
459 message: format!(
460 "metric '{family}' on cycle {cycle}: coordinate binding \
461 '{wire}' for dimension '{dim}' did not resolve through \
462 ctx.wires — this is a wiring bug between scope \
463 synthesis and the metrics wrapper"
464 ),
465 retryable: false,
466 }));
467 };
468 let polydat::ast::Value::Str(text) = &value else {
472 return Err(ExecutionError::Op(crate::adapter::AdapterError {
473 error_name: "metric_cell_not_a_string".into(),
474 message: format!(
475 "metric '{family}' cell '{dim}' on cycle {cycle}: \
476 coordinate resolved to a non-string {disc:?}. A \
477 dimension's values are label values, which are \
478 strings — convert the expression explicitly.",
479 disc = std::mem::discriminant(&value)
480 ),
481 retryable: false,
482 }));
483 };
484 coord = coord.with(dim.clone(), text.to_string());
485 }
486
487 let key = coord.to_prometheus();
488 {
489 let cache = self.instances.lock().unwrap_or_else(|e| e.into_inner());
490 if let Some(found) = cache.get(&key) {
491 return Ok(found.clone());
492 }
493 }
494
495 let cell = nmbrs_metrics::cells::resolve_under(&self.parent, &coord);
500 let cell_labels = {
501 let g = cell.read().unwrap_or_else(|e| e.into_inner());
502 g.effective_labels().clone()
503 };
504 let instr_labels = cell_labels.with("family", family.to_string());
505 let instrument = match self.kind {
506 nmbrs_workload::model::MetricKind::Gauge => MetricInstrument::Gauge(Arc::new(
507 nmbrs_metrics::instruments::gauge::ValueGauge::new(instr_labels),
508 )),
509 nmbrs_workload::model::MetricKind::Histogram => MetricInstrument::Histogram(Arc::new(
510 nmbrs_metrics::instruments::histogram::Histogram::new(instr_labels),
511 )),
512 nmbrs_workload::model::MetricKind::Counter => MetricInstrument::Counter(Arc::new(
513 nmbrs_metrics::instruments::counter::Counter::new(instr_labels),
514 )),
515 };
516 {
517 let mut g = cell.write().unwrap_or_else(|e| e.into_inner());
518 g.register_instrument_with_unit(
519 family.to_string(),
520 self.unit.clone(),
521 instrument.as_ref(),
522 )
523 .map_err(|e| {
524 ExecutionError::Op(crate::adapter::AdapterError {
525 error_name: "metric_cell_family_collision".into(),
526 message: format!("metric '{family}' cell {key}: {e}"),
527 retryable: false,
528 })
529 })?;
530 }
531 let mut cache = self.instances.lock().unwrap_or_else(|e| e.into_inner());
532 Ok(cache.entry(key).or_insert(instrument).clone())
533 }
534}
535
536#[cfg(test)]
541pub(crate) fn test_gauge_slot(
542 family: &str,
543 binding_name: &str,
544) -> (
545 MetricSlot,
546 Arc<nmbrs_metrics::instruments::gauge::ValueGauge>,
547) {
548 let g = Arc::new(nmbrs_metrics::instruments::gauge::ValueGauge::new(
549 nmbrs_metrics::labels::Labels::default(),
550 ));
551 (
552 MetricSlot {
553 family: family.to_string(),
554 value_expr: binding_name.to_string(),
555 binding_name: binding_name.to_string(),
556 format: None,
557 instrument: Some(MetricInstrument::Gauge(g.clone())),
558 placement: None,
559 },
560 g,
561 )
562}
563
564impl WrappingDispenser for MetricsDispenser {}
565
566impl OpDispenser for MetricsDispenser {
567 fn execute<'a>(
568 &'a self,
569 cycle: u64,
570 ctx: &'a crate::fixture::ExecCtx<'a>,
571 ) -> std::pin::Pin<
572 Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
573 > {
574 Box::pin(async move {
575 let result = self.inner.execute(cycle, ctx).await?;
576 if result.skipped {
579 return Ok(result);
580 }
581 for slot in self.slots.iter() {
582 let Some(value) = ctx.wires.get(&slot.binding_name) else {
592 return Err(ExecutionError::Op(crate::adapter::AdapterError {
593 error_name: "metric_value_unresolved".into(),
594 message: format!(
595 "metric '{family}' on cycle {cycle}: synthesised \
596 binding '{binding}' (from `value: {expr}`) did not \
597 resolve through ctx.wires — this is a wiring bug \
598 between scope synthesis and the metrics wrapper",
599 family = slot.family,
600 binding = slot.binding_name,
601 expr = slot.value_expr,
602 ),
603 retryable: false,
604 }));
605 };
606 if matches!(value, polydat::ast::Value::None) {
617 continue;
618 }
619 let raw = match value_to_f64(&value) {
620 Some(v) => v,
621 None => {
622 return Err(ExecutionError::Op(crate::adapter::AdapterError {
629 error_name: "metric_value_non_numeric".into(),
630 message: format!(
631 "metric '{family}' on cycle {cycle}: \
632 binding '{expr}' is not coercible to f64 \
633 (got value variant {disc:?}); metric \
634 values must be numeric (U64 / F64 / Bool)",
635 family = slot.family,
636 expr = slot.value_expr,
637 disc = std::mem::discriminant(&value),
638 ),
639 retryable: false,
640 }));
641 }
642 };
643 let sanitised = slot.format.as_ref().map(|f| f.apply(raw)).unwrap_or(raw);
644 let instrument = match (&slot.instrument, &slot.placement) {
647 (Some(i), _) => std::borrow::Cow::Borrowed(i),
648 (None, Some(p)) => match p.resolve(ctx.wires, &slot.family, cycle) {
649 Ok(i) => std::borrow::Cow::Owned(i),
650 Err(e) => return Err(e),
651 },
652 (None, None) => unreachable!("a slot has either an instrument or a placement"),
653 };
654 match instrument.as_ref() {
655 MetricInstrument::Gauge(g) => g.set(sanitised),
656 MetricInstrument::Histogram(h) => h.record(sanitised as u64),
657 MetricInstrument::Counter(c) => {
658 if sanitised <= 0.0 {
659 crate::diag!(
660 crate::observer::LogLevel::Warn,
661 "counter '{}' got non-positive value {sanitised}; skipping",
662 slot.family,
663 );
664 } else {
665 c.inc_by(sanitised as u64);
666 }
667 }
668 }
669 }
670 Ok(result)
671 })
672 }
673 fn inner_dispenser(&self) -> Option<&dyn OpDispenser> {
674 Some(self.inner.as_ref())
675 }
676}
677
678#[cfg(test)]
679mod absent_value_tests {
680 #[test]
692 fn absent_binding_skips_the_sample_but_bad_types_still_fail() {
693 let src = std::fs::read_to_string(concat!(
694 env!("CARGO_MANIFEST_DIR"),
695 "/src/wrappers/metrics.rs"
696 ))
697 .expect("read own source");
698 let skip = src
699 .find("if matches!(value, polydat::ast::Value::None) {")
700 .expect("None must be skipped explicitly");
701 let coerce = src
702 .find("let raw = match value_to_f64(&value) {")
703 .expect("the coercion site must still exist");
704 assert!(
705 skip < coerce,
706 "the None skip must come BEFORE the coercion, or an absent value \
707 still reaches the error path"
708 );
709 assert!(
710 src.contains("metric_value_non_numeric"),
711 "non-numeric TYPES must still raise metric_value_non_numeric — \
712 the skip is for absence, not for bad wiring"
713 );
714 }
715}
716
717#[cfg(test)]
718mod tests {
719 use super::*;
720 use crate::adapter::{ExecutionError, OpResult};
721 use crate::fixture::ExecCtx;
722 use nmbrs_workload::model::{MetricKind, MetricSpec};
723
724 struct CapturesInner;
725 impl OpDispenser for CapturesInner {
726 fn execute<'a>(
727 &'a self,
728 _cycle: u64,
729 _ctx: &'a ExecCtx<'a>,
730 ) -> std::pin::Pin<
731 Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
732 > {
733 Box::pin(async move {
734 Ok(OpResult {
735 body: None,
736 skipped: false,
737 })
738 })
739 }
740 }
741
742 fn fresh_component() -> nmbrs_metrics::component::Component {
743 nmbrs_metrics::component::Component::new(
744 nmbrs_metrics::labels::Labels::empty(),
745 HashMap::new(),
746 )
747 }
748
749 fn fresh_component_arc() -> Arc<std::sync::RwLock<nmbrs_metrics::component::Component>> {
752 Arc::new(std::sync::RwLock::new(fresh_component()))
753 }
754
755 fn wrap_on(
758 inner: Arc<dyn OpDispenser>,
759 decl: &HashMap<String, MetricSpec>,
760 comp: &Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
761 fx: &mut crate::fixture::ScopeFixture,
762 ) -> Result<Arc<dyn OpDispenser>, String> {
763 let mut guard = comp.write().unwrap();
764 MetricsDispenser::wrap(inner, decl, &mut guard, comp, fx)
765 }
766
767 fn fresh_fixture() -> crate::fixture::ScopeFixture {
768 use polydat::compile::assembly::{PolydatAssembler, WireRef};
769 use polydat::library::identity::Identity;
770 let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
771 asm.add_node(
772 "cycle_id",
773 Box::new(Identity::new(polydat::ast::PortType::U64)),
774 vec![WireRef::input("cycle")],
775 );
776 asm.add_output("cycle_id", WireRef::node("cycle_id"));
777 let kernel = asm.compile().expect("test fixture asm.compile");
778 crate::fixture::ScopeFixture::new(kernel.program().clone())
779 }
780
781 fn make_spec(value: &str, kind: MetricKind, format: Option<&str>) -> MetricSpec {
782 MetricSpec {
783 cell: Default::default(),
784 value: value.to_string(),
785 family: None,
786 kind: Some(kind),
787 unit: None,
788 format: format.map(|s| s.to_string()),
789 }
790 }
791
792 #[test]
793 fn metrics_dispenser_empty_returns_inner_unchanged() {
794 let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
795 let inner_ptr = Arc::as_ptr(&inner);
796 let comp = fresh_component_arc();
797 let mut fx = fresh_fixture();
798 let wrapped = wrap_on(inner.clone(), &HashMap::new(), &comp, &mut fx).unwrap();
799 assert_eq!(Arc::as_ptr(&wrapped), inner_ptr);
800 }
801
802 impl MetricsDispenser {
808 fn slot_gauge(
809 &self,
810 family: &str,
811 ) -> Option<Arc<nmbrs_metrics::instruments::gauge::ValueGauge>> {
812 self.slots
813 .iter()
814 .find(|s| s.family == family)
815 .and_then(|s| match s.instrument.as_ref()? {
816 MetricInstrument::Gauge(g) => Some(g.clone()),
817 _ => None,
818 })
819 }
820 fn slot_histogram(
821 &self,
822 family: &str,
823 ) -> Option<Arc<nmbrs_metrics::instruments::histogram::Histogram>> {
824 self.slots
825 .iter()
826 .find(|s| s.family == family)
827 .and_then(|s| match s.instrument.as_ref()? {
828 MetricInstrument::Histogram(h) => Some(h.clone()),
829 _ => None,
830 })
831 }
832 fn slot_counter(
833 &self,
834 family: &str,
835 ) -> Option<Arc<nmbrs_metrics::instruments::counter::Counter>> {
836 self.slots
837 .iter()
838 .find(|s| s.family == family)
839 .and_then(|s| match s.instrument.as_ref()? {
840 MetricInstrument::Counter(c) => Some(c.clone()),
841 _ => None,
842 })
843 }
844 }
845
846 fn kernel_with_const_outputs(
847 consts: &[(&str, f64)],
848 ) -> (
849 crate::scope_kernel::ScopeKernel,
850 crate::fixture::ScopeFixture,
851 ) {
852 use polydat::compile::assembly::{PolydatAssembler, WireRef};
853 use polydat::library::fixed::ConstF64;
854 let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
855 for (name, val) in consts {
856 let binding = crate::scope::synthesize_metric_binding_name(name);
857 asm.add_node(&binding, Box::new(ConstF64::new(*val)), vec![]);
858 asm.add_output(&binding, WireRef::node(&binding));
859 }
860 let kernel =
861 crate::scope_kernel::ScopeKernel::from(asm.compile().expect("test kernel asm.compile"));
862 let fx = crate::fixture::ScopeFixture::new(kernel.program().clone());
863 (kernel, fx)
864 }
865
866 fn typed_wrap_with_kernel(
867 inner: Arc<dyn OpDispenser>,
868 decls: &HashMap<String, MetricSpec>,
869 consts: &[(&str, f64)],
870 ) -> Result<
871 (
872 Arc<MetricsDispenser>,
873 crate::fixture::ResolvedPulls,
874 crate::scope_kernel::ScopeKernel,
875 ),
876 String,
877 > {
878 let (mut kernel, mut fx) = kernel_with_const_outputs(consts);
879 let mut comp = fresh_component();
880
881 if decls.is_empty() {
882 return Err("typed_wrap_with_kernel requires non-empty decls".into());
883 }
884 let mut entries: Vec<_> = decls.iter().collect();
885 entries.sort_by(|a, b| a.0.cmp(b.0));
886 let component_labels = comp.effective_labels().clone();
887 let mut slots = Vec::with_capacity(entries.len());
888 for (name, spec) in entries {
889 let family = spec.family.clone().unwrap_or_else(|| name.clone());
890 let format = match &spec.format {
891 Some(s) => Some(
892 nmbrs_workload::metric_format::parse_format_spec(s)
893 .map_err(|e| format!("metric '{name}' format: {e}"))?,
894 ),
895 None => None,
896 };
897 let kind = spec.kind.unwrap_or_default();
898 let instr_labels = component_labels.with("family", family.clone());
899 let instrument = match kind {
900 MetricKind::Gauge => MetricInstrument::Gauge(Arc::new(
901 nmbrs_metrics::instruments::gauge::ValueGauge::new(instr_labels),
902 )),
903 MetricKind::Histogram => MetricInstrument::Histogram(Arc::new(
904 nmbrs_metrics::instruments::histogram::Histogram::new(instr_labels),
905 )),
906 MetricKind::Counter => MetricInstrument::Counter(Arc::new(
907 nmbrs_metrics::instruments::counter::Counter::new(instr_labels),
908 )),
909 };
910 comp.register_instrument_with_unit(
911 family.clone(),
912 spec.unit.clone(),
913 instrument.as_ref(),
914 )?;
915 let binding_name = crate::scope::synthesize_metric_binding_name(name);
916 let _ = fx.register_pull(&binding_name)?;
917 slots.push(MetricSlot {
918 family,
919 value_expr: spec.value.clone(),
920 binding_name,
921 format,
922 instrument: Some(instrument),
923 placement: None,
924 });
925 }
926 let typed = Arc::new(MetricsDispenser {
927 inner,
928 slots: Arc::new(slots),
929 });
930
931 let plan = fx.seal();
932 kernel.set_inputs(&[0]);
933 let pulls = plan.resolve_with(&mut kernel);
934 Ok((typed, pulls, kernel))
935 }
936
937 fn run_dispenser(
938 dispenser: Arc<dyn OpDispenser>,
939 pulls: &crate::fixture::ResolvedPulls,
940 kernel: &mut crate::scope_kernel::ScopeKernel,
941 ) -> Result<OpResult, ExecutionError> {
942 let fields = crate::adapter::ResolvedFields::new(vec![], vec![]);
943 let cw = crate::wires::CycleWires::new(kernel);
944 let ctx = ExecCtx::with_wires(&fields, pulls, &cw);
945 let rt = tokio::runtime::Builder::new_current_thread()
946 .build()
947 .unwrap();
948 rt.block_on(dispenser.execute(0, &ctx))
949 }
950
951 #[test]
952 fn metrics_dispenser_gauge_records_f64() {
953 let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
954 let mut decl = HashMap::new();
955 decl.insert(
956 "my_factor".into(),
957 make_spec("my_factor", MetricKind::Gauge, None),
958 );
959
960 let (typed, pulls, mut kernel) =
961 typed_wrap_with_kernel(inner, &decl, &[("my_factor", 3.5)]).unwrap();
962 let gauge = typed.slot_gauge("my_factor").unwrap();
963 run_dispenser(typed.clone() as Arc<dyn OpDispenser>, &pulls, &mut kernel).unwrap();
964
965 assert!((gauge.get() - 3.5).abs() < 1e-9);
966 }
967
968 #[test]
969 fn metrics_dispenser_histogram_truncates_to_u64() {
970 let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
971 let mut decl = HashMap::new();
972 decl.insert(
973 "latency_ms".into(),
974 make_spec("latency_ms", MetricKind::Histogram, None),
975 );
976
977 let (typed, pulls, mut kernel) =
978 typed_wrap_with_kernel(inner, &decl, &[("latency_ms", 7.9)]).unwrap();
979 let hist = typed.slot_histogram("latency_ms").unwrap();
980 run_dispenser(typed.clone() as Arc<dyn OpDispenser>, &pulls, &mut kernel).unwrap();
981
982 let snap = hist.peek_snapshot();
983 assert_eq!(snap.max(), 7);
984 assert_eq!(snap.len(), 1);
985 }
986
987 #[test]
988 fn metrics_dispenser_counter_positive_inc_and_skip_non_positive() {
989 let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
990 let mut decl = HashMap::new();
991 decl.insert(
992 "ok_inc".into(),
993 make_spec("ok_inc", MetricKind::Counter, None),
994 );
995 decl.insert(
996 "skip_inc".into(),
997 make_spec("skip_inc", MetricKind::Counter, None),
998 );
999
1000 let (typed, pulls, mut kernel) =
1001 typed_wrap_with_kernel(inner, &decl, &[("ok_inc", 5.0), ("skip_inc", 0.0)]).unwrap();
1002 let ok_counter = typed.slot_counter("ok_inc").unwrap();
1003 let skip_counter = typed.slot_counter("skip_inc").unwrap();
1004 run_dispenser(typed.clone() as Arc<dyn OpDispenser>, &pulls, &mut kernel).unwrap();
1005
1006 assert_eq!(ok_counter.get(), 5);
1007 assert_eq!(skip_counter.get(), 0);
1008 }
1009
1010 #[test]
1011 fn metrics_dispenser_format_rounds_value() {
1012 let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
1013 let mut decl = HashMap::new();
1014 decl.insert(
1015 "ratio".into(),
1016 make_spec("ratio", MetricKind::Gauge, Some("#.##")),
1017 );
1018
1019 let (typed, pulls, mut kernel) =
1020 typed_wrap_with_kernel(inner, &decl, &[("ratio", 1.234)]).unwrap();
1021 let gauge = typed.slot_gauge("ratio").unwrap();
1022 run_dispenser(typed.clone() as Arc<dyn OpDispenser>, &pulls, &mut kernel).unwrap();
1023
1024 assert!((gauge.get() - 1.23).abs() < 1e-9);
1025 }
1026
1027 #[test]
1028 fn metrics_dispenser_duplicate_family_errors() {
1029 let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
1030 let comp = fresh_component_arc();
1031 comp.write()
1032 .unwrap()
1033 .register_instrument(
1034 "recall_at_10",
1035 nmbrs_metrics::component::InstrumentRef::Counter(Arc::new(
1036 nmbrs_metrics::instruments::counter::Counter::new(
1037 nmbrs_metrics::labels::Labels::of("name", "recall_at_10"),
1038 ),
1039 )),
1040 )
1041 .unwrap();
1042
1043 let mut decl = HashMap::new();
1044 decl.insert(
1045 "recall_at_10".into(),
1046 make_spec("recall_at_10", MetricKind::Gauge, None),
1047 );
1048
1049 let (_kernel, mut fx) = kernel_with_const_outputs(&[("recall_at_10", 0.0)]);
1050 let err = match wrap_on(inner, &decl, &comp, &mut fx) {
1051 Ok(_) => panic!("expected duplicate-family error, got Ok"),
1052 Err(e) => e,
1053 };
1054 assert!(
1055 err.contains("duplicate family name"),
1056 "unexpected error: {err}"
1057 );
1058 }
1059
1060 #[test]
1061 fn metrics_dispenser_skipped_op_records_nothing() {
1062 struct SkipInner;
1063 impl OpDispenser for SkipInner {
1064 fn execute<'a>(
1065 &'a self,
1066 _cycle: u64,
1067 _ctx: &'a ExecCtx<'a>,
1068 ) -> std::pin::Pin<
1069 Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
1070 > {
1071 Box::pin(async move { Ok(OpResult::skipped()) })
1072 }
1073 }
1074 let mut decl = HashMap::new();
1075 decl.insert("g".into(), make_spec("g", MetricKind::Gauge, None));
1076
1077 let (typed, pulls, mut kernel) =
1078 typed_wrap_with_kernel(Arc::new(SkipInner), &decl, &[("g", 1.0)]).unwrap();
1079 let gauge = typed.slot_gauge("g").unwrap();
1080
1081 let res =
1082 run_dispenser(typed.clone() as Arc<dyn OpDispenser>, &pulls, &mut kernel).unwrap();
1083 assert!(res.skipped);
1084 assert_eq!(gauge.get(), 0.0);
1085 }
1086
1087 #[test]
1088 fn metrics_dispenser_accepts_arbitrary_polydat_expression() {
1089 let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
1090 let mut decl = HashMap::new();
1091 decl.insert(
1092 "computed".into(),
1093 make_spec("factor * 2.0", MetricKind::Gauge, None),
1094 );
1095
1096 let (mut kernel, mut fx) = kernel_with_const_outputs(&[("computed", 6.0)]);
1097 let comp = fresh_component_arc();
1098 let _ = wrap_on(inner, &decl, &comp, &mut fx)
1099 .expect("arbitrary Polydat expression should wrap cleanly");
1100 let plan = fx.seal();
1101 kernel.set_inputs(&[0]);
1102 let _pulls = plan.resolve_with(&mut kernel);
1103 }
1104
1105 #[test]
1106 fn metrics_dispenser_missing_wire_errors_at_init() {
1107 let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
1108 let mut decl = HashMap::new();
1109 decl.insert(
1110 "missing_metric".into(),
1111 make_spec("absent_wire", MetricKind::Gauge, None),
1112 );
1113
1114 let (_kernel, mut fx) = kernel_with_const_outputs(&[("present", 1.0)]);
1115 let comp = fresh_component_arc();
1116 let err = wrap_on(inner, &decl, &comp, &mut fx)
1117 .err()
1118 .expect("missing-wire metric should error at init");
1119 assert!(err.contains("absent_wire"), "msg: {err}");
1120 assert!(err.contains("Available"), "msg: {err}");
1121 }
1122
1123 #[test]
1126 fn value_to_f64_smoke() {
1127 assert_eq!(value_to_f64(&polydat::ast::Value::U64(5)), Some(5.0));
1128 assert_eq!(value_to_f64(&polydat::ast::Value::Bool(true)), Some(1.0));
1129 assert_eq!(value_to_f64(&polydat::ast::Value::Str("x".into())), None);
1130 }
1131}