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, or places its own
21/// measurements in a cell (`cell:`), whose service time this wrapper
22/// records.
23fn triggers(s: WrapperSubject) -> bool {
24    let Some(template) = s.op() else {
25        return false;
26    };
27    !template.metrics.is_empty() || !template.cell.is_empty()
28}
29
30fn describe_assignment(s: WrapperSubject) -> Option<String> {
31    let template = s.op()?;
32    let mut parts = Vec::new();
33    if !template.metrics.is_empty() {
34        let mut names: Vec<&str> = template.metrics.keys().map(|s| s.as_str()).collect();
35        names.sort();
36        parts.push(format!("emits {}", names.join(", ")));
37    }
38    if !template.cell.is_empty() {
39        let dims: Vec<&str> = template.cell.keys().map(|s| s.as_str()).collect();
40        parts.push(format!("places service time by {}", dims.join(", ")));
41    }
42    if parts.is_empty() {
43        return None;
44    }
45    Some(format!("metrics: {}", parts.join("; ")))
46}
47
48/// `metrics` must sit outside every other non-dryrun wrapper —
49/// it observes their per-cycle effects on `ctx.wires`. Listed
50/// as the `forbids_outer` set on metrics' registration so the
51/// constraint validator hard-errors if anything tries to slip
52/// outside it (except DRYRUN, which is strictly outermost via
53/// its own `forbids_outer` declaration).
54const FORBIDS_OUTER: &[WrapperName] = &[
55    super::traverse::NAME,
56    super::delay::NAME,
57    crate::validation::WRAPPER_NAME,
58    super::poll::NAME,
59    super::r#if::NAME,
60    // `emit` is INTENTIONALLY allowed outer of metrics — the
61    // emit wrapper is the operator-visible render surface and
62    // under `dryrun=emit` it sits outer of DRYRUN (and therefore
63    // outer of metrics) so the rendered op text reaches stdout
64    // before the short-circuit. Metrics fires inner of emit;
65    // the per-cycle measurement is unaffected.
66    super::result::NAME,
67];
68
69inventory::submit! {
70    WrapperRegistration {
71        name: NAME,
72        // `metrics:` is parsed into ParsedOp.metrics, not into
73        // params, so there's no owned `params`-key. Trigger
74        // fires only when the metrics map is non-empty.
75        owned_fields: &[],
76        triggers,
77        requires_inner: &[],
78        forbids_outer: FORBIDS_OUTER,
79        mutually_exclusive_with: &[],
80        describe_assignment,
81        levels: &[crate::wrapper_registry::WrapperLevel::Op],
82    }
83}
84
85/// Wraps an inner OpDispenser to publish per-cycle synthetic
86/// metrics declared in the op template's `metrics:` map
87/// (SRD-40b §6).
88///
89/// Per-cycle responsibilities (in order, matching SRD-40b §5.2 →
90/// §6 pipeline):
91///
92/// 1. Await the inner dispenser's `execute`. With a
93///    [`crate::wrappers::ResultDispenser`] in the wrapper stack
94///    between the inner adapter and this one, declared `result:`
95///    wires are already written through `ctx.wires.write` to the
96///    per-fiber kernel by the time we run.
97/// 2. For each declared metric, read the value through
98///    `ctx.wires.get(name)` (bare-binding-name canonical form per
99///    SRD-40b §1). The read pulls fresh through the eval cone
100///    so any computed output (e.g. `row_count := count`) reflects
101///    this cycle's value.
102/// 3. Apply the optional
103///    [`metric_format::FormatSpec`](nmbrs_workload::metric_format::FormatSpec)
104///    sanitiser to round to the configured precision (Phase B).
105/// 4. Dispatch to the kind-specific instrument record method
106///    (SRD-40b §6.1):
107///    - [`MetricKind::Gauge`](nmbrs_workload::model::MetricKind::Gauge) →
108///      [`ValueGauge::set`](nmbrs_metrics::instruments::gauge::ValueGauge::set)
109///      (f64).
110///    - [`MetricKind::Histogram`](nmbrs_workload::model::MetricKind::Histogram) →
111///      [`Histogram::record`](nmbrs_metrics::instruments::histogram::Histogram::record)
112///      (truncated to u64 after format rounding).
113///    - [`MetricKind::Counter`](nmbrs_workload::model::MetricKind::Counter) →
114///      [`Counter::inc_by`](nmbrs_metrics::instruments::counter::Counter::inc_by)
115///      (u64);
116///      non-positive values warn and skip — counters are
117///      monotonic by definition.
118///
119/// Non-bare-name expressions (`factor * 2.0`, `if(...)`, …) are
120/// **deferred** — the wrap step errors when `spec.value` is not
121/// a bare identifier.
122pub struct MetricsDispenser {
123    inner: Arc<dyn OpDispenser>,
124    /// One slot per declared metric. Stable ordering by metric
125    /// name keeps per-cycle dispatch deterministic for tests and
126    /// makes any per-cycle warning sequence reproducible.
127    slots: Arc<Vec<MetricSlot>>,
128    /// The op's own cells, when it declares `cell:`. Each executed
129    /// cycle's service time is recorded in the cycle's cell.
130    op_cells: Option<Arc<crate::op_cells::OpCells>>,
131}
132
133/// Lenient per-iteration GAUGE publication for poll drains: the
134/// dispenser above only fires when the (potentially hours-long)
135/// drain op completes, so the poll wrapper re-publishes gauge slots
136/// per poll iteration against that iteration's wires — the store
137/// then carries live samples (`compaction_progress_parts` etc.)
138/// instead of a single end-of-drain point. Gauges only: counters
139/// and histograms keep their one-record-per-op semantics (the
140/// end-of-op publish would double-count them). Resolution misses
141/// degrade to a debug log — status must never fail the poll.
142pub(crate) fn publish_gauges_lenient(slots: &[MetricSlot], wires: &dyn crate::wires::WireSource) {
143    for slot in slots {
144        // Cell-placed metrics are skipped: their instrument depends on a
145        // coordinate resolved from the cycle's wires, which this lenient
146        // path has no basis to choose.
147        let Some(MetricInstrument::Gauge(g)) = &slot.instrument else {
148            continue;
149        };
150        let Some(value) = wires.get(&slot.binding_name) else {
151            crate::diag!(
152                crate::observer::LogLevel::Debug,
153                "poll gauge '{}': binding '{}' unresolved this iteration",
154                slot.family,
155                slot.binding_name
156            );
157            continue;
158        };
159        let Some(raw) = value_to_f64(&value) else {
160            crate::diag!(
161                crate::observer::LogLevel::Debug,
162                "poll gauge '{}': '{}' non-numeric this iteration",
163                slot.family,
164                slot.value_expr
165            );
166            continue;
167        };
168        let sanitised = slot.format.as_ref().map(|f| f.apply(raw)).unwrap_or(raw);
169        g.set(sanitised);
170    }
171}
172
173/// One compiled metric slot: instrument storage + sanitiser +
174/// pre-bound Polydat pull handle.
175pub(crate) struct MetricSlot {
176    /// Family name registered with the [`Component`]. Used in
177    /// diagnostic messages (e.g. the counter non-positive warning).
178    family: String,
179    /// The original `value:` text from the workload, kept for
180    /// diagnostics. Per-cycle resolution reads through the
181    /// internal `binding_name` below; the user's original text
182    /// surfaces in error messages so operators see what they wrote.
183    value_expr: String,
184    /// Internal kernel-output name (`__metric_<name>`) the
185    /// op-template synthesiser created from this metric's
186    /// `value:` expression. Cycle-time reads go through
187    /// `ctx.wires.get(&binding_name)`.
188    binding_name: String,
189    /// Optional value sanitiser. Applied after the value is
190    /// pulled, before the instrument record.
191    format: Option<nmbrs_workload::metric_format::FormatSpec>,
192    /// Resolved instrument storage — exactly one variant is
193    /// populated per slot, matching `MetricSpec.kind`.
194    /// The instrument, for a metric that registers ONCE on the dispenser's
195    /// own component. `None` when the metric is cell-placed: its instruments
196    /// are materialised per coordinate in [`CellPlacement`], because each cell
197    /// is a distinct identity and therefore a distinct instrument.
198    instrument: Option<MetricInstrument>,
199    /// Dimensional placement, when the metric declared `cell:`.
200    placement: Option<CellPlacement>,
201}
202
203/// Per-coordinate instrument materialisation for a cell-placed metric.
204///
205/// The parent is the component this metric would otherwise have registered on,
206/// so a cell REFINES that identity rather than replacing part of it. Nothing
207/// ambient is consulted.
208pub(crate) struct CellPlacement {
209    /// `(dimension, synthesised coordinate wire)`, in the workload's declared
210    /// order. The wire is `__cell_<metric>__<dim>` — see
211    /// `crate::scope::synthesize_cell_binding_name`.
212    dims: Vec<(String, String)>,
213    /// The registration site whose identity each cell refines.
214    parent: Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
215    kind: nmbrs_workload::model::MetricKind,
216    unit: Option<String>,
217    /// Instruments already materialised, keyed by the coordinate's canonical
218    /// rendering. Steady state is a hash lookup: the registry write and the
219    /// component attach happen once per distinct coordinate, never per cycle.
220    instances: std::sync::Mutex<std::collections::HashMap<String, MetricInstrument>>,
221}
222
223/// Kind-specialised instrument storage owned by a [`MetricSlot`].
224///
225/// The same `Arc<...>` is shared with the dispenser's `Component`
226/// instrument registry — registered via
227/// `Component::register_instrument` at [`MetricsDispenser::wrap`] time.
228/// Per-cycle code records through the slot's typed `Arc`; the cadence
229/// reporter snapshots through the registry. One source of truth, two
230/// access paths.
231#[derive(Clone)]
232enum MetricInstrument {
233    Gauge(Arc<nmbrs_metrics::instruments::gauge::ValueGauge>),
234    Histogram(Arc<nmbrs_metrics::instruments::histogram::Histogram>),
235    Counter(Arc<nmbrs_metrics::instruments::counter::Counter>),
236}
237
238impl MetricInstrument {
239    /// Promote the kind-erased slot value into the canonical
240    /// [`InstrumentRef`] for registry storage.
241    fn as_ref(&self) -> nmbrs_metrics::component::InstrumentRef {
242        match self {
243            MetricInstrument::Gauge(g) => nmbrs_metrics::component::InstrumentRef::Gauge(g.clone()),
244            MetricInstrument::Histogram(h) => {
245                nmbrs_metrics::component::InstrumentRef::Histogram(h.clone())
246            }
247            MetricInstrument::Counter(c) => {
248                nmbrs_metrics::component::InstrumentRef::Counter(c.clone())
249            }
250        }
251    }
252}
253
254/// Numeric coercion for capture-map lookups. Returns `None`
255/// for non-numeric variants (string, vector, none) so the
256/// MetricsDispenser slot path logs + skips rather than panicking
257/// through `Value::as_f64`'s strict matcher.
258fn value_to_f64(v: &polydat::ast::Value) -> Option<f64> {
259    match v {
260        polydat::ast::Value::F64(f) => Some(*f),
261        polydat::ast::Value::U64(u) => Some(*u as f64),
262        polydat::ast::Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
263        _ => None,
264    }
265}
266
267/// What [`MetricsDispenser::wrap_with_slots`] returns: the wrapped
268/// dispenser and its compiled slot list, which the poll wrapper uses to
269/// re-publish gauge slots per iteration. `slots` is `None` when the op
270/// declares no metrics and the dispenser is the unwrapped inner one.
271pub(crate) struct MetricsWrap {
272    pub(crate) dispenser: Arc<dyn OpDispenser>,
273    pub(crate) slots: Option<Arc<Vec<MetricSlot>>>,
274}
275
276impl MetricsDispenser {
277    /// Wrap an inner dispenser with synthetic-metric publication
278    /// for the op template's `metrics:` declarations.
279    ///
280    /// Init steps (SRD-40b §6 init):
281    /// 1. Empty declaration → return `inner` unchanged. No
282    ///    overhead for ops that don't publish synthetic metrics.
283    /// 2. For each `(name, spec)`, allocate the kind-specific
284    ///    instrument and register it on the component via
285    ///    `Component::register_instrument`. A duplicate-family
286    ///    collision (§7.2) errors here, before any cycle runs.
287    /// 3. Pre-parse the optional `format:` string into a
288    ///    [`FormatSpec`](nmbrs_workload::metric_format::FormatSpec).
289    ///
290    /// `component` is borrowed mutably so `register_instrument`
291    /// can claim the family slot atomically with the instrument
292    /// allocation. The same `Arc<...>` is held both on the
293    /// component (for cadence-reporter capture) and in the
294    /// returned dispenser's slots (for per-cycle record).
295    pub fn wrap(
296        inner: Arc<dyn OpDispenser>,
297        metrics: &HashMap<String, nmbrs_workload::model::MetricSpec>,
298        component: &mut nmbrs_metrics::component::Component,
299        component_arc: &Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
300        fx: &mut crate::fixture::ScopeFixture,
301    ) -> Result<Arc<dyn OpDispenser>, String> {
302        Self::wrap_with_slots(inner, metrics, component, component_arc, None, fx)
303            .map(|w| w.dispenser)
304    }
305
306    /// As [`Self::wrap`], additionally returning the compiled slot
307    /// list (shared `Arc`) so the poll wrapper can re-publish the
308    /// GAUGE slots per poll iteration (see
309    /// [`publish_gauges_lenient`]). `None` when the op declares no
310    /// metrics.
311    pub(crate) fn wrap_with_slots(
312        inner: Arc<dyn OpDispenser>,
313        metrics: &HashMap<String, nmbrs_workload::model::MetricSpec>,
314        component: &mut nmbrs_metrics::component::Component,
315        // The same component, as the handle cells attach under. A cell refines
316        // THIS identity, so the parent comes from the registration site rather
317        // than from anything ambient.
318        component_arc: &Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
319        // The op's own cells, when it declares `cell:`: this wrapper
320        // records each cycle's service time there.
321        op_cells: Option<Arc<crate::op_cells::OpCells>>,
322        fx: &mut crate::fixture::ScopeFixture,
323    ) -> Result<MetricsWrap, String> {
324        if metrics.is_empty() && op_cells.is_none() {
325            return Ok(MetricsWrap {
326                dispenser: inner,
327                slots: None,
328            });
329        }
330        // Stable ordering on metric names so init-time
331        // diagnostics + per-cycle dispatch are reproducible.
332        let mut entries: Vec<_> = metrics.iter().collect();
333        entries.sort_by(|a, b| a.0.cmp(b.0));
334
335        let component_labels = component.effective_labels().clone();
336        let mut slots = Vec::with_capacity(entries.len());
337        for (name, spec) in entries {
338            let family = spec.family.clone().unwrap_or_else(|| name.clone());
339
340            let format = match &spec.format {
341                Some(s) => Some(
342                    nmbrs_workload::metric_format::parse_format_spec(s)
343                        .map_err(|e| format!("metric '{name}' format: {e}"))?,
344                ),
345                None => None,
346            };
347
348            let kind = spec.kind.unwrap_or_default();
349            // Instrument labels carry the family name as a label
350            // alongside the component's effective labels. The
351            // `family` argument to `register_instrument` is the
352            // canonical family-name string; the labels are the
353            // dimensional cell.
354            let instr_labels = component_labels.with("family", family.clone());
355            let instrument = match kind {
356                nmbrs_workload::model::MetricKind::Gauge => MetricInstrument::Gauge(Arc::new(
357                    nmbrs_metrics::instruments::gauge::ValueGauge::new(instr_labels),
358                )),
359                nmbrs_workload::model::MetricKind::Histogram => {
360                    MetricInstrument::Histogram(Arc::new(
361                        nmbrs_metrics::instruments::histogram::Histogram::new(instr_labels),
362                    ))
363                }
364                nmbrs_workload::model::MetricKind::Counter => MetricInstrument::Counter(Arc::new(
365                    nmbrs_metrics::instruments::counter::Counter::new(instr_labels),
366                )),
367            };
368
369            // Resolve the metric's value expression against the
370            // Polydat Kernel up front. The op-template synthesiser
371            // appended each metric's `value:` expression as a
372            // `__metric_<name> := <expr>` binding on the kernel
373            // (see `crate::scope::synthesize_metric_binding_name`),
374            // so cycle-time reads go through that internal output —
375            // arbitrary Polydat expressions work, not just bare names.
376            // The closure-binding-economy walker injected magic
377            // externs (body/count/ok) for any of those names this
378            // expression referenced, so a workload that writes
379            // `value: count` no longer needs a fake result-binding
380            // to wedge the slot open.
381            let binding_name = crate::scope::synthesize_metric_binding_name(name);
382            let _ = fx.register_pull(&binding_name).map_err(|e| {
383                format!(
384                    "metric '{name}' value '{value}': {e} (synthesised binding \
385                     '{binding_name}' should have been registered by the \
386                     op-template kernel synthesiser — this is a bug)",
387                    value = spec.value,
388                )
389            })?;
390
391            // SRD-40b §7.2 — collide-on-duplicate at init. The
392            // single registry on `Component` is the canonical
393            // store; the slot's `Arc<...>` shares the same
394            // instrument for the per-cycle hot path. The
395            // optional `unit` rides through to drive the
396            // `_<unit>` suffix on `metric_family.name` and the
397            // `unit` column at capture time (SRD-40a §4.3).
398            // Cell-placed metrics register PER CELL, at first sight of each
399            // coordinate — not here. Registering on the dispenser's own
400            // component as well would claim the family for the un-refined
401            // identity, and the first cell to materialise would then collide
402            // with it on this same duplicate-family check.
403            let placement = if spec.cell.is_empty() {
404                component.register_instrument_with_unit(
405                    family.clone(),
406                    spec.unit.clone(),
407                    instrument.as_ref(),
408                )?;
409                None
410            } else {
411                let mut dims = Vec::with_capacity(spec.cell.len());
412                for dim in spec.cell.keys() {
413                    let wire = crate::scope::synthesize_cell_binding_name(name, dim);
414                    let _ = fx.register_pull(&wire).map_err(|e| {
415                        format!(
416                            "metric '{name}' cell '{dim}': {e} (synthesised \
417                             coordinate binding '{wire}' should have been \
418                             registered by the op-template kernel synthesiser \
419                             — this is a bug)"
420                        )
421                    })?;
422                    dims.push((dim.clone(), wire));
423                }
424                Some(CellPlacement {
425                    dims,
426                    parent: component_arc.clone(),
427                    kind,
428                    unit: spec.unit.clone(),
429                    instances: std::sync::Mutex::new(std::collections::HashMap::new()),
430                })
431            };
432
433            slots.push(MetricSlot {
434                family,
435                value_expr: spec.value.clone(),
436                binding_name,
437                format,
438                instrument: if placement.is_some() {
439                    None
440                } else {
441                    Some(instrument)
442                },
443                placement,
444            });
445        }
446
447        let slots = Arc::new(slots);
448        Ok(MetricsWrap {
449            dispenser: Arc::new(Self {
450                inner,
451                slots: slots.clone(),
452                op_cells,
453            }),
454            slots: Some(slots),
455        })
456    }
457}
458
459impl CellPlacement {
460    /// The instrument for this cycle's coordinate, materialising the cell and
461    /// registering the family on first sight of each distinct coordinate.
462    ///
463    /// Steady state is a hash lookup. The component attach and the registry
464    /// write happen once per coordinate, never per cycle — which is what keeps
465    /// a per-row metric off the component write lock.
466    fn resolve(
467        &self,
468        wires: &dyn crate::wires::WireSource,
469        family: &str,
470        cycle: u64,
471    ) -> Result<MetricInstrument, ExecutionError> {
472        let coord = crate::op_cells::read_coordinate(
473            &self.dims,
474            wires,
475            "metric",
476            &format!("metric '{family}'"),
477            cycle,
478        )?;
479
480        let key = coord.to_prometheus();
481        {
482            let cache = self.instances.lock().unwrap_or_else(|e| e.into_inner());
483            if let Some(found) = cache.get(&key) {
484                return Ok(found.clone());
485            }
486        }
487
488        // First sight of this coordinate: materialise the cell, build the
489        // instrument carrying the cell's FULL effective labels, and register
490        // the family there. The duplicate-family check runs per cell, which is
491        // exactly where it belongs.
492        let cell = nmbrs_metrics::cells::resolve_under(&self.parent, &coord);
493        let cell_labels = {
494            let g = cell.read().unwrap_or_else(|e| e.into_inner());
495            g.effective_labels().clone()
496        };
497        let instr_labels = cell_labels.with("family", family.to_string());
498        let instrument = match self.kind {
499            nmbrs_workload::model::MetricKind::Gauge => MetricInstrument::Gauge(Arc::new(
500                nmbrs_metrics::instruments::gauge::ValueGauge::new(instr_labels),
501            )),
502            nmbrs_workload::model::MetricKind::Histogram => MetricInstrument::Histogram(Arc::new(
503                nmbrs_metrics::instruments::histogram::Histogram::new(instr_labels),
504            )),
505            nmbrs_workload::model::MetricKind::Counter => MetricInstrument::Counter(Arc::new(
506                nmbrs_metrics::instruments::counter::Counter::new(instr_labels),
507            )),
508        };
509        {
510            let mut g = cell.write().unwrap_or_else(|e| e.into_inner());
511            g.register_instrument_with_unit(
512                family.to_string(),
513                self.unit.clone(),
514                instrument.as_ref(),
515            )
516            .map_err(|e| {
517                ExecutionError::Op(crate::adapter::AdapterError {
518                    error_name: "metric_cell_family_collision".into(),
519                    message: format!("metric '{family}' cell {key}: {e}"),
520                    retryable: false,
521                })
522            })?;
523        }
524        let mut cache = self.instances.lock().unwrap_or_else(|e| e.into_inner());
525        Ok(cache.entry(key).or_insert(instrument).clone())
526    }
527}
528
529/// A gauge slot wired straight to a wire name — the metric path a poll
530/// publishes through, without the workload/kernel machinery around it.
531/// Lets other modules' tests assert on what actually reaches the
532/// instrument, rather than on a display-side proxy.
533#[cfg(test)]
534pub(crate) fn test_gauge_slot(
535    family: &str,
536    binding_name: &str,
537) -> (
538    MetricSlot,
539    Arc<nmbrs_metrics::instruments::gauge::ValueGauge>,
540) {
541    let g = Arc::new(nmbrs_metrics::instruments::gauge::ValueGauge::new(
542        nmbrs_metrics::labels::Labels::default(),
543    ));
544    (
545        MetricSlot {
546            family: family.to_string(),
547            value_expr: binding_name.to_string(),
548            binding_name: binding_name.to_string(),
549            format: None,
550            instrument: Some(MetricInstrument::Gauge(g.clone())),
551            placement: None,
552        },
553        g,
554    )
555}
556
557impl WrappingDispenser for MetricsDispenser {}
558
559impl OpDispenser for MetricsDispenser {
560    fn execute<'a>(
561        &'a self,
562        cycle: u64,
563        ctx: &'a crate::fixture::ExecCtx<'a>,
564    ) -> std::pin::Pin<
565        Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
566    > {
567        Box::pin(async move {
568            let started = self.op_cells.as_ref().map(|_| std::time::Instant::now());
569            let outcome = self.inner.execute(cycle, ctx).await;
570            // Service time lands in the op's cell for every executed
571            // cycle, failed ones included, as the activity's own
572            // service time does. A failed cycle whose coordinate cannot
573            // be read keeps its own error.
574            if let (Some(cells), Some(started)) = (&self.op_cells, started) {
575                let nanos = started.elapsed().as_nanos() as u64;
576                match &outcome {
577                    Ok(result) if result.skipped => {}
578                    Ok(_) => cells.resolve(ctx.wires, cycle)?.record_service_time(nanos),
579                    Err(_) => {
580                        if let Ok(cell) = cells.resolve(ctx.wires, cycle) {
581                            cell.record_service_time(nanos);
582                        }
583                    }
584                }
585            }
586            let result = outcome?;
587            // Skipped ops produce no measurement — SRD-40b §5.2 /
588            // §6 pipeline only fires on a successfully-executed op.
589            if result.skipped {
590                return Ok(result);
591            }
592            for slot in self.slots.iter() {
593                // Sole resolution path: ctx.wires reads through the
594                // live per-fiber kernel handle (project rule
595                // "GK Is Canonical Scope"). The op-template synthesiser
596                // compiled this metric's `value:` expression into the
597                // kernel as `__metric_<name> := <expr>`; pulling that
598                // wire fires the expression's eval cone — including
599                // magic-extern reads (body/count/ok) ResultDispenser
600                // wrote earlier in the same cycle. ctx.wires.get is
601                // the live read; no pre-stack snapshot.
602                let Some(value) = ctx.wires.get(&slot.binding_name) else {
603                    return Err(ExecutionError::Op(crate::adapter::AdapterError {
604                        error_name: "metric_value_unresolved".into(),
605                        message: format!(
606                            "metric '{family}' on cycle {cycle}: synthesised \
607                             binding '{binding}' (from `value: {expr}`) did not \
608                             resolve through ctx.wires — this is a wiring bug \
609                             between scope synthesis and the metrics wrapper",
610                            family = slot.family,
611                            binding = slot.binding_name,
612                            expr = slot.value_expr,
613                        ),
614                        retryable: false,
615                    }));
616                };
617                // `None` is the absence of a measurement, not a bad one. A
618                // conditional aggregate that matched nothing this cycle
619                // (`:sum(x where kind='y')` with no matching rows) resolves to
620                // None by design — "absent, not zero". Publishing no sample is
621                // the honest response; erroring turns every conditional
622                // aggregate into a run-ending fault the first cycle its subject
623                // is idle, which is exactly when a drain is being watched.
624                //
625                // Genuinely non-numeric TYPES (Str, vector, handle) still fail
626                // loudly below — those are wiring mistakes, not absences.
627                if matches!(value, polydat::ast::Value::None) {
628                    continue;
629                }
630                let raw = match value_to_f64(&value) {
631                    Some(v) => v,
632                    None => {
633                        // The wire resolved but its type can't
634                        // coerce to a numeric metric value (Str,
635                        // vector, handle, etc.). Surface as a
636                        // hard ExecutionError so the activity's
637                        // `errors:` policy decides — by default
638                        // (errors=stop) the phase + run halt.
639                        return Err(ExecutionError::Op(crate::adapter::AdapterError {
640                            error_name: "metric_value_non_numeric".into(),
641                            message: format!(
642                                "metric '{family}' on cycle {cycle}: \
643                                 binding '{expr}' is not coercible to f64 \
644                                 (got value variant {disc:?}); metric \
645                                 values must be numeric (U64 / F64 / Bool)",
646                                family = slot.family,
647                                expr = slot.value_expr,
648                                disc = std::mem::discriminant(&value),
649                            ),
650                            retryable: false,
651                        }));
652                    }
653                };
654                let sanitised = slot.format.as_ref().map(|f| f.apply(raw)).unwrap_or(raw);
655                // A cell-placed metric resolves its coordinate from this
656                // cycle's wires and lands on the instrument for THAT cell.
657                let instrument = match (&slot.instrument, &slot.placement) {
658                    (Some(i), _) => std::borrow::Cow::Borrowed(i),
659                    (None, Some(p)) => match p.resolve(ctx.wires, &slot.family, cycle) {
660                        Ok(i) => std::borrow::Cow::Owned(i),
661                        Err(e) => return Err(e),
662                    },
663                    (None, None) => unreachable!("a slot has either an instrument or a placement"),
664                };
665                match instrument.as_ref() {
666                    MetricInstrument::Gauge(g) => g.set(sanitised),
667                    MetricInstrument::Histogram(h) => h.record(sanitised as u64),
668                    MetricInstrument::Counter(c) => {
669                        if sanitised <= 0.0 {
670                            crate::diag!(
671                                crate::observer::LogLevel::Warn,
672                                "counter '{}' got non-positive value {sanitised}; skipping",
673                                slot.family,
674                            );
675                        } else {
676                            c.inc_by(sanitised as u64);
677                        }
678                    }
679                }
680            }
681            Ok(result)
682        })
683    }
684    fn inner_dispenser(&self) -> Option<&dyn OpDispenser> {
685        Some(self.inner.as_ref())
686    }
687}
688
689#[cfg(test)]
690mod absent_value_tests {
691    /// A gauge whose binding resolved to `None` must publish NO SAMPLE, not
692    /// fail the run. `None` is the absence of a measurement: a conditional
693    /// aggregate like `:sum(progress where kind='secondary index build')`
694    /// yields it by design whenever no row has that kind, which is precisely
695    /// when a drain is idle and being watched. Erroring there killed a
696    /// 58-minute run at tier 19 with
697    /// `metric_value_non_numeric ... variant Discriminant(19)`.
698    ///
699    /// Genuinely non-numeric TYPES must still fail loudly — those are wiring
700    /// mistakes, not absences — so the skip is matched on `Value::None`
701    /// specifically, never on "failed to coerce".
702    #[test]
703    fn absent_binding_skips_the_sample_but_bad_types_still_fail() {
704        let src = std::fs::read_to_string(concat!(
705            env!("CARGO_MANIFEST_DIR"),
706            "/src/wrappers/metrics.rs"
707        ))
708        .expect("read own source");
709        let skip = src
710            .find("if matches!(value, polydat::ast::Value::None) {")
711            .expect("None must be skipped explicitly");
712        let coerce = src
713            .find("let raw = match value_to_f64(&value) {")
714            .expect("the coercion site must still exist");
715        assert!(
716            skip < coerce,
717            "the None skip must come BEFORE the coercion, or an absent value \
718             still reaches the error path"
719        );
720        assert!(
721            src.contains("metric_value_non_numeric"),
722            "non-numeric TYPES must still raise metric_value_non_numeric — \
723             the skip is for absence, not for bad wiring"
724        );
725    }
726}
727
728#[cfg(test)]
729mod tests {
730    use super::*;
731    use crate::adapter::{ExecutionError, OpResult};
732    use crate::fixture::ExecCtx;
733    use nmbrs_workload::model::{MetricKind, MetricSpec};
734
735    struct CapturesInner;
736    impl OpDispenser for CapturesInner {
737        fn execute<'a>(
738            &'a self,
739            _cycle: u64,
740            _ctx: &'a ExecCtx<'a>,
741        ) -> std::pin::Pin<
742            Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
743        > {
744            Box::pin(async move {
745                Ok(OpResult {
746                    body: None,
747                    skipped: false,
748                })
749            })
750        }
751    }
752
753    fn fresh_component() -> nmbrs_metrics::component::Component {
754        nmbrs_metrics::component::Component::new(
755            nmbrs_metrics::labels::Labels::empty(),
756            HashMap::new(),
757        )
758    }
759
760    /// A component as the production path holds it: an `Arc` (cells attach
761    /// under it) plus the `&mut` borrow registration needs.
762    fn fresh_component_arc() -> Arc<std::sync::RwLock<nmbrs_metrics::component::Component>> {
763        Arc::new(std::sync::RwLock::new(fresh_component()))
764    }
765
766    /// `MetricsDispenser::wrap` with the component handled the way the
767    /// activity does it.
768    fn wrap_on(
769        inner: Arc<dyn OpDispenser>,
770        decl: &HashMap<String, MetricSpec>,
771        comp: &Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
772        fx: &mut crate::fixture::ScopeFixture,
773    ) -> Result<Arc<dyn OpDispenser>, String> {
774        let mut guard = comp.write().unwrap();
775        MetricsDispenser::wrap(inner, decl, &mut guard, comp, fx)
776    }
777
778    fn fresh_fixture() -> crate::fixture::ScopeFixture {
779        use polydat::compile::assembly::{PolydatAssembler, WireRef};
780        use polydat::library::identity::Identity;
781        let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
782        asm.add_node(
783            "cycle_id",
784            Box::new(Identity::new(polydat::ast::PortType::U64)),
785            vec![WireRef::input("cycle")],
786        );
787        asm.add_output("cycle_id", WireRef::node("cycle_id"));
788        let kernel = asm.compile().expect("test fixture asm.compile");
789        crate::fixture::ScopeFixture::new(kernel.program().clone())
790    }
791
792    fn make_spec(value: &str, kind: MetricKind, format: Option<&str>) -> MetricSpec {
793        MetricSpec {
794            cell: Default::default(),
795            value: value.to_string(),
796            family: None,
797            kind: Some(kind),
798            unit: None,
799            format: format.map(|s| s.to_string()),
800        }
801    }
802
803    #[test]
804    fn metrics_dispenser_empty_returns_inner_unchanged() {
805        let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
806        let inner_ptr = Arc::as_ptr(&inner);
807        let comp = fresh_component_arc();
808        let mut fx = fresh_fixture();
809        let wrapped = wrap_on(inner.clone(), &HashMap::new(), &comp, &mut fx).unwrap();
810        assert_eq!(Arc::as_ptr(&wrapped), inner_ptr);
811    }
812
813    /// Test-only introspection: peek at allocated instrument
814    /// `Arc`s by family name. Tests need this because `wrap`
815    /// returns `Arc<dyn OpDispenser>` and we want to assert
816    /// against the same `ValueGauge` / `Histogram` / `Counter`
817    /// the wrapper writes through.
818    impl MetricsDispenser {
819        fn slot_gauge(
820            &self,
821            family: &str,
822        ) -> Option<Arc<nmbrs_metrics::instruments::gauge::ValueGauge>> {
823            self.slots
824                .iter()
825                .find(|s| s.family == family)
826                .and_then(|s| match s.instrument.as_ref()? {
827                    MetricInstrument::Gauge(g) => Some(g.clone()),
828                    _ => None,
829                })
830        }
831        fn slot_histogram(
832            &self,
833            family: &str,
834        ) -> Option<Arc<nmbrs_metrics::instruments::histogram::Histogram>> {
835            self.slots
836                .iter()
837                .find(|s| s.family == family)
838                .and_then(|s| match s.instrument.as_ref()? {
839                    MetricInstrument::Histogram(h) => Some(h.clone()),
840                    _ => None,
841                })
842        }
843        fn slot_counter(
844            &self,
845            family: &str,
846        ) -> Option<Arc<nmbrs_metrics::instruments::counter::Counter>> {
847            self.slots
848                .iter()
849                .find(|s| s.family == family)
850                .and_then(|s| match s.instrument.as_ref()? {
851                    MetricInstrument::Counter(c) => Some(c.clone()),
852                    _ => None,
853                })
854        }
855    }
856
857    fn kernel_with_const_outputs(
858        consts: &[(&str, f64)],
859    ) -> (
860        crate::scope_kernel::ScopeKernel,
861        crate::fixture::ScopeFixture,
862    ) {
863        use polydat::compile::assembly::{PolydatAssembler, WireRef};
864        use polydat::library::fixed::ConstF64;
865        let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
866        for (name, val) in consts {
867            let binding = crate::scope::synthesize_metric_binding_name(name);
868            asm.add_node(&binding, Box::new(ConstF64::new(*val)), vec![]);
869            asm.add_output(&binding, WireRef::node(&binding));
870        }
871        let kernel =
872            crate::scope_kernel::ScopeKernel::from(asm.compile().expect("test kernel asm.compile"));
873        let fx = crate::fixture::ScopeFixture::new(kernel.program().clone());
874        (kernel, fx)
875    }
876
877    fn typed_wrap_with_kernel(
878        inner: Arc<dyn OpDispenser>,
879        decls: &HashMap<String, MetricSpec>,
880        consts: &[(&str, f64)],
881    ) -> Result<
882        (
883            Arc<MetricsDispenser>,
884            crate::fixture::ResolvedPulls,
885            crate::scope_kernel::ScopeKernel,
886        ),
887        String,
888    > {
889        let (mut kernel, mut fx) = kernel_with_const_outputs(consts);
890        let mut comp = fresh_component();
891
892        if decls.is_empty() {
893            return Err("typed_wrap_with_kernel requires non-empty decls".into());
894        }
895        let mut entries: Vec<_> = decls.iter().collect();
896        entries.sort_by(|a, b| a.0.cmp(b.0));
897        let component_labels = comp.effective_labels().clone();
898        let mut slots = Vec::with_capacity(entries.len());
899        for (name, spec) in entries {
900            let family = spec.family.clone().unwrap_or_else(|| name.clone());
901            let format = match &spec.format {
902                Some(s) => Some(
903                    nmbrs_workload::metric_format::parse_format_spec(s)
904                        .map_err(|e| format!("metric '{name}' format: {e}"))?,
905                ),
906                None => None,
907            };
908            let kind = spec.kind.unwrap_or_default();
909            let instr_labels = component_labels.with("family", family.clone());
910            let instrument = match kind {
911                MetricKind::Gauge => MetricInstrument::Gauge(Arc::new(
912                    nmbrs_metrics::instruments::gauge::ValueGauge::new(instr_labels),
913                )),
914                MetricKind::Histogram => MetricInstrument::Histogram(Arc::new(
915                    nmbrs_metrics::instruments::histogram::Histogram::new(instr_labels),
916                )),
917                MetricKind::Counter => MetricInstrument::Counter(Arc::new(
918                    nmbrs_metrics::instruments::counter::Counter::new(instr_labels),
919                )),
920            };
921            comp.register_instrument_with_unit(
922                family.clone(),
923                spec.unit.clone(),
924                instrument.as_ref(),
925            )?;
926            let binding_name = crate::scope::synthesize_metric_binding_name(name);
927            let _ = fx.register_pull(&binding_name)?;
928            slots.push(MetricSlot {
929                family,
930                value_expr: spec.value.clone(),
931                binding_name,
932                format,
933                instrument: Some(instrument),
934                placement: None,
935            });
936        }
937        let typed = Arc::new(MetricsDispenser {
938            inner,
939            slots: Arc::new(slots),
940            op_cells: None,
941        });
942
943        let plan = fx.seal();
944        kernel.set_inputs(&[0]);
945        let pulls = plan.resolve_with(&mut kernel);
946        Ok((typed, pulls, kernel))
947    }
948
949    fn run_dispenser(
950        dispenser: Arc<dyn OpDispenser>,
951        pulls: &crate::fixture::ResolvedPulls,
952        kernel: &mut crate::scope_kernel::ScopeKernel,
953    ) -> Result<OpResult, ExecutionError> {
954        let fields = crate::adapter::ResolvedFields::new(vec![], vec![]);
955        let cw = crate::wires::CycleWires::new(kernel);
956        let ctx = ExecCtx::with_wires(&fields, pulls, &cw);
957        let rt = tokio::runtime::Builder::new_current_thread()
958            .build()
959            .unwrap();
960        rt.block_on(dispenser.execute(0, &ctx))
961    }
962
963    #[test]
964    fn metrics_dispenser_gauge_records_f64() {
965        let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
966        let mut decl = HashMap::new();
967        decl.insert(
968            "my_factor".into(),
969            make_spec("my_factor", MetricKind::Gauge, None),
970        );
971
972        let (typed, pulls, mut kernel) =
973            typed_wrap_with_kernel(inner, &decl, &[("my_factor", 3.5)]).unwrap();
974        let gauge = typed.slot_gauge("my_factor").unwrap();
975        run_dispenser(typed.clone() as Arc<dyn OpDispenser>, &pulls, &mut kernel).unwrap();
976
977        assert!((gauge.get() - 3.5).abs() < 1e-9);
978    }
979
980    #[test]
981    fn metrics_dispenser_histogram_truncates_to_u64() {
982        let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
983        let mut decl = HashMap::new();
984        decl.insert(
985            "latency_ms".into(),
986            make_spec("latency_ms", MetricKind::Histogram, None),
987        );
988
989        let (typed, pulls, mut kernel) =
990            typed_wrap_with_kernel(inner, &decl, &[("latency_ms", 7.9)]).unwrap();
991        let hist = typed.slot_histogram("latency_ms").unwrap();
992        run_dispenser(typed.clone() as Arc<dyn OpDispenser>, &pulls, &mut kernel).unwrap();
993
994        let snap = hist.peek_snapshot();
995        assert_eq!(snap.max(), 7);
996        assert_eq!(snap.len(), 1);
997    }
998
999    #[test]
1000    fn metrics_dispenser_counter_positive_inc_and_skip_non_positive() {
1001        let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
1002        let mut decl = HashMap::new();
1003        decl.insert(
1004            "ok_inc".into(),
1005            make_spec("ok_inc", MetricKind::Counter, None),
1006        );
1007        decl.insert(
1008            "skip_inc".into(),
1009            make_spec("skip_inc", MetricKind::Counter, None),
1010        );
1011
1012        let (typed, pulls, mut kernel) =
1013            typed_wrap_with_kernel(inner, &decl, &[("ok_inc", 5.0), ("skip_inc", 0.0)]).unwrap();
1014        let ok_counter = typed.slot_counter("ok_inc").unwrap();
1015        let skip_counter = typed.slot_counter("skip_inc").unwrap();
1016        run_dispenser(typed.clone() as Arc<dyn OpDispenser>, &pulls, &mut kernel).unwrap();
1017
1018        assert_eq!(ok_counter.get(), 5);
1019        assert_eq!(skip_counter.get(), 0);
1020    }
1021
1022    #[test]
1023    fn metrics_dispenser_format_rounds_value() {
1024        let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
1025        let mut decl = HashMap::new();
1026        decl.insert(
1027            "ratio".into(),
1028            make_spec("ratio", MetricKind::Gauge, Some("#.##")),
1029        );
1030
1031        let (typed, pulls, mut kernel) =
1032            typed_wrap_with_kernel(inner, &decl, &[("ratio", 1.234)]).unwrap();
1033        let gauge = typed.slot_gauge("ratio").unwrap();
1034        run_dispenser(typed.clone() as Arc<dyn OpDispenser>, &pulls, &mut kernel).unwrap();
1035
1036        assert!((gauge.get() - 1.23).abs() < 1e-9);
1037    }
1038
1039    #[test]
1040    fn metrics_dispenser_duplicate_family_errors() {
1041        let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
1042        let comp = fresh_component_arc();
1043        comp.write()
1044            .unwrap()
1045            .register_instrument(
1046                "recall_at_10",
1047                nmbrs_metrics::component::InstrumentRef::Counter(Arc::new(
1048                    nmbrs_metrics::instruments::counter::Counter::new(
1049                        nmbrs_metrics::labels::Labels::of("name", "recall_at_10"),
1050                    ),
1051                )),
1052            )
1053            .unwrap();
1054
1055        let mut decl = HashMap::new();
1056        decl.insert(
1057            "recall_at_10".into(),
1058            make_spec("recall_at_10", MetricKind::Gauge, None),
1059        );
1060
1061        let (_kernel, mut fx) = kernel_with_const_outputs(&[("recall_at_10", 0.0)]);
1062        let err = match wrap_on(inner, &decl, &comp, &mut fx) {
1063            Ok(_) => panic!("expected duplicate-family error, got Ok"),
1064            Err(e) => e,
1065        };
1066        assert!(
1067            err.contains("duplicate family name"),
1068            "unexpected error: {err}"
1069        );
1070    }
1071
1072    #[test]
1073    fn metrics_dispenser_skipped_op_records_nothing() {
1074        struct SkipInner;
1075        impl OpDispenser for SkipInner {
1076            fn execute<'a>(
1077                &'a self,
1078                _cycle: u64,
1079                _ctx: &'a ExecCtx<'a>,
1080            ) -> std::pin::Pin<
1081                Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
1082            > {
1083                Box::pin(async move { Ok(OpResult::skipped()) })
1084            }
1085        }
1086        let mut decl = HashMap::new();
1087        decl.insert("g".into(), make_spec("g", MetricKind::Gauge, None));
1088
1089        let (typed, pulls, mut kernel) =
1090            typed_wrap_with_kernel(Arc::new(SkipInner), &decl, &[("g", 1.0)]).unwrap();
1091        let gauge = typed.slot_gauge("g").unwrap();
1092
1093        let res =
1094            run_dispenser(typed.clone() as Arc<dyn OpDispenser>, &pulls, &mut kernel).unwrap();
1095        assert!(res.skipped);
1096        assert_eq!(gauge.get(), 0.0);
1097    }
1098
1099    #[test]
1100    fn metrics_dispenser_accepts_arbitrary_polydat_expression() {
1101        let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
1102        let mut decl = HashMap::new();
1103        decl.insert(
1104            "computed".into(),
1105            make_spec("factor * 2.0", MetricKind::Gauge, None),
1106        );
1107
1108        let (mut kernel, mut fx) = kernel_with_const_outputs(&[("computed", 6.0)]);
1109        let comp = fresh_component_arc();
1110        let _ = wrap_on(inner, &decl, &comp, &mut fx)
1111            .expect("arbitrary Polydat expression should wrap cleanly");
1112        let plan = fx.seal();
1113        kernel.set_inputs(&[0]);
1114        let _pulls = plan.resolve_with(&mut kernel);
1115    }
1116
1117    #[test]
1118    fn metrics_dispenser_missing_wire_errors_at_init() {
1119        let inner: Arc<dyn OpDispenser> = Arc::new(CapturesInner);
1120        let mut decl = HashMap::new();
1121        decl.insert(
1122            "missing_metric".into(),
1123            make_spec("absent_wire", MetricKind::Gauge, None),
1124        );
1125
1126        let (_kernel, mut fx) = kernel_with_const_outputs(&[("present", 1.0)]);
1127        let comp = fresh_component_arc();
1128        let err = wrap_on(inner, &decl, &comp, &mut fx)
1129            .err()
1130            .expect("missing-wire metric should error at init");
1131        assert!(err.contains("absent_wire"), "msg: {err}");
1132        assert!(err.contains("Available"), "msg: {err}");
1133    }
1134
1135    /// Silence dead-code warning for value_to_f64 (used inside
1136    /// wrapper but private to this module otherwise).
1137    #[test]
1138    fn value_to_f64_smoke() {
1139        assert_eq!(value_to_f64(&polydat::ast::Value::U64(5)), Some(5.0));
1140        assert_eq!(value_to_f64(&polydat::ast::Value::Bool(true)), Some(1.0));
1141        assert_eq!(value_to_f64(&polydat::ast::Value::Str("x".into())), None);
1142    }
1143}