1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// 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'"));
}
}