nmbrs_workload/polydat_matter.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! SRD-13d §3.1 — declarative GK-content classification for
5//! every node in the workload AST. The scope-tree pre-walker
6//! uses [`HasPolydatMatter::polydat_matter`] as the **first question** at
7//! every scope decision: most workloads short-circuit here
8//! and never reach the program-hash-equivalence refinement
9//! (§3.2).
10//!
11//! Implementations cover the AST types — runtime objects
12//! (the `Component` tree, fibers, dispensers) consume the
13//! marks the trait produced; they don't implement the trait
14//! themselves. Polydat content lives on the AST, not on runtime
15//! state.
16
17use crate::model::{BindingsDef, ParsedOp, ScenarioNode, Workload, WorkloadPhase};
18
19/// SRD-13d §3.1 classification of how much Polydat content a
20/// scope-tree node carries.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum PolydatMatter {
23 /// No Polydat references at all — no `bindings:`, no
24 /// `metrics:`, no inline `{{<expr>}}`, no GK-typed
25 /// fields. Walker skips kernel construction entirely.
26 None,
27 /// References parent-scope Polydat names but **defines
28 /// nothing new**. Examples: `metrics:` declarations whose
29 /// `value:` is a bare name resolving to a parent binding;
30 /// inline `{{<name>}}` substitution where `<name>` is a
31 /// parent binding; op fields that bind parent-scope
32 /// wires without declaring new ones. Walker skips kernel
33 /// construction; reads thread through the parent's
34 /// kernel state directly.
35 Readonly,
36 /// Declares new bindings, wire expressions, or constants
37 /// that the parent doesn't supply. Walker materialises a
38 /// kernel for this node — possibly subject to hash-check
39 /// flattening (§3.2) if the new content turns out to be
40 /// equivalent to the parent's.
41 Definitions,
42}
43
44/// Implemented by every workload-AST type that can sit in
45/// the construction tree. Pure function of the parsed AST;
46/// no runtime state, no compilation.
47pub trait HasPolydatMatter {
48 /// Classify this node's contribution to Polydat content.
49 fn polydat_matter(&self) -> PolydatMatter;
50}
51
52// -----------------------------------------------------------
53// Helpers
54// -----------------------------------------------------------
55
56/// `bindings:` block contributes definitions when non-empty.
57fn bindings_def_matter(b: &BindingsDef) -> PolydatMatter {
58 if b.is_empty() {
59 PolydatMatter::None
60 } else {
61 PolydatMatter::Definitions
62 }
63}
64
65/// True when any value field on the op uses inline `{{<expr>}}`
66/// substitution. Promotes to `Definitions` because the
67/// rewrite pass (`crate::scope::rewrite_inline_exprs` in
68/// nmbrs-runtime) hoists each into a `__expr_N := <expr>`
69/// binding owned by the op.
70fn has_inline_expr(op: &ParsedOp) -> bool {
71 fn scan(v: &serde_json::Value) -> bool {
72 match v {
73 serde_json::Value::String(s) => s.contains("{{") && s.contains("}}"),
74 serde_json::Value::Array(arr) => arr.iter().any(scan),
75 serde_json::Value::Object(map) => map.values().any(scan),
76 _ => false,
77 }
78 }
79 op.op.values().any(scan) || op.params.values().any(scan)
80}
81
82// -----------------------------------------------------------
83// Trait impls
84// -----------------------------------------------------------
85
86impl HasPolydatMatter for ParsedOp {
87 fn polydat_matter(&self) -> PolydatMatter {
88 // Op-level bindings always promote when non-empty.
89 let by_bindings = bindings_def_matter(&self.bindings);
90 if by_bindings == PolydatMatter::Definitions {
91 return PolydatMatter::Definitions;
92 }
93
94 // Inline `{{<expr>}}` constructs on any op field
95 // hoist into anonymous bindings during pre-compile.
96 if has_inline_expr(self) {
97 return PolydatMatter::Definitions;
98 }
99
100 // metrics: any declared metric contributes Definitions.
101 // Post-SRD-68 follow-up: the op-template synthesiser
102 // appends a `__metric_<name> := <value_expr>` binding per
103 // metric (see `crate::scope::synthesize_metric_binding_name`)
104 // so the closure-binding economy can walk the value
105 // expression's free identifiers for magic-extern slot
106 // allocation. That synthesised binding is itself a
107 // definition, so even a bare-name `value: count` requires
108 // an op-template kernel — the kernel is where the
109 // synthesised `__metric_<name>` LHS lands.
110 if !self.metrics.is_empty() {
111 return PolydatMatter::Definitions;
112 }
113
114 // cell: each coordinate expression is synthesised as a binding
115 // on the op-template kernel, as a metric's is.
116 if !self.cell.is_empty() {
117 return PolydatMatter::Definitions;
118 }
119
120 // result: declarations expose result-body fields as
121 // Polydat wires — a definition by construction (the
122 // wire didn't exist before this op).
123 if self.result.as_ref().is_some_and(|r| !r.is_empty()) {
124 return PolydatMatter::Definitions;
125 }
126
127 // capture: writes result-extracted values onto Polydat
128 // wires — definitions by construction, same as `result:`.
129 // The op-template kernel is where the capture target's
130 // slot lives; when the target is an ancestral `shared`
131 // cell, that slot is what the wiring cascade cell-binds.
132 // Without materialisation the cycle-time write lands on a
133 // non-cell fallback and the captured value never crosses
134 // the phase boundary — a later phase gating on the cell
135 // reads its initializer forever.
136 if !self.captures.is_empty() {
137 return PolydatMatter::Definitions;
138 }
139
140 // Anything that gets here reads parent bindings only
141 // (e.g. `if:` / `delay:` references) or has nothing
142 // GK-shaped at all.
143 if self.condition.is_some() || self.delay.is_some() {
144 PolydatMatter::Readonly
145 } else {
146 PolydatMatter::None
147 }
148 }
149}
150
151impl HasPolydatMatter for WorkloadPhase {
152 fn polydat_matter(&self) -> PolydatMatter {
153 // Phase-level `bindings:` block on the phase AST.
154 // Today's parser also legacy-merges this into per-op
155 // bindings; the phase still owns the structural fact
156 // that it declared the binding (SRD-13d §3.1's
157 // classification operates on the AST, not on the
158 // post-merge runtime view).
159 let by_bindings = bindings_def_matter(&self.bindings);
160 if by_bindings == PolydatMatter::Definitions {
161 return PolydatMatter::Definitions;
162 }
163 // Phase-level `metrics:` synthesise `volatile __metric_<name>
164 // := <value>` (plus the injected `phase_start` extern) onto
165 // the phase kernel — definitions by construction, so the
166 // phase needs its own scope kernel even with no `bindings:`.
167 if !self.metrics.is_empty() {
168 return PolydatMatter::Definitions;
169 }
170 // `for_each:` clauses always bind iteration variables.
171 if self.for_each.is_some() {
172 return PolydatMatter::Definitions;
173 }
174 // `cycles` / `concurrency` referencing workload-param
175 // Polydat names (`{train_count}` etc.) ⇒ Readonly. `rate`
176 // is f64-typed today (no Polydat refs) but counted as a
177 // parent reference for symmetry; revisit when rate
178 // grows GK-expression support.
179 let refs_parent = [&self.cycles, &self.concurrency].iter().any(|opt| {
180 opt.as_ref()
181 .is_some_and(|s| s.contains('{') && s.contains('}'))
182 });
183 if refs_parent || self.rate.is_some() {
184 return PolydatMatter::Readonly;
185 }
186 PolydatMatter::None
187 }
188}
189
190impl HasPolydatMatter for ScenarioNode {
191 fn polydat_matter(&self) -> PolydatMatter {
192 match self {
193 // Iteration constructs always declare iteration
194 // variables — Definitions by construction.
195 ScenarioNode::Comprehension { .. }
196 | ScenarioNode::DoWhile { .. }
197 | ScenarioNode::DoUntil { .. } => PolydatMatter::Definitions,
198 // Phase reference + scenario-include wrappers
199 // don't add Polydat content on their own; the
200 // wrapped phase / included scenario carries it.
201 ScenarioNode::Phase(_) | ScenarioNode::IncludedScenario { .. } => PolydatMatter::None,
202 // Scenario-tree-level `bindings:` block (also the
203 // canonical lowered form of `set:` sugar) installs
204 // a Polydat scope kernel — Definitions by definition.
205 ScenarioNode::Bindings { .. } => PolydatMatter::Definitions,
206 }
207 }
208}
209
210impl HasPolydatMatter for Workload {
211 fn polydat_matter(&self) -> PolydatMatter {
212 // Workload root carries the top-level `bindings:`
213 // block + workload-level params. Either contributes
214 // Definitions when non-empty.
215 let by_bindings = bindings_def_matter(&self.bindings);
216 if by_bindings == PolydatMatter::Definitions {
217 return PolydatMatter::Definitions;
218 }
219 if !self.params.is_empty() {
220 // Params turn into `final <name> := <literal>`
221 // bindings on the workload-params kernel
222 // (crates/nmbrs-runtime/src/params.rs), so any param
223 // declaration is Polydat content.
224 return PolydatMatter::Definitions;
225 }
226 PolydatMatter::None
227 }
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233 use crate::model::{MetricSpec, ResultSpec};
234
235 fn empty_op(name: &str) -> ParsedOp {
236 ParsedOp::simple(name, "noop")
237 }
238
239 // ── ParsedOp ─────────────────────────────────────────
240
241 #[test]
242 fn parsed_op_with_no_polydat_content_is_none() {
243 let op = empty_op("x");
244 assert_eq!(op.polydat_matter(), PolydatMatter::None);
245 }
246
247 #[test]
248 fn parsed_op_with_bindings_is_definitions() {
249 let mut op = empty_op("x");
250 op.bindings = BindingsDef::PolydatSource("k := 5".into());
251 assert_eq!(op.polydat_matter(), PolydatMatter::Definitions);
252 }
253
254 #[test]
255 fn parsed_op_empty_bindings_string_is_none() {
256 let mut op = empty_op("x");
257 op.bindings = BindingsDef::PolydatSource(" \n ".into());
258 assert_eq!(op.polydat_matter(), PolydatMatter::None);
259 }
260
261 #[test]
262 fn parsed_op_with_inline_expr_is_definitions() {
263 let mut op = empty_op("x");
264 op.op.insert(
265 "stmt".into(),
266 serde_json::Value::String("SELECT {{cycle}}".into()),
267 );
268 assert_eq!(op.polydat_matter(), PolydatMatter::Definitions);
269 }
270
271 #[test]
272 fn parsed_op_metrics_bare_value_is_definitions() {
273 // Post-SRD-68 follow-up: every metric synthesises a
274 // `__metric_<name> := <value>` binding into the
275 // op-template kernel — even bare-name `value:` forms
276 // become a definition (the synthesised LHS is the
277 // definition), which requires an op-template kernel
278 // to exist. Used to return Readonly back when
279 // MetricsDispenser read parent bindings directly;
280 // that path is gone.
281 let mut op = empty_op("x");
282 op.metrics.insert(
283 "foo".into(),
284 MetricSpec {
285 value: "existing_wire".into(),
286 family: None,
287 kind: None,
288 unit: None,
289 format: None,
290 cell: Default::default(),
291 },
292 );
293 assert_eq!(op.polydat_matter(), PolydatMatter::Definitions);
294 }
295
296 #[test]
297 fn parsed_op_metrics_dotted_name_is_definitions() {
298 // Same as above; dotted-name forms equally require a
299 // synthesised `__metric_<name>` binding.
300 let mut op = empty_op("x");
301 op.metrics.insert(
302 "foo".into(),
303 MetricSpec {
304 value: "phase.recall_at_10".into(),
305 family: None,
306 kind: None,
307 unit: None,
308 format: None,
309 cell: Default::default(),
310 },
311 );
312 assert_eq!(op.polydat_matter(), PolydatMatter::Definitions);
313 }
314
315 #[test]
316 fn parsed_op_metrics_expression_is_definitions() {
317 let mut op = empty_op("x");
318 op.metrics.insert(
319 "foo".into(),
320 MetricSpec {
321 value: "factor * 2.0".into(),
322 family: None,
323 kind: None,
324 unit: None,
325 format: None,
326 cell: Default::default(),
327 },
328 );
329 assert_eq!(op.polydat_matter(), PolydatMatter::Definitions);
330 }
331
332 #[test]
333 fn parsed_op_with_result_is_definitions() {
334 let mut op = empty_op("x");
335 let mut entries = std::collections::BTreeMap::new();
336 entries.insert("rows_returned".into(), "count".into());
337 op.result = Some(ResultSpec::Map(entries));
338 assert_eq!(op.polydat_matter(), PolydatMatter::Definitions);
339 }
340
341 #[test]
342 fn parsed_op_with_only_condition_is_readonly() {
343 let mut op = empty_op("x");
344 op.condition = Some("ok".into());
345 assert_eq!(op.polydat_matter(), PolydatMatter::Readonly);
346 }
347
348 // ── ScenarioNode ─────────────────────────────────────
349
350 // ── WorkloadPhase ───────────────────────────────────
351
352 #[test]
353 fn workload_phase_with_phase_bindings_is_definitions() {
354 let phase = WorkloadPhase {
355 cycles: None,
356 concurrency: None,
357 rate: None,
358 adapter: None,
359 errors: None,
360 tags: None,
361 ops: vec![],
362 for_each: None,
363 loop_scope: None,
364 iter_scope: None,
365 checkpoint: None,
366 status_metrics: vec![],
367 metrics: Default::default(),
368 bindings: BindingsDef::PolydatSource("k := 5".into()),
369 poll: None,
370 ..Default::default()
371 };
372 assert_eq!(phase.polydat_matter(), PolydatMatter::Definitions);
373 }
374
375 #[test]
376 fn workload_phase_with_for_each_is_definitions() {
377 let phase = WorkloadPhase {
378 cycles: None,
379 concurrency: None,
380 rate: None,
381 adapter: None,
382 errors: None,
383 tags: None,
384 ops: vec![],
385 for_each: Some("k in 1,2,3".into()),
386 loop_scope: None,
387 iter_scope: None,
388 checkpoint: None,
389 status_metrics: vec![],
390 metrics: Default::default(),
391 bindings: BindingsDef::default(),
392 poll: None,
393 ..Default::default()
394 };
395 assert_eq!(phase.polydat_matter(), PolydatMatter::Definitions);
396 }
397
398 #[test]
399 fn workload_phase_with_metrics_is_definitions() {
400 // A phase-level `metrics:` block synthesises
401 // `volatile __metric_<name> := <value>` (+ the injected
402 // `phase_start` extern) onto the phase kernel, so the phase
403 // needs its own scope kernel even with no `bindings:`.
404 let mut metrics = std::collections::HashMap::new();
405 metrics.insert(
406 "time_to_index".to_string(),
407 crate::model::MetricSpec {
408 value: "current_epoch_millis() - phase_start".into(),
409 family: None,
410 kind: None,
411 unit: None,
412 format: None,
413 cell: Default::default(),
414 },
415 );
416 let phase = WorkloadPhase {
417 cycles: None,
418 concurrency: None,
419 rate: None,
420 adapter: None,
421 errors: None,
422 tags: None,
423 ops: vec![],
424 for_each: None,
425 loop_scope: None,
426 iter_scope: None,
427 checkpoint: None,
428 status_metrics: vec![],
429 metrics,
430 bindings: BindingsDef::default(),
431 poll: None,
432 ..Default::default()
433 };
434 assert_eq!(phase.polydat_matter(), PolydatMatter::Definitions);
435 }
436
437 #[test]
438 fn workload_phase_bare_is_none() {
439 let phase = WorkloadPhase {
440 cycles: None,
441 concurrency: None,
442 rate: None,
443 adapter: None,
444 errors: None,
445 tags: None,
446 ops: vec![],
447 for_each: None,
448 loop_scope: None,
449 iter_scope: None,
450 checkpoint: None,
451 status_metrics: vec![],
452 metrics: Default::default(),
453 bindings: BindingsDef::default(),
454 poll: None,
455 ..Default::default()
456 };
457 assert_eq!(phase.polydat_matter(), PolydatMatter::None);
458 }
459
460 #[test]
461 fn workload_phase_cycles_param_ref_is_readonly() {
462 let phase = WorkloadPhase {
463 cycles: Some("{train_count}".into()),
464 concurrency: None,
465 rate: None,
466 adapter: None,
467 errors: None,
468 tags: None,
469 ops: vec![],
470 for_each: None,
471 loop_scope: None,
472 iter_scope: None,
473 checkpoint: None,
474 status_metrics: vec![],
475 metrics: Default::default(),
476 bindings: BindingsDef::default(),
477 poll: None,
478 ..Default::default()
479 };
480 assert_eq!(phase.polydat_matter(), PolydatMatter::Readonly);
481 }
482
483 // ── ScenarioNode ─────────────────────────────────────
484
485 #[test]
486 fn scenario_node_phase_is_none() {
487 let node = ScenarioNode::Phase("p".into());
488 assert_eq!(node.polydat_matter(), PolydatMatter::None);
489 }
490
491 #[test]
492 fn scenario_node_do_while_is_definitions() {
493 let node = ScenarioNode::DoWhile {
494 condition: "ok".into(),
495 counter: None,
496 children: vec![],
497 };
498 assert_eq!(node.polydat_matter(), PolydatMatter::Definitions);
499 }
500}