Skip to main content

nmbrs_runtime/
op_cells.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Dimensional placement of an op's own measurements (SRD-115 ยง4.4).
5//!
6//! An op that declares `cell:` has each cycle's service time, relevancy
7//! scores and validation outcomes recorded in the cell its coordinate
8//! expressions name for that cycle, as a declared metric with `cell:`
9//! has its value placed (`docs/metric-dimensions-from-data.md`). A cell
10//! is a child of the op's component, so it carries `op=` and every
11//! label above it, plus the coordinate.
12//!
13//! The phase's own totals are not replaced. They are recorded on the
14//! activity's component, a tier above, under the same family names; a
15//! series from a cell is told from a total by its `op` label.
16//!
17//! One [`OpCells`] is shared by the two wrappers that record into it:
18//! the validation wrapper, for scores and outcomes, and the metrics
19//! wrapper, for service time.
20
21use std::collections::HashMap;
22use std::sync::{Arc, Mutex, OnceLock, RwLock};
23
24use nmbrs_metrics::component::{Component, InstrumentRef};
25use nmbrs_metrics::instruments::timer::Timer;
26use nmbrs_metrics::labels::Labels;
27
28use crate::adapter::{AdapterError, ExecutionError};
29use crate::relevancy::RelevancyFn;
30use crate::validation::ValidationMetrics;
31use crate::wires::WireSource;
32
33/// The family an op cell's service time is registered under: the
34/// activity's own service-time family, one tier down.
35pub const SERVICE_TIME_FAMILY: &str = "cycles_servicetime";
36
37/// Read a cell coordinate from the cycle's wires.
38///
39/// `dims` pairs each dimension with the wire its expression was
40/// compiled to. `subject` names what is being placed, for the error
41/// text; `kind` prefixes the error names (`<kind>_cell_unresolved`,
42/// `<kind>_cell_not_a_string`).
43///
44/// A label value is a string. Anything else would key cells on
45/// formatting and not on identity, so it is refused, not rendered.
46pub(crate) fn read_coordinate(
47    dims: &[(String, String)],
48    wires: &dyn WireSource,
49    kind: &str,
50    subject: &str,
51    cycle: u64,
52) -> Result<Labels, ExecutionError> {
53    let mut coordinate = Labels::default();
54    for (dim, wire) in dims {
55        let Some(value) = wires.get(wire) else {
56            return Err(ExecutionError::Op(AdapterError {
57                error_name: format!("{kind}_cell_unresolved"),
58                message: format!(
59                    "{subject} on cycle {cycle}: coordinate binding \
60                     '{wire}' for dimension '{dim}' did not resolve through \
61                     ctx.wires โ€” this is a wiring bug between scope \
62                     synthesis and the wrapper that places the measurement"
63                ),
64                retryable: false,
65            }));
66        };
67        let polydat::ast::Value::Str(text) = &value else {
68            return Err(ExecutionError::Op(AdapterError {
69                error_name: format!("{kind}_cell_not_a_string"),
70                message: format!(
71                    "{subject} cell '{dim}' on cycle {cycle}: \
72                     coordinate resolved to a non-string {disc:?}. A \
73                     dimension's values are label values, which are \
74                     strings โ€” convert the expression explicitly.",
75                    disc = std::mem::discriminant(&value)
76                ),
77                retryable: false,
78            }));
79        };
80        coordinate = coordinate.with(dim.clone(), text.to_string());
81    }
82    Ok(coordinate)
83}
84
85/// What an op's relevancy evaluation computes, so each cell can hold
86/// the same statistics the op's totals do.
87struct RelevancyShape {
88    functions: Vec<RelevancyFn>,
89    k: usize,
90    r: Option<usize>,
91}
92
93/// One cell of an op: the instruments for one coordinate.
94pub struct OpCell {
95    /// The coordinate alone: the dimension labels this cell adds.
96    coordinate: Labels,
97    /// The cell component's effective labels: every inherited label
98    /// and the coordinate.
99    labels: Labels,
100    /// Service time of the cycles that landed in this cell. Registered
101    /// on the cell's component, so the cadence reporter captures it.
102    service_time: Arc<Timer>,
103    /// Relevancy statistics and validation outcomes of those cycles.
104    validation: ValidationMetrics,
105}
106
107impl OpCell {
108    /// The dimension labels of this cell.
109    pub fn coordinate(&self) -> &Labels {
110        &self.coordinate
111    }
112
113    /// Every label a series from this cell carries.
114    pub fn labels(&self) -> &Labels {
115        &self.labels
116    }
117
118    /// Record one cycle's service time.
119    pub fn record_service_time(&self, nanos: u64) {
120        self.service_time.record(nanos);
121    }
122
123    /// The relevancy statistics and validation outcomes of this cell.
124    pub fn validation(&self) -> &ValidationMetrics {
125        &self.validation
126    }
127}
128
129/// The cells of one op template, materialised per coordinate.
130pub struct OpCells {
131    /// The op's name, for error text.
132    op: String,
133    /// `(dimension, coordinate wire)`, in the workload's declared order.
134    dims: Vec<(String, String)>,
135    /// The op's component: the identity each cell refines.
136    parent: Arc<RwLock<Component>>,
137    /// Set once by the validation wrapper when the op scores relevancy,
138    /// before any cycle runs.
139    relevancy: OnceLock<RelevancyShape>,
140    /// Cells already materialised, keyed by the coordinate's canonical
141    /// rendering. Steady state is a hash lookup; the component attach
142    /// and the registry write happen once per coordinate.
143    instances: Mutex<HashMap<String, Arc<OpCell>>>,
144}
145
146impl OpCells {
147    /// The cells of `template` under its component `parent`, or `None`
148    /// when the op declares no `cell:`.
149    ///
150    /// Registers each coordinate wire as a pull, so a coordinate the
151    /// op-template kernel does not carry fails here, before any cycle.
152    pub fn for_op(
153        template: &nmbrs_workload::model::ParsedOp,
154        parent: &Arc<RwLock<Component>>,
155        fx: &mut crate::fixture::ScopeFixture,
156    ) -> Result<Option<Arc<Self>>, String> {
157        if template.cell.is_empty() {
158            return Ok(None);
159        }
160        let mut dims = Vec::with_capacity(template.cell.len());
161        for dim in template.cell.keys() {
162            let wire = crate::scope::synthesize_op_cell_binding_name(dim);
163            fx.register_pull(&wire).map_err(|e| {
164                format!(
165                    "cell '{dim}': {e} (synthesised coordinate binding \
166                     '{wire}' should have been registered by the \
167                     op-template kernel synthesiser โ€” this is a bug)"
168                )
169            })?;
170            dims.push((dim.clone(), wire));
171        }
172        Ok(Some(Arc::new(Self {
173            op: template.name.clone(),
174            dims,
175            parent: parent.clone(),
176            relevancy: OnceLock::new(),
177            instances: Mutex::new(HashMap::new()),
178        })))
179    }
180
181    /// The dimension names, in declared order.
182    pub fn dimensions(&self) -> impl Iterator<Item = &str> {
183        self.dims.iter().map(|(dim, _)| dim.as_str())
184    }
185
186    /// The op these cells belong to.
187    pub fn op(&self) -> &str {
188        &self.op
189    }
190
191    /// Declare the relevancy functions the op computes. Called once,
192    /// when the validation wrapper is built; every cell materialised
193    /// afterwards holds statistics for these functions.
194    pub(crate) fn set_relevancy(&self, functions: &[RelevancyFn], k: usize, r: Option<usize>) {
195        // A second declaration would be a second validation wrapper on
196        // one op, which the wrapper registry does not build; the first
197        // stands.
198        let _ = self.relevancy.set(RelevancyShape {
199            functions: functions.to_vec(),
200            k,
201            r,
202        });
203    }
204
205    /// The cell for this cycle's coordinate, materialised on first
206    /// sight of each distinct coordinate.
207    pub fn resolve(
208        &self,
209        wires: &dyn WireSource,
210        cycle: u64,
211    ) -> Result<Arc<OpCell>, ExecutionError> {
212        let subject = format!("op '{}'", self.op);
213        let coordinate = read_coordinate(&self.dims, wires, "op", &subject, cycle)?;
214        let key = coordinate.to_prometheus();
215        {
216            let cache = self.instances.lock().unwrap_or_else(|e| e.into_inner());
217            if let Some(found) = cache.get(&key) {
218                return Ok(found.clone());
219            }
220        }
221
222        let component = nmbrs_metrics::cells::resolve_under(&self.parent, &coordinate);
223        let mut cache = self.instances.lock().unwrap_or_else(|e| e.into_inner());
224        // Two fibers may reach a new coordinate together. The component
225        // is one either way (the cell map memoises it); the instruments
226        // must be one too, so the second fiber takes the first's.
227        if let Some(found) = cache.get(&key) {
228            return Ok(found.clone());
229        }
230        let mut guard = component.write().unwrap_or_else(|e| e.into_inner());
231        let labels = guard.effective_labels().clone();
232        let service_time = Arc::new(Timer::with_sigdigs_from(
233            labels.with("name", SERVICE_TIME_FAMILY),
234            &guard,
235        ));
236        guard
237            .register_instrument(
238                SERVICE_TIME_FAMILY,
239                InstrumentRef::Timer(service_time.clone()),
240            )
241            .map_err(|e| {
242                ExecutionError::Op(AdapterError {
243                    error_name: "op_cell_family_collision".into(),
244                    message: format!("{subject} cell {key}: {e}"),
245                    retryable: false,
246                })
247            })?;
248        drop(guard);
249        let validation = match self.relevancy.get() {
250            Some(shape) => ValidationMetrics::new(&labels, &shape.functions, shape.k, shape.r),
251            None => ValidationMetrics::assertions_only(),
252        };
253        let cell = Arc::new(OpCell {
254            coordinate,
255            labels,
256            service_time,
257            validation,
258        });
259        cache.insert(key, cell.clone());
260        Ok(cell)
261    }
262
263    /// Every cell materialised so far, ordered by coordinate.
264    pub fn cells(&self) -> Vec<Arc<OpCell>> {
265        let cache = self.instances.lock().unwrap_or_else(|e| e.into_inner());
266        let mut keyed: Vec<(&String, &Arc<OpCell>)> = cache.iter().collect();
267        keyed.sort_by(|a, b| a.0.cmp(b.0));
268        keyed.into_iter().map(|(_, cell)| cell.clone()).collect()
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275    use polydat::ast::Value;
276
277    /// Wires held in a map, for a coordinate read.
278    struct Fixed(HashMap<String, Value>);
279
280    impl WireSource for Fixed {
281        fn get(&self, name: &str) -> Option<Value> {
282            self.0.get(name).cloned()
283        }
284        fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
285            Box::new(self.0.keys().cloned())
286        }
287    }
288
289    fn wires(pairs: &[(&str, Value)]) -> Fixed {
290        Fixed(
291            pairs
292                .iter()
293                .map(|(k, v)| (k.to_string(), v.clone()))
294                .collect(),
295        )
296    }
297
298    fn cells_over(dims: &[&str]) -> (Arc<RwLock<Component>>, OpCells) {
299        let phase = Arc::new(RwLock::new(Component::new(
300            Labels::of("phase", "probe"),
301            HashMap::new(),
302        )));
303        let op = Arc::new(RwLock::new(Component::new(
304            Labels::of("op", "select"),
305            HashMap::new(),
306        )));
307        nmbrs_metrics::component::attach(&phase, &op);
308        let cells = OpCells {
309            op: "select".into(),
310            dims: dims
311                .iter()
312                .map(|d| {
313                    (
314                        d.to_string(),
315                        crate::scope::synthesize_op_cell_binding_name(d),
316                    )
317                })
318                .collect(),
319            parent: op,
320            relevancy: OnceLock::new(),
321            instances: Mutex::new(HashMap::new()),
322        };
323        (phase, cells)
324    }
325
326    #[test]
327    fn one_coordinate_is_one_cell_and_carries_the_ops_labels() {
328        let (_phase, cells) = cells_over(&["band", "form"]);
329        let w = wires(&[
330            ("__opcell_band", Value::Str("1pct".into())),
331            ("__opcell_form", Value::Str("topic.eq".into())),
332        ]);
333        let first = cells.resolve(&w, 0).expect("resolves");
334        let again = cells.resolve(&w, 1).expect("resolves");
335        assert!(Arc::ptr_eq(&first, &again));
336        assert_eq!(cells.cells().len(), 1);
337        let rendered = first.labels().to_prometheus();
338        for owned in ["phase=", "op=", "band=\"1pct\"", "form=\"topic.eq\""] {
339            assert!(rendered.contains(owned), "{owned} missing from {rendered}");
340        }
341    }
342
343    #[test]
344    fn distinct_coordinates_keep_separate_statistics() {
345        let (_phase, cells) = cells_over(&["band"]);
346        cells.set_relevancy(&[RelevancyFn::Recall], 10, None);
347        let narrow = wires(&[("__opcell_band", Value::Str("1pct".into()))]);
348        let wide = wires(&[("__opcell_band", Value::Str("10pct".into()))]);
349        cells
350            .resolve(&narrow, 0)
351            .unwrap()
352            .validation()
353            .record_relevancy("recall", 0.5);
354        cells
355            .resolve(&wide, 1)
356            .unwrap()
357            .validation()
358            .record_relevancy("recall", 1.0);
359        cells
360            .resolve(&wide, 2)
361            .unwrap()
362            .validation()
363            .record_relevancy("recall", 1.0);
364        let all = cells.cells();
365        assert_eq!(all.len(), 2);
366        let count = |band: &str| {
367            all.iter()
368                .find(|c| c.coordinate().get("band") == Some(band))
369                .map(|c| c.validation().relevancy_stats["recall"].snapshot().len())
370        };
371        assert_eq!(count("1pct"), Some(1));
372        assert_eq!(count("10pct"), Some(2));
373    }
374
375    #[test]
376    fn a_coordinate_that_is_not_text_is_refused() {
377        let (_phase, cells) = cells_over(&["band"]);
378        let w = wires(&[("__opcell_band", Value::U64(3))]);
379        let Err(ExecutionError::Op(e)) = cells.resolve(&w, 7) else {
380            panic!("a numeric coordinate must be refused");
381        };
382        assert_eq!(e.error_name, "op_cell_not_a_string");
383        assert!(e.message.contains("op 'select'") && e.message.contains("'band'"));
384    }
385}