Skip to main content

nmbrs_runtime/wrappers/
metrics.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Synthetic-metric recorder (SRD-40b §6). After the inner
5//! adapter returns, pulls each declared metric's value through
6//! the per-fiber op-template kernel via `ctx.wires.get` and
7//! records it onto the kind-specialised instrument
8//! (gauge / histogram / counter).
9
10use 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
17/// SRD-32a wrapper name.
18pub const NAME: WrapperName = WrapperName::new("metrics");
19
20/// Trigger: op declares a non-empty `metrics:` map.
21fn 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
38/// `metrics` must sit outside every other non-dryrun wrapper —
39/// it observes their per-cycle effects on `ctx.wires`. Listed
40/// as the `forbids_outer` set on metrics' registration so the
41/// constraint validator hard-errors if anything tries to slip
42/// outside it (except DRYRUN, which is strictly outermost via
43/// its own `forbids_outer` declaration).
44const 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    // `emit` is INTENTIONALLY allowed outer of metrics — the
51    // emit wrapper is the operator-visible render surface and
52    // under `dryrun=emit` it sits outer of DRYRUN (and therefore
53    // outer of metrics) so the rendered op text reaches stdout
54    // before the short-circuit. Metrics fires inner of emit;
55    // the per-cycle measurement is unaffected.
56    super::result::NAME,
57];
58
59inventory::submit! {
60    WrapperRegistration {
61        name: NAME,
62        // `metrics:` is parsed into ParsedOp.metrics, not into
63        // params, so there's no owned `params`-key. Trigger
64        // fires only when the metrics map is non-empty.
65        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
75/// Wraps an inner OpDispenser to publish per-cycle synthetic
76/// metrics declared in the op template's `metrics:` map
77/// (SRD-40b §6).
78///
79/// Per-cycle responsibilities (in order, matching SRD-40b §5.2 →
80/// §6 pipeline):
81///
82/// 1. Await the inner dispenser's `execute`. With a
83///    [`crate::wrappers::ResultDispenser`] in the wrapper stack
84///    between the inner adapter and this one, declared `result:`
85///    wires are already written through `ctx.wires.write` to the
86///    per-fiber kernel by the time we run.
87/// 2. For each declared metric, read the value through
88///    `ctx.wires.get(name)` (bare-binding-name canonical form per
89///    SRD-40b §1). The read pulls fresh through the eval cone
90///    so any computed output (e.g. `row_count := count`) reflects
91///    this cycle's value.
92/// 3. Apply the optional
93///    [`metric_format::FormatSpec`](nmbrs_workload::metric_format::FormatSpec)
94///    sanitiser to round to the configured precision (Phase B).
95/// 4. Dispatch to the kind-specific instrument record method
96///    (SRD-40b §6.1):
97///    - [`MetricKind::Gauge`](nmbrs_workload::model::MetricKind::Gauge) →
98///      [`ValueGauge::set`](nmbrs_metrics::instruments::gauge::ValueGauge::set)
99///      (f64).
100///    - [`MetricKind::Histogram`](nmbrs_workload::model::MetricKind::Histogram) →
101///      [`Histogram::record`](nmbrs_metrics::instruments::histogram::Histogram::record)
102///      (truncated to u64 after format rounding).
103///    - [`MetricKind::Counter`](nmbrs_workload::model::MetricKind::Counter) →
104///      [`Counter::inc_by`](nmbrs_metrics::instruments::counter::Counter::inc_by)
105///      (u64);
106///      non-positive values warn and skip — counters are
107///      monotonic by definition.
108///
109/// Non-bare-name expressions (`factor * 2.0`, `if(...)`, …) are
110/// **deferred** — the wrap step errors when `spec.value` is not
111/// a bare identifier.
112pub struct MetricsDispenser {
113    inner: Arc<dyn OpDispenser>,
114    /// One slot per declared metric. Stable ordering by metric
115    /// name keeps per-cycle dispatch deterministic for tests and
116    /// makes any per-cycle warning sequence reproducible.
117    slots: Arc<Vec<MetricSlot>>,
118}
119
120/// Lenient per-iteration GAUGE publication for poll drains: the
121/// dispenser above only fires when the (potentially hours-long)
122/// drain op completes, so the poll wrapper re-publishes gauge slots
123/// per poll iteration against that iteration's wires — the store
124/// then carries live samples (`compaction_progress_parts` etc.)
125/// instead of a single end-of-drain point. Gauges only: counters
126/// and histograms keep their one-record-per-op semantics (the
127/// end-of-op publish would double-count them). Resolution misses
128/// degrade to a debug log — status must never fail the poll.
129pub(crate) fn publish_gauges_lenient(slots: &[MetricSlot], wires: &dyn crate::wires::WireSource) {
130    for slot in slots {
131        // Cell-placed metrics are skipped: their instrument depends on a
132        // coordinate resolved from the cycle's wires, which this lenient
133        // path has no basis to choose.
134        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
160/// One compiled metric slot: instrument storage + sanitiser +
161/// pre-bound Polydat pull handle.
162pub(crate) struct MetricSlot {
163    /// Family name registered with the [`Component`]. Used in
164    /// diagnostic messages (e.g. the counter non-positive warning).
165    family: String,
166    /// The original `value:` text from the workload, kept for
167    /// diagnostics. Per-cycle resolution reads through the
168    /// internal `binding_name` below; the user's original text
169    /// surfaces in error messages so operators see what they wrote.
170    value_expr: String,
171    /// Internal kernel-output name (`__metric_<name>`) the
172    /// op-template synthesiser created from this metric's
173    /// `value:` expression. Cycle-time reads go through
174    /// `ctx.wires.get(&binding_name)`.
175    binding_name: String,
176    /// Optional value sanitiser. Applied after the value is
177    /// pulled, before the instrument record.
178    format: Option<nmbrs_workload::metric_format::FormatSpec>,
179    /// Resolved instrument storage — exactly one variant is
180    /// populated per slot, matching `MetricSpec.kind`.
181    /// The instrument, for a metric that registers ONCE on the dispenser's
182    /// own component. `None` when the metric is cell-placed: its instruments
183    /// are materialised per coordinate in [`CellPlacement`], because each cell
184    /// is a distinct identity and therefore a distinct instrument.
185    instrument: Option<MetricInstrument>,
186    /// Dimensional placement, when the metric declared `cell:`.
187    placement: Option<CellPlacement>,
188}
189
190/// Per-coordinate instrument materialisation for a cell-placed metric.
191///
192/// The parent is the component this metric would otherwise have registered on,
193/// so a cell REFINES that identity rather than replacing part of it. Nothing
194/// ambient is consulted.
195pub(crate) struct CellPlacement {
196    /// `(dimension, synthesised coordinate wire)`, in the workload's declared
197    /// order. The wire is `__cell_<metric>__<dim>` — see
198    /// `crate::scope::synthesize_cell_binding_name`.
199    dims: Vec<(String, String)>,
200    /// The registration site whose identity each cell refines.
201    parent: Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
202    kind: nmbrs_workload::model::MetricKind,
203    unit: Option<String>,
204    /// Instruments already materialised, keyed by the coordinate's canonical
205    /// rendering. Steady state is a hash lookup: the registry write and the
206    /// component attach happen once per distinct coordinate, never per cycle.
207    instances: std::sync::Mutex<std::collections::HashMap<String, MetricInstrument>>,
208}
209
210/// Kind-specialised instrument storage owned by a [`MetricSlot`].
211///
212/// The same `Arc<...>` is shared with the dispenser's `Component`
213/// instrument registry — registered via
214/// `Component::register_instrument` at [`MetricsDispenser::wrap`] time.
215/// Per-cycle code records through the slot's typed `Arc`; the cadence
216/// reporter snapshots through the registry. One source of truth, two
217/// access paths.
218#[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    /// Promote the kind-erased slot value into the canonical
227    /// [`InstrumentRef`] for registry storage.
228    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
241/// Numeric coercion for capture-map lookups. Returns `None`
242/// for non-numeric variants (string, vector, none) so the
243/// MetricsDispenser slot path logs + skips rather than panicking
244/// through `Value::as_f64`'s strict matcher.
245fn 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
254/// What [`MetricsDispenser::wrap_with_slots`] returns: the wrapped
255/// dispenser and its compiled slot list, which the poll wrapper uses to
256/// re-publish gauge slots per iteration. `slots` is `None` when the op
257/// declares no metrics and the dispenser is the unwrapped inner one.
258pub(crate) struct MetricsWrap {
259    pub(crate) dispenser: Arc<dyn OpDispenser>,
260    pub(crate) slots: Option<Arc<Vec<MetricSlot>>>,
261}
262
263impl MetricsDispenser {
264    /// Wrap an inner dispenser with synthetic-metric publication
265    /// for the op template's `metrics:` declarations.
266    ///
267    /// Init steps (SRD-40b §6 init):
268    /// 1. Empty declaration → return `inner` unchanged. No
269    ///    overhead for ops that don't publish synthetic metrics.
270    /// 2. For each `(name, spec)`, allocate the kind-specific
271    ///    instrument and register it on the component via
272    ///    `Component::register_instrument`. A duplicate-family
273    ///    collision (§7.2) errors here, before any cycle runs.
274    /// 3. Pre-parse the optional `format:` string into a
275    ///    [`FormatSpec`](nmbrs_workload::metric_format::FormatSpec).
276    ///
277    /// `component` is borrowed mutably so `register_instrument`
278    /// can claim the family slot atomically with the instrument
279    /// allocation. The same `Arc<...>` is held both on the
280    /// component (for cadence-reporter capture) and in the
281    /// returned dispenser's slots (for per-cycle record).
282    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    /// As [`Self::wrap`], additionally returning the compiled slot
293    /// list (shared `Arc`) so the poll wrapper can re-publish the
294    /// GAUGE slots per poll iteration (see
295    /// [`publish_gauges_lenient`]). `None` when the op declares no
296    /// metrics.
297    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        // The same component, as the handle cells attach under. A cell refines
302        // THIS identity, so the parent comes from the registration site rather
303        // than from anything ambient.
304        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        // Stable ordering on metric names so init-time
314        // diagnostics + per-cycle dispatch are reproducible.
315        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            // Instrument labels carry the family name as a label
333            // alongside the component's effective labels. The
334            // `family` argument to `register_instrument` is the
335            // canonical family-name string; the labels are the
336            // dimensional cell.
337            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            // Resolve the metric's value expression against the
353            // Polydat Kernel up front. The op-template synthesiser
354            // appended each metric's `value:` expression as a
355            // `__metric_<name> := <expr>` binding on the kernel
356            // (see `crate::scope::synthesize_metric_binding_name`),
357            // so cycle-time reads go through that internal output —
358            // arbitrary Polydat expressions work, not just bare names.
359            // The closure-binding-economy walker injected magic
360            // externs (body/count/ok) for any of those names this
361            // expression referenced, so a workload that writes
362            // `value: count` no longer needs a fake result-binding
363            // to wedge the slot open.
364            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            // SRD-40b §7.2 — collide-on-duplicate at init. The
375            // single registry on `Component` is the canonical
376            // store; the slot's `Arc<...>` shares the same
377            // instrument for the per-cycle hot path. The
378            // optional `unit` rides through to drive the
379            // `_<unit>` suffix on `metric_family.name` and the
380            // `unit` column at capture time (SRD-40a §4.3).
381            // Cell-placed metrics register PER CELL, at first sight of each
382            // coordinate — not here. Registering on the dispenser's own
383            // component as well would claim the family for the un-refined
384            // identity, and the first cell to materialise would then collide
385            // with it on this same duplicate-family check.
386            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    /// The instrument for this cycle's coordinate, materialising the cell and
443    /// registering the family on first sight of each distinct coordinate.
444    ///
445    /// Steady state is a hash lookup. The component attach and the registry
446    /// write happen once per coordinate, never per cycle — which is what keeps
447    /// a per-row metric off the component write lock.
448    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            // A label value is a string. Anything else would key cells on
469            // formatting rather than on identity, so it is refused here rather
470            // than stringified behind the author's back.
471            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        // First sight of this coordinate: materialise the cell, build the
496        // instrument carrying the cell's FULL effective labels, and register
497        // the family there. The duplicate-family check runs per cell, which is
498        // exactly where it belongs.
499        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/// A gauge slot wired straight to a wire name — the metric path a poll
537/// publishes through, without the workload/kernel machinery around it.
538/// Lets other modules' tests assert on what actually reaches the
539/// instrument, rather than on a display-side proxy.
540#[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            // Skipped ops produce no measurement — SRD-40b §5.2 /
577            // §6 pipeline only fires on a successfully-executed op.
578            if result.skipped {
579                return Ok(result);
580            }
581            for slot in self.slots.iter() {
582                // Sole resolution path: ctx.wires reads through the
583                // live per-fiber kernel handle (project rule
584                // "GK Is Canonical Scope"). The op-template synthesiser
585                // compiled this metric's `value:` expression into the
586                // kernel as `__metric_<name> := <expr>`; pulling that
587                // wire fires the expression's eval cone — including
588                // magic-extern reads (body/count/ok) ResultDispenser
589                // wrote earlier in the same cycle. ctx.wires.get is
590                // the live read; no pre-stack snapshot.
591                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                // `None` is the absence of a measurement, not a bad one. A
607                // conditional aggregate that matched nothing this cycle
608                // (`:sum(x where kind='y')` with no matching rows) resolves to
609                // None by design — "absent, not zero". Publishing no sample is
610                // the honest response; erroring turns every conditional
611                // aggregate into a run-ending fault the first cycle its subject
612                // is idle, which is exactly when a drain is being watched.
613                //
614                // Genuinely non-numeric TYPES (Str, vector, handle) still fail
615                // loudly below — those are wiring mistakes, not absences.
616                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                        // The wire resolved but its type can't
623                        // coerce to a numeric metric value (Str,
624                        // vector, handle, etc.). Surface as a
625                        // hard ExecutionError so the activity's
626                        // `errors:` policy decides — by default
627                        // (errors=stop) the phase + run halt.
628                        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                // A cell-placed metric resolves its coordinate from this
645                // cycle's wires and lands on the instrument for THAT cell.
646                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    /// A gauge whose binding resolved to `None` must publish NO SAMPLE, not
681    /// fail the run. `None` is the absence of a measurement: a conditional
682    /// aggregate like `:sum(progress where kind='secondary index build')`
683    /// yields it by design whenever no row has that kind, which is precisely
684    /// when a drain is idle and being watched. Erroring there killed a
685    /// 58-minute run at tier 19 with
686    /// `metric_value_non_numeric ... variant Discriminant(19)`.
687    ///
688    /// Genuinely non-numeric TYPES must still fail loudly — those are wiring
689    /// mistakes, not absences — so the skip is matched on `Value::None`
690    /// specifically, never on "failed to coerce".
691    #[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    /// A component as the production path holds it: an `Arc` (cells attach
750    /// under it) plus the `&mut` borrow registration needs.
751    fn fresh_component_arc() -> Arc<std::sync::RwLock<nmbrs_metrics::component::Component>> {
752        Arc::new(std::sync::RwLock::new(fresh_component()))
753    }
754
755    /// `MetricsDispenser::wrap` with the component handled the way the
756    /// activity does it.
757    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    /// Test-only introspection: peek at allocated instrument
803    /// `Arc`s by family name. Tests need this because `wrap`
804    /// returns `Arc<dyn OpDispenser>` and we want to assert
805    /// against the same `ValueGauge` / `Histogram` / `Counter`
806    /// the wrapper writes through.
807    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    /// Silence dead-code warning for value_to_f64 (used inside
1124    /// wrapper but private to this module otherwise).
1125    #[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}