nmbrs-runtime 0.7.2

Workload execution runtime for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Dimensional placement of an op's own measurements (SRD-115 ยง4.4).
//!
//! An op that declares `cell:` has each cycle's service time, relevancy
//! scores and validation outcomes recorded in the cell its coordinate
//! expressions name for that cycle, as a declared metric with `cell:`
//! has its value placed (`docs/metric-dimensions-from-data.md`). A cell
//! is a child of the op's component, so it carries `op=` and every
//! label above it, plus the coordinate.
//!
//! The phase's own totals are not replaced. They are recorded on the
//! activity's component, a tier above, under the same family names; a
//! series from a cell is told from a total by its `op` label.
//!
//! One [`OpCells`] is shared by the two wrappers that record into it:
//! the validation wrapper, for scores and outcomes, and the metrics
//! wrapper, for service time.

use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock, RwLock};

use nmbrs_metrics::component::{Component, InstrumentRef};
use nmbrs_metrics::instruments::timer::Timer;
use nmbrs_metrics::labels::Labels;

use crate::adapter::{AdapterError, ExecutionError};
use crate::relevancy::RelevancyFn;
use crate::validation::ValidationMetrics;
use crate::wires::WireSource;

/// The family an op cell's service time is registered under: the
/// activity's own service-time family, one tier down.
pub const SERVICE_TIME_FAMILY: &str = "cycles_servicetime";

/// Read a cell coordinate from the cycle's wires.
///
/// `dims` pairs each dimension with the wire its expression was
/// compiled to. `subject` names what is being placed, for the error
/// text; `kind` prefixes the error names (`<kind>_cell_unresolved`,
/// `<kind>_cell_not_a_string`).
///
/// A label value is a string. Anything else would key cells on
/// formatting and not on identity, so it is refused, not rendered.
pub(crate) fn read_coordinate(
    dims: &[(String, String)],
    wires: &dyn WireSource,
    kind: &str,
    subject: &str,
    cycle: u64,
) -> Result<Labels, ExecutionError> {
    let mut coordinate = Labels::default();
    for (dim, wire) in dims {
        let Some(value) = wires.get(wire) else {
            return Err(ExecutionError::Op(AdapterError {
                error_name: format!("{kind}_cell_unresolved"),
                message: format!(
                    "{subject} on cycle {cycle}: coordinate binding \
                     '{wire}' for dimension '{dim}' did not resolve through \
                     ctx.wires โ€” this is a wiring bug between scope \
                     synthesis and the wrapper that places the measurement"
                ),
                retryable: false,
            }));
        };
        let polydat::ast::Value::Str(text) = &value else {
            return Err(ExecutionError::Op(AdapterError {
                error_name: format!("{kind}_cell_not_a_string"),
                message: format!(
                    "{subject} cell '{dim}' on cycle {cycle}: \
                     coordinate resolved to a non-string {disc:?}. A \
                     dimension's values are label values, which are \
                     strings โ€” convert the expression explicitly.",
                    disc = std::mem::discriminant(&value)
                ),
                retryable: false,
            }));
        };
        coordinate = coordinate.with(dim.clone(), text.to_string());
    }
    Ok(coordinate)
}

/// What an op's relevancy evaluation computes, so each cell can hold
/// the same statistics the op's totals do.
struct RelevancyShape {
    functions: Vec<RelevancyFn>,
    k: usize,
    r: Option<usize>,
}

/// One cell of an op: the instruments for one coordinate.
pub struct OpCell {
    /// The coordinate alone: the dimension labels this cell adds.
    coordinate: Labels,
    /// The cell component's effective labels: every inherited label
    /// and the coordinate.
    labels: Labels,
    /// Service time of the cycles that landed in this cell. Registered
    /// on the cell's component, so the cadence reporter captures it.
    service_time: Arc<Timer>,
    /// Relevancy statistics and validation outcomes of those cycles.
    validation: ValidationMetrics,
}

impl OpCell {
    /// The dimension labels of this cell.
    pub fn coordinate(&self) -> &Labels {
        &self.coordinate
    }

    /// Every label a series from this cell carries.
    pub fn labels(&self) -> &Labels {
        &self.labels
    }

    /// Record one cycle's service time.
    pub fn record_service_time(&self, nanos: u64) {
        self.service_time.record(nanos);
    }

    /// The relevancy statistics and validation outcomes of this cell.
    pub fn validation(&self) -> &ValidationMetrics {
        &self.validation
    }
}

/// The cells of one op template, materialised per coordinate.
pub struct OpCells {
    /// The op's name, for error text.
    op: String,
    /// `(dimension, coordinate wire)`, in the workload's declared order.
    dims: Vec<(String, String)>,
    /// The op's component: the identity each cell refines.
    parent: Arc<RwLock<Component>>,
    /// Set once by the validation wrapper when the op scores relevancy,
    /// before any cycle runs.
    relevancy: OnceLock<RelevancyShape>,
    /// Cells already materialised, keyed by the coordinate's canonical
    /// rendering. Steady state is a hash lookup; the component attach
    /// and the registry write happen once per coordinate.
    instances: Mutex<HashMap<String, Arc<OpCell>>>,
}

impl OpCells {
    /// The cells of `template` under its component `parent`, or `None`
    /// when the op declares no `cell:`.
    ///
    /// Registers each coordinate wire as a pull, so a coordinate the
    /// op-template kernel does not carry fails here, before any cycle.
    pub fn for_op(
        template: &nmbrs_workload::model::ParsedOp,
        parent: &Arc<RwLock<Component>>,
        fx: &mut crate::fixture::ScopeFixture,
    ) -> Result<Option<Arc<Self>>, String> {
        if template.cell.is_empty() {
            return Ok(None);
        }
        let mut dims = Vec::with_capacity(template.cell.len());
        for dim in template.cell.keys() {
            let wire = crate::scope::synthesize_op_cell_binding_name(dim);
            fx.register_pull(&wire).map_err(|e| {
                format!(
                    "cell '{dim}': {e} (synthesised coordinate binding \
                     '{wire}' should have been registered by the \
                     op-template kernel synthesiser โ€” this is a bug)"
                )
            })?;
            dims.push((dim.clone(), wire));
        }
        Ok(Some(Arc::new(Self {
            op: template.name.clone(),
            dims,
            parent: parent.clone(),
            relevancy: OnceLock::new(),
            instances: Mutex::new(HashMap::new()),
        })))
    }

    /// The dimension names, in declared order.
    pub fn dimensions(&self) -> impl Iterator<Item = &str> {
        self.dims.iter().map(|(dim, _)| dim.as_str())
    }

    /// The op these cells belong to.
    pub fn op(&self) -> &str {
        &self.op
    }

    /// Declare the relevancy functions the op computes. Called once,
    /// when the validation wrapper is built; every cell materialised
    /// afterwards holds statistics for these functions.
    pub(crate) fn set_relevancy(&self, functions: &[RelevancyFn], k: usize, r: Option<usize>) {
        // A second declaration would be a second validation wrapper on
        // one op, which the wrapper registry does not build; the first
        // stands.
        let _ = self.relevancy.set(RelevancyShape {
            functions: functions.to_vec(),
            k,
            r,
        });
    }

    /// The cell for this cycle's coordinate, materialised on first
    /// sight of each distinct coordinate.
    pub fn resolve(
        &self,
        wires: &dyn WireSource,
        cycle: u64,
    ) -> Result<Arc<OpCell>, ExecutionError> {
        let subject = format!("op '{}'", self.op);
        let coordinate = read_coordinate(&self.dims, wires, "op", &subject, cycle)?;
        let key = coordinate.to_prometheus();
        {
            let cache = self.instances.lock().unwrap_or_else(|e| e.into_inner());
            if let Some(found) = cache.get(&key) {
                return Ok(found.clone());
            }
        }

        let component = nmbrs_metrics::cells::resolve_under(&self.parent, &coordinate);
        let mut cache = self.instances.lock().unwrap_or_else(|e| e.into_inner());
        // Two fibers may reach a new coordinate together. The component
        // is one either way (the cell map memoises it); the instruments
        // must be one too, so the second fiber takes the first's.
        if let Some(found) = cache.get(&key) {
            return Ok(found.clone());
        }
        let mut guard = component.write().unwrap_or_else(|e| e.into_inner());
        let labels = guard.effective_labels().clone();
        let service_time = Arc::new(Timer::with_sigdigs_from(
            labels.with("name", SERVICE_TIME_FAMILY),
            &guard,
        ));
        guard
            .register_instrument(
                SERVICE_TIME_FAMILY,
                InstrumentRef::Timer(service_time.clone()),
            )
            .map_err(|e| {
                ExecutionError::Op(AdapterError {
                    error_name: "op_cell_family_collision".into(),
                    message: format!("{subject} cell {key}: {e}"),
                    retryable: false,
                })
            })?;
        drop(guard);
        let validation = match self.relevancy.get() {
            Some(shape) => ValidationMetrics::new(&labels, &shape.functions, shape.k, shape.r),
            None => ValidationMetrics::assertions_only(),
        };
        let cell = Arc::new(OpCell {
            coordinate,
            labels,
            service_time,
            validation,
        });
        cache.insert(key, cell.clone());
        Ok(cell)
    }

    /// Every cell materialised so far, ordered by coordinate.
    pub fn cells(&self) -> Vec<Arc<OpCell>> {
        let cache = self.instances.lock().unwrap_or_else(|e| e.into_inner());
        let mut keyed: Vec<(&String, &Arc<OpCell>)> = cache.iter().collect();
        keyed.sort_by(|a, b| a.0.cmp(b.0));
        keyed.into_iter().map(|(_, cell)| cell.clone()).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use polydat::ast::Value;

    /// Wires held in a map, for a coordinate read.
    struct Fixed(HashMap<String, Value>);

    impl WireSource for Fixed {
        fn get(&self, name: &str) -> Option<Value> {
            self.0.get(name).cloned()
        }
        fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
            Box::new(self.0.keys().cloned())
        }
    }

    fn wires(pairs: &[(&str, Value)]) -> Fixed {
        Fixed(
            pairs
                .iter()
                .map(|(k, v)| (k.to_string(), v.clone()))
                .collect(),
        )
    }

    fn cells_over(dims: &[&str]) -> (Arc<RwLock<Component>>, OpCells) {
        let phase = Arc::new(RwLock::new(Component::new(
            Labels::of("phase", "probe"),
            HashMap::new(),
        )));
        let op = Arc::new(RwLock::new(Component::new(
            Labels::of("op", "select"),
            HashMap::new(),
        )));
        nmbrs_metrics::component::attach(&phase, &op);
        let cells = OpCells {
            op: "select".into(),
            dims: dims
                .iter()
                .map(|d| {
                    (
                        d.to_string(),
                        crate::scope::synthesize_op_cell_binding_name(d),
                    )
                })
                .collect(),
            parent: op,
            relevancy: OnceLock::new(),
            instances: Mutex::new(HashMap::new()),
        };
        (phase, cells)
    }

    #[test]
    fn one_coordinate_is_one_cell_and_carries_the_ops_labels() {
        let (_phase, cells) = cells_over(&["band", "form"]);
        let w = wires(&[
            ("__opcell_band", Value::Str("1pct".into())),
            ("__opcell_form", Value::Str("topic.eq".into())),
        ]);
        let first = cells.resolve(&w, 0).expect("resolves");
        let again = cells.resolve(&w, 1).expect("resolves");
        assert!(Arc::ptr_eq(&first, &again));
        assert_eq!(cells.cells().len(), 1);
        let rendered = first.labels().to_prometheus();
        for owned in ["phase=", "op=", "band=\"1pct\"", "form=\"topic.eq\""] {
            assert!(rendered.contains(owned), "{owned} missing from {rendered}");
        }
    }

    #[test]
    fn distinct_coordinates_keep_separate_statistics() {
        let (_phase, cells) = cells_over(&["band"]);
        cells.set_relevancy(&[RelevancyFn::Recall], 10, None);
        let narrow = wires(&[("__opcell_band", Value::Str("1pct".into()))]);
        let wide = wires(&[("__opcell_band", Value::Str("10pct".into()))]);
        cells
            .resolve(&narrow, 0)
            .unwrap()
            .validation()
            .record_relevancy("recall", 0.5);
        cells
            .resolve(&wide, 1)
            .unwrap()
            .validation()
            .record_relevancy("recall", 1.0);
        cells
            .resolve(&wide, 2)
            .unwrap()
            .validation()
            .record_relevancy("recall", 1.0);
        let all = cells.cells();
        assert_eq!(all.len(), 2);
        let count = |band: &str| {
            all.iter()
                .find(|c| c.coordinate().get("band") == Some(band))
                .map(|c| c.validation().relevancy_stats["recall"].snapshot().len())
        };
        assert_eq!(count("1pct"), Some(1));
        assert_eq!(count("10pct"), Some(2));
    }

    #[test]
    fn a_coordinate_that_is_not_text_is_refused() {
        let (_phase, cells) = cells_over(&["band"]);
        let w = wires(&[("__opcell_band", Value::U64(3))]);
        let Err(ExecutionError::Op(e)) = cells.resolve(&w, 7) else {
            panic!("a numeric coordinate must be refused");
        };
        assert_eq!(e.error_name, "op_cell_not_a_string");
        assert!(e.message.contains("op 'select'") && e.message.contains("'band'"));
    }
}