1use 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
33pub const SERVICE_TIME_FAMILY: &str = "cycles_servicetime";
36
37pub(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
85struct RelevancyShape {
88 functions: Vec<RelevancyFn>,
89 k: usize,
90 r: Option<usize>,
91}
92
93pub struct OpCell {
95 coordinate: Labels,
97 labels: Labels,
100 service_time: Arc<Timer>,
103 validation: ValidationMetrics,
105}
106
107impl OpCell {
108 pub fn coordinate(&self) -> &Labels {
110 &self.coordinate
111 }
112
113 pub fn labels(&self) -> &Labels {
115 &self.labels
116 }
117
118 pub fn record_service_time(&self, nanos: u64) {
120 self.service_time.record(nanos);
121 }
122
123 pub fn validation(&self) -> &ValidationMetrics {
125 &self.validation
126 }
127}
128
129pub struct OpCells {
131 op: String,
133 dims: Vec<(String, String)>,
135 parent: Arc<RwLock<Component>>,
137 relevancy: OnceLock<RelevancyShape>,
140 instances: Mutex<HashMap<String, Arc<OpCell>>>,
144}
145
146impl OpCells {
147 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 pub fn dimensions(&self) -> impl Iterator<Item = &str> {
183 self.dims.iter().map(|(dim, _)| dim.as_str())
184 }
185
186 pub fn op(&self) -> &str {
188 &self.op
189 }
190
191 pub(crate) fn set_relevancy(&self, functions: &[RelevancyFn], k: usize, r: Option<usize>) {
195 let _ = self.relevancy.set(RelevancyShape {
199 functions: functions.to_vec(),
200 k,
201 r,
202 });
203 }
204
205 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 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 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 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}