nmbrs_workload/model.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Normalized workload model: the canonical ParsedOp representation.
5//!
6//! All YAML shorthand forms normalize to this model. This is what
7//! driver adapters consume.
8
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11
12/// A complete workload definition after normalization.
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct Workload {
15 #[serde(default)]
16 pub description: Option<String>,
17 #[serde(default)]
18 pub scenarios: HashMap<String, Vec<ScenarioStep>>,
19 #[serde(default)]
20 pub ops: Vec<ParsedOp>,
21 /// Workload-level Polydat bindings declared via the top-level
22 /// `bindings:` block. These compile into the workload-root
23 /// kernel directly, separate from per-op bindings — so
24 /// declarations like `cursor row = range(0, 50)` are visible
25 /// to scenario-level comprehensions (e.g.,
26 /// `for xval in all(row)`) without needing to be threaded
27 /// through phase-level ops.
28 #[serde(default)]
29 pub bindings: BindingsDef,
30 /// Resolved workload parameters. These are available as bind points
31 /// in op templates and as constants in Polydat bindings.
32 /// Populated from: workload `params:` defaults, CLI overrides, env vars.
33 #[serde(default)]
34 pub params: HashMap<String, String>,
35 /// Phase definitions. Each phase has its own config and either
36 /// inline ops or tag filters to select from blocks/top-level ops.
37 #[serde(default)]
38 pub phases: HashMap<String, WorkloadPhase>,
39 /// Phase names in YAML definition order. HashMap does not preserve
40 /// insertion order, so this Vec tracks the order phases appeared in
41 /// the workload YAML for deterministic default scenario execution.
42 #[serde(default)]
43 pub phase_order: Vec<String>,
44 /// SRD-83 — workload-shell stop conditions. Declarations distribute
45 /// by their `each:` selector: `each: phase` applies the predicate at
46 /// every phase, while `each: [self, workload]` evaluates it at the
47 /// workload shell itself (reading the `children_*` aggregate of
48 /// child phase outcomes).
49 #[serde(default)]
50 pub stop_when: Vec<StopConditionSpec>,
51 /// Param names declared in the workload YAML `params:` section.
52 /// Used to detect unrecognized CLI params. Does not include
53 /// ad-hoc CLI params.
54 #[serde(default)]
55 pub declared_params: Vec<String>,
56 /// Unified report block (SRD-46): plots and tables under one
57 /// schema with figure enumeration, palette/style cascade, and
58 /// declaration-order rendering. Replaces the separate
59 /// `plot:` and `summary:` blocks (gone, no shim).
60 #[serde(default)]
61 pub report: crate::report::Report,
62 /// Non-fatal warnings emitted by the report-block parser
63 /// (SRD-46). Empty in normal mode; strict mode (SRD-15)
64 /// promotes them to errors. Plumbed up so the runner /
65 /// validator decide how to surface them.
66 #[serde(default, skip_serializing)]
67 pub report_warnings: Vec<String>,
68 /// Non-fatal reference-resolution warnings from the
69 /// `extends:` chain (SRD-85 nearest-first): a target name
70 /// that matched multiple resources resolved to the nearest,
71 /// and the shadowing is surfaced here — never silently.
72 /// Logged by the runner; strict mode promotes to errors.
73 #[serde(default, skip_serializing)]
74 pub resolution_warnings: Vec<String>,
75 /// Fatal scenario-parse errors collected during
76 /// `parse_scenario_nodes` — typically "unknown scenario-
77 /// node key" cases the parser used to silently drop. Per
78 /// the project's "Never Ignore Silently" rule (memory),
79 /// the runner promotes these to hard errors before
80 /// dispatching the workload. Unlike `report_warnings`,
81 /// these are always-fatal regardless of strict mode —
82 /// a malformed scenario-tree node never produces useful
83 /// behavior, so a downstream `phase 'iterate' not found`
84 /// error masks the real bug.
85 #[serde(default, skip_serializing)]
86 pub scenario_parse_errors: Vec<String>,
87 /// Workload-wide default for the per-phase
88 /// [`WorkloadPhase::status_metrics`] field. Phases that don't
89 /// declare their own `status_metrics:` inherit this list.
90 /// Supports glob-style patterns (`recall*`, `latency*`) so a
91 /// single doc-root entry can emphasize a metric family across
92 /// every phase that produces it.
93 ///
94 /// Empty (default) → no metrics tail anywhere; per-phase
95 /// declarations are still honoured.
96 #[serde(default)]
97 pub status_metrics: Vec<String>,
98 /// Resolved `readouts:` block bindings (SRD-63 §5).
99 /// One entry per event slot the workload bound; the
100 /// runtime binder reads this map and dispatches at fire
101 /// time. Empty (default) → all slots fall back to the
102 /// hard-coded built-ins activity.rs uses today.
103 ///
104 /// Each value is a list of literal body strings — one
105 /// per readout invocation in the slot. The body strings
106 /// haven't been parsed against the readout grammar yet;
107 /// that happens at activity-init time once the workload
108 /// kernel is in place. Push 3 ships the data shape
109 /// only; Push 4 wires resolved layered overrides
110 /// (CLI / extends).
111 #[serde(default)]
112 pub readouts: ReadoutsBindings,
113 /// SRD-32a Push 3 — workload-root wrapper composition
114 /// override. When present, every op template in this
115 /// workload uses this innermost-to-outermost order
116 /// instead of the runtime's default tiebreaker order.
117 /// Per-op `wrappers: { order: ... }` shadows this entry
118 /// entirely (no cascading merge).
119 #[serde(default, skip_serializing_if = "Option::is_none")]
120 pub wrappers: Option<WrappersConfig>,
121 /// SRD-108 Part B — names the blueprint this document
122 /// IMPLEMENTS (resolved local-first, then bundled catalog,
123 /// like `extends:` targets). A document carrying this is an
124 /// implementation module: it provides op bodies for the
125 /// blueprint's abstract slots and must carry no phase
126 /// scaffolding of its own.
127 #[serde(default, skip_serializing_if = "Option::is_none")]
128 pub implements: Option<String>,
129 /// SRD-106 Part 3 — `stick_session: true` declares this
130 /// workload's intended usage as iterative re-attachment:
131 /// when the operator passes no explicit session selection
132 /// and `sessions/latest` exists, the run re-attaches to it
133 /// and layers a new execution per SRD-77, announcing the
134 /// re-attachment as the run's first notable event. CLI
135 /// `stick_session=true|false` overrides; `--session new`
136 /// forces a fresh session. Absent → today's fresh-session
137 /// behavior.
138 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub stick_session: Option<bool>,
140}
141
142impl Workload {
143 /// Unification (2026-05-27): the scenario-tree executor is
144 /// the sole execution path. Workloads that pre-date the
145 /// `phases:`/`scenarios:` shape — `op=...` inline CLI,
146 /// `blocks:` YAML, top-level `ops:` lists — would
147 /// historically run via a separate single-activity branch
148 /// in the runner that bypassed `run_phase`. After
149 /// unification that branch is gone; this method
150 /// synthesizes an implicit `main` phase + `default`
151 /// scenario so the runner has the phased shape to walk.
152 ///
153 /// **Idempotent**: when `phases` is already populated the
154 /// method returns without changes. The synthesized phase
155 /// owns the ops; `Workload::ops` stays populated because
156 /// downstream compile-time inspectors (the workload-root
157 /// kernel, wrapper-cascade resolver, bind-point
158 /// validator) still walk the top-level list.
159 ///
160 /// **Synthesized shape**: phase name `main`, scenario name
161 /// `default` containing `[Phase("main")]`. No `cycles` /
162 /// `concurrency` / `rate` / `errors` overrides — those
163 /// inherit from CLI / workload defaults via the existing
164 /// phased resolution.
165 pub fn synthesize_default_phase(&mut self) {
166 if !self.phases.is_empty() {
167 return;
168 }
169 if self.ops.is_empty() {
170 return;
171 }
172 const SYNTHETIC: &str = "main";
173 // Promote CLI-style `cycles=N` / `concurrency=N` /
174 // `rate=N` from `self.params` onto the synthetic
175 // phase. Pre-unification, the now-deleted single-
176 // activity branch read these directly off CLI params
177 // and set them on `ActivityConfig`; the phased branch
178 // reads them off `WorkloadPhase`. Forwarding here
179 // preserves the legacy contract — `nmbrs run op=...
180 // cycles=20` still runs 20 cycles after unification.
181 //
182 // The `==ops:N` wrap on cycles tells the per-phase
183 // resolver (executor.rs's `phase_cycles` block) to
184 // treat the number as a raw op-iteration count
185 // instead of the standard "N stanzas" multiplication.
186 // The legacy single-activity branch always used the
187 // op-count interpretation; without this, a 2-op
188 // stanza with `cycles=4` would run 8 ops instead of
189 // the historical 4.
190 let cycles = self.params.get("cycles").map(|c| format!("==ops:{c}"));
191 let concurrency = self.params.get("concurrency").cloned();
192 let rate = self.params.get("rate").cloned();
193 // Move GK-syntax workload-root bindings DOWN onto the
194 // synthetic phase. The legacy single-activity branch
195 // compiled workload-root bindings into the SAME kernel
196 // as the op templates, so destructure-target names
197 // (`(device, reading) := ...`) were locally visible.
198 // The phased path puts workload-root bindings on a
199 // separate kernel and exposes only the manifest names
200 // to child kernels — but the manifest lists the
201 // destructure tuple as a single entry, not the
202 // individual targets. Putting the bindings on the
203 // phase kernel preserves the legacy locality.
204 //
205 // The legacy `Map` form (`user_id: Hash(); Mod(...)`)
206 // gets a translation pass at workload-root that the
207 // phase-level parser doesn't apply — so we leave that
208 // form alone. Only `PolydatSource` (native Polydat string form)
209 // moves down. This split matches the two-form parser
210 // contract and avoids re-implementing translation.
211 let bindings = match &self.bindings {
212 BindingsDef::PolydatSource(_) => std::mem::take(&mut self.bindings),
213 BindingsDef::Map(_) => BindingsDef::default(),
214 };
215 let phase = WorkloadPhase {
216 ops: self.ops.clone(),
217 bindings,
218 cycles,
219 concurrency,
220 rate,
221 ..Default::default()
222 };
223 self.phases.insert(SYNTHETIC.to_string(), phase);
224 self.phase_order.push(SYNTHETIC.to_string());
225 // Only seed the default scenario when none was
226 // declared — an operator-authored `scenarios:` block
227 // (even with no phases yet) is honoured as-is.
228 if self.scenarios.is_empty() {
229 self.scenarios.insert(
230 "default".to_string(),
231 vec![ScenarioStep::Phase(SYNTHETIC.to_string())],
232 );
233 }
234 }
235}
236
237/// SRD-32a Push 3 — wrapper-composition override block.
238/// Carries an explicit innermost-to-outermost order list
239/// that the resolver uses in place of its built-in
240/// default-order tiebreaker. The list must be a permutation
241/// of the wrappers the op actually triggers (after
242/// transitive activation); listing a non-triggered wrapper
243/// or omitting a triggered one is a hard error per SRD-32a
244/// §"Workload-level override".
245#[derive(Debug, Clone, Default, Serialize, Deserialize)]
246pub struct WrappersConfig {
247 /// Innermost-to-outermost wrapper-name list. Empty list
248 /// is treated as "no override" (equivalent to leaving
249 /// `wrappers:` off the workload).
250 #[serde(default, skip_serializing_if = "Vec::is_empty")]
251 pub order: Vec<String>,
252}
253
254/// Per-event-slot list of readout body strings declared in
255/// the workload's `readouts:` block. See SRD-63 §5.0 for
256/// the three legal forms.
257///
258/// The lower-case slot keys here mirror the
259/// `nmbrs_runtime::lifecycle::EventType::slot_name` return values
260/// (`on_phase_end`, `on_update`, …) so workload yaml
261/// uses the same vocabulary the design doc uses.
262#[derive(Debug, Clone, Default, Serialize, Deserialize)]
263pub struct ReadoutsBindings {
264 #[serde(default, skip_serializing_if = "Vec::is_empty")]
265 pub on_session_start: Vec<String>,
266 #[serde(default, skip_serializing_if = "Vec::is_empty")]
267 pub on_session_end: Vec<String>,
268 #[serde(default, skip_serializing_if = "Vec::is_empty")]
269 pub on_phase_start: Vec<String>,
270 #[serde(default, skip_serializing_if = "Vec::is_empty")]
271 pub on_phase_end: Vec<String>,
272 #[serde(default, skip_serializing_if = "Vec::is_empty")]
273 pub on_each_start: Vec<String>,
274 #[serde(default, skip_serializing_if = "Vec::is_empty")]
275 pub on_each_end: Vec<String>,
276 #[serde(default, skip_serializing_if = "Vec::is_empty")]
277 pub on_scope_start: Vec<String>,
278 #[serde(default, skip_serializing_if = "Vec::is_empty")]
279 pub on_scope_end: Vec<String>,
280 #[serde(default, skip_serializing_if = "Vec::is_empty")]
281 pub on_update: Vec<String>,
282}
283
284impl ReadoutsBindings {
285 /// True when no slot has any binding. Workloads in
286 /// this state fall through to the built-in defaults
287 /// activity.rs uses today.
288 pub fn is_empty(&self) -> bool {
289 self.on_session_start.is_empty()
290 && self.on_session_end.is_empty()
291 && self.on_phase_start.is_empty()
292 && self.on_phase_end.is_empty()
293 && self.on_each_start.is_empty()
294 && self.on_each_end.is_empty()
295 && self.on_scope_start.is_empty()
296 && self.on_scope_end.is_empty()
297 && self.on_update.is_empty()
298 }
299
300 /// Look up a slot's body list by its `slot_name` (e.g.
301 /// `"on_update"`). Returns an empty slice when the
302 /// slot has no bindings.
303 pub fn get(&self, slot_name: &str) -> &[String] {
304 match slot_name {
305 "on_session_start" => &self.on_session_start,
306 "on_session_end" => &self.on_session_end,
307 "on_phase_start" => &self.on_phase_start,
308 "on_phase_end" => &self.on_phase_end,
309 "on_each_start" => &self.on_each_start,
310 "on_each_end" => &self.on_each_end,
311 "on_scope_start" => &self.on_scope_start,
312 "on_scope_end" => &self.on_scope_end,
313 "on_update" => &self.on_update,
314 _ => &[],
315 }
316 }
317}
318
319/// Parsed summary report configuration.
320///
321/// Controls which columns, rows, and aggregates appear in the
322/// post-run summary table. Parsed from a semicolon-delimited DSL:
323///
324/// ```text
325/// "recall; mean(recall) over profile~label; details=hide"
326/// ```
327///
328/// Directives:
329/// - Bare words (no `=` or `(`): gauge column filter patterns, comma-separated.
330/// `"all"` shows every discovered gauge.
331/// - `filter=<regex>`: row filter on activity labels.
332/// - `<func>(<col>) over <key>~<pat>`: aggregate expression.
333/// - `details=hide`: suppress individual data rows.
334#[derive(Debug, Clone)]
335pub struct SummaryConfig {
336 /// Gauge column filter patterns (e.g., `["recall", "precision"]`).
337 /// Empty means show all discovered gauges.
338 pub columns: Vec<String>,
339 /// Row filter regex patterns on activity labels.
340 pub row_filters: Vec<String>,
341 /// Aggregate expressions to compute after the data rows.
342 pub aggregates: Vec<AggregateExpr>,
343 /// Whether to show individual data rows (default `true`).
344 pub show_details: bool,
345 /// Raw source string for diagnostics and future Polydat template detection.
346 pub raw: String,
347 /// SRD-46 v2: native MetricsQL columns. When non-empty,
348 /// `summary_command` routes through the metricsql renderer
349 /// instead of the legacy SQL builder. Each entry is
350 /// `(column_name, metricsql_expression)`. Anonymous
351 /// single-column form (`query: <expr>`) lands as
352 /// `("value", expr)`.
353 pub metricsql_columns: Vec<(String, String)>,
354 /// Label key the metricsql results are grouped on (becomes
355 /// the leftmost column of the rendered table). When empty
356 /// AND `metricsql_columns` is non-empty, the renderer falls
357 /// back to a single un-grouped row showing the average value
358 /// across all returned series.
359 ///
360 /// Multi-key form: `group_by: k, r, optimize_for` produces
361 /// one table row per distinct tuple — the same series
362 /// breakdown the matching plot draws.
363 pub group_by: Vec<String>,
364 /// SRD-46 — `state: <expr>`: a per-row COMPLETION test rendered as a word
365 /// rather than a number. A row whose expression yields a value is `complete`;
366 /// a row with none is `active`.
367 ///
368 /// The expression to use is whatever the workload records only at completion,
369 /// so "has this finished" is answered by the presence of that datum rather
370 /// than inferred from a progress percentage — a progress gauge can sit below
371 /// 100 on a row that finished, because the last poll before completion is the
372 /// value that persists.
373 pub state_query: Option<String>,
374 /// Per-column header annotations (`header <col>: <text>`) —
375 /// rendered into the column's header stack under its name, so a
376 /// table can carry each column's DEFINITION (e.g. the SRD-113
377 /// designation `last(result_success)`) where the reader is
378 /// already looking.
379 pub header_notes: Vec<(String, String)>,
380}
381
382/// An aggregate expression: either
383/// `mean(recall) over profile~label` (single-key filter form,
384/// emits one aggregate row) or
385/// `mean(recall) over k,limit,optimize_for` (multi-key grouping
386/// form, emits one aggregate row per distinct value-tuple).
387#[derive(Debug, Clone)]
388pub struct AggregateExpr {
389 /// Aggregation function.
390 pub function: AggFunction,
391 /// Column name pattern — only gauge columns containing this string
392 /// are aggregated; others show `-` in the aggregate row.
393 pub column_pattern: String,
394 /// Label key to filter rows on (e.g., `"profile"`).
395 /// Set in the single-key filter form. Empty when
396 /// `group_by` is non-empty (multi-key grouping form).
397 pub label_key: String,
398 /// Substring pattern matched against the label value (e.g., `"label"`).
399 /// Set in the single-key filter form. Empty when
400 /// `group_by` is non-empty.
401 pub label_pattern: String,
402 /// Multi-key grouping form: when non-empty, rows are
403 /// grouped by every distinct tuple of values across these
404 /// label keys, and the aggregate emits one row per group.
405 /// `label_key` / `label_pattern` are empty when this is set.
406 pub group_by: Vec<String>,
407}
408
409/// Supported aggregation functions for summary report expressions.
410#[derive(Debug, Clone, Copy, PartialEq, Eq)]
411pub enum AggFunction {
412 Mean,
413 Min,
414 Max,
415}
416
417impl std::fmt::Display for AggFunction {
418 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
419 match self {
420 AggFunction::Mean => write!(f, "mean"),
421 AggFunction::Min => write!(f, "min"),
422 AggFunction::Max => write!(f, "max"),
423 }
424 }
425}
426
427impl Serialize for SummaryConfig {
428 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
429 serializer.serialize_str(&self.raw)
430 }
431}
432
433impl<'de> Deserialize<'de> for SummaryConfig {
434 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
435 let raw = String::deserialize(deserializer)?;
436 Ok(SummaryConfig::parse(&raw))
437 }
438}
439
440impl SummaryConfig {
441 /// Parse a short-form summary DSL string.
442 ///
443 /// Semicolon-separated directives:
444 /// - `"recall,precision"` — column filters
445 /// - `"filter=search_post"` — row filter
446 /// - `"mean(recall) over profile~label"` — aggregate expression
447 /// - `"details=hide"` — hide individual data rows
448 pub fn parse(raw: &str) -> Self {
449 let mut columns = Vec::new();
450 let mut row_filters = Vec::new();
451 let mut aggregates = Vec::new();
452 let mut show_details = true;
453 let mut metricsql_columns: Vec<(String, String)> = Vec::new();
454 let mut group_by: Vec<String> = Vec::new();
455 let mut state_query: Option<String> = None;
456 let mut header_notes: Vec<(String, String)> = Vec::new();
457
458 // Strip `#` line comments before parsing (SRD-46:
459 // report/plot/table bodies all support `#` comments).
460 let cleaned = strip_hash_line_comments(raw);
461
462 // SRD-46 v2 line-pass: native-form directives
463 // (`query: <expr>`, `query <col>: <expr>`, `group_by: <key>`).
464 // Pulled out before the legacy `;`-separator pass so a
465 // metricsql expression containing `;` (rare but legal)
466 // doesn't get sliced apart, and so legacy and native
467 // forms can coexist during migration.
468 let mut residual_lines: Vec<String> = Vec::new();
469 for line in cleaned.lines().map(str::trim).filter(|s| !s.is_empty()) {
470 if let Some(rest) = line
471 .strip_prefix("group_by:")
472 .map(str::trim)
473 .or_else(|| line.strip_prefix("group-by:").map(str::trim))
474 {
475 group_by = rest
476 .split(',')
477 .map(|s| s.trim().to_string())
478 .filter(|s| !s.is_empty())
479 .collect();
480 continue;
481 }
482 // Three surface forms for query columns:
483 // query <col>: <expr> — legacy named (space sep)
484 // query: <col>: <expr> — canonical named (uniform `name: value`)
485 // query: <expr> — single anonymous column
486 // The canonical form factors out as: after `query:`, if the
487 // remainder begins with a bare-identifier followed by `:`,
488 // the leading identifier is the column name; otherwise the
489 // whole remainder is the anonymous expression. Identifiers
490 // here are `[A-Za-z_][A-Za-z0-9_-]*` — anything containing
491 // whitespace, parens, braces, or operators forces the
492 // anonymous interpretation, which is what we want for
493 // metricsql expressions whose label-literal `:` shows up
494 // before a function-call `(`.
495 // `header <col>: <text>` — a column's header annotation.
496 if let Some(rest) = line.strip_prefix("header ") {
497 if let Some((col, note)) = rest.split_once(':') {
498 let (col, note) = (col.trim(), note.trim());
499 if !col.is_empty() && !note.is_empty() {
500 header_notes.push((col.to_string(), note.to_string()));
501 }
502 }
503 continue;
504 }
505 // `state: <expr>` — completion test, rendered as a word.
506 if let Some(rest) = line.strip_prefix("state:") {
507 let expr = rest.trim();
508 if !expr.is_empty() {
509 state_query = Some(expr.to_string());
510 }
511 continue;
512 }
513 if let Some(rest) = line.strip_prefix("query") {
514 let rest = rest.trim_start();
515 if let Some(after_colon) = rest.strip_prefix(':') {
516 let after_colon = after_colon.trim_start();
517 if let Some((col, expr)) = split_named_query(after_colon) {
518 metricsql_columns.push((col, expr));
519 } else {
520 metricsql_columns
521 .push(("value".to_string(), after_colon.trim().to_string()));
522 }
523 continue;
524 }
525 // Legacy `query <col>: <expr>` form — the next
526 // colon terminates the column name.
527 if let Some(colon_idx) = rest.find(':') {
528 let col = rest[..colon_idx].trim().to_string();
529 let expr = rest[colon_idx + 1..].trim().to_string();
530 if !col.is_empty() && !expr.is_empty() {
531 metricsql_columns.push((col, expr));
532 continue;
533 }
534 }
535 }
536 residual_lines.push(line.to_string());
537 }
538 let cleaned: String = residual_lines.join(";");
539
540 for directive in cleaned.split(';').map(str::trim).filter(|s| !s.is_empty()) {
541 if directive == "details=hide" {
542 show_details = false;
543 } else if let Some(filter) = directive.strip_prefix("filter=") {
544 row_filters.push(filter.trim().to_string());
545 } else if let Some(agg) = Self::parse_aggregate(directive) {
546 aggregates.push(agg);
547 } else {
548 // Column filter: comma-separated names. Two
549 // names are recognized as wildcards ("show
550 // every gauge column"): the legacy `all`
551 // keyword and `*` (the bare-`--summary` user
552 // mental model — `nmbrs --summary '*'` means
553 // "default summary of all metrics").
554 for col in directive
555 .split(',')
556 .map(str::trim)
557 .filter(|s| !s.is_empty())
558 {
559 if col != "all" && col != "*" {
560 columns.push(col.to_string());
561 }
562 // `all` / `*` = empty columns vec = show
563 // every gauge with no filtering.
564 }
565 }
566 }
567
568 SummaryConfig {
569 columns,
570 row_filters,
571 aggregates,
572 show_details,
573 raw: raw.to_string(),
574 metricsql_columns,
575 group_by,
576 state_query,
577 header_notes,
578 }
579 }
580
581 /// Try to parse an aggregate directive in either form:
582 /// - `<func>(<col>) over <key>~<pat>` (single-key filter)
583 /// - `<func>(<col>) over <k1>,<k2>,…` (multi-key grouping)
584 fn parse_aggregate(s: &str) -> Option<AggregateExpr> {
585 let paren_open = s.find('(')?;
586 let paren_close = s.find(')')?;
587 if paren_close <= paren_open {
588 return None;
589 }
590
591 let func_name = s[..paren_open].trim();
592 let function = match func_name {
593 "mean" => AggFunction::Mean,
594 "min" => AggFunction::Min,
595 "max" => AggFunction::Max,
596 _ => return None,
597 };
598
599 let column_pattern = s[paren_open + 1..paren_close].trim().to_string();
600
601 let after_paren = s[paren_close + 1..].trim();
602 let over_rest = after_paren.strip_prefix("over")?.trim();
603
604 // Single-key filter form: `<key>~<pat>` (note: `~` may
605 // appear inside multi-key form too, e.g. nobody writes
606 // `k,a~b` — use presence of `~` as the discriminator;
607 // for clean multi-key, no `~` is present).
608 if let Some(tilde) = over_rest.find('~') {
609 let label_key = over_rest[..tilde].trim().to_string();
610 let label_pattern = over_rest[tilde + 1..].trim().to_string();
611 return Some(AggregateExpr {
612 function,
613 column_pattern,
614 label_key,
615 label_pattern,
616 group_by: Vec::new(),
617 });
618 }
619
620 // Multi-key grouping form: comma-separated label keys.
621 let group_by: Vec<String> = over_rest
622 .split(',')
623 .map(str::trim)
624 .filter(|s| !s.is_empty())
625 .map(|s| s.to_string())
626 .collect();
627 if group_by.is_empty() {
628 return None;
629 }
630 Some(AggregateExpr {
631 function,
632 column_pattern,
633 label_key: String::new(),
634 label_pattern: String::new(),
635 group_by,
636 })
637 }
638}
639
640/// Strip `#` line comments from a multi-line spec body. A `#`
641/// Split a `query:` payload into `(column_name, expression)` when
642/// the payload's leading token is a bare identifier followed by
643/// `:`. Returns `None` for the anonymous-column form (the whole
644/// payload is the expression).
645///
646/// An identifier here is `[A-Za-z_][A-Za-z0-9_-]*`. The lookup
647/// fails as soon as any character outside that class appears
648/// before the first `:`, which is what guards a metricsql label
649/// expression like `recall_mean{k="10"}` from being mistaken for
650/// a column name (the `{` ends the candidate identifier before
651/// the eventual `:` inside `k="10"` is reached).
652fn split_named_query(text: &str) -> Option<(String, String)> {
653 let bytes = text.as_bytes();
654 let mut i = 0;
655 while i < bytes.len() {
656 let b = bytes[i];
657 let is_first = i == 0;
658 let ok = if is_first {
659 b.is_ascii_alphabetic() || b == b'_'
660 } else {
661 b.is_ascii_alphanumeric() || b == b'_' || b == b'-'
662 };
663 if !ok {
664 break;
665 }
666 i += 1;
667 }
668 if i == 0 {
669 return None;
670 }
671 // Optional whitespace, then `:` to separate name from value.
672 let mut j = i;
673 while j < bytes.len() && bytes[j].is_ascii_whitespace() {
674 j += 1;
675 }
676 if j >= bytes.len() || bytes[j] != b':' {
677 return None;
678 }
679 let name = text[..i].to_string();
680 let expr = text[j + 1..].trim().to_string();
681 if name.is_empty() || expr.is_empty() {
682 return None;
683 }
684 Some((name, expr))
685}
686
687/// starts a comment only when it's at line-start or preceded by
688/// whitespace — so hex colors (`#117733`) and JSON sub-blocks
689/// (`{"color": "#fff"}`) survive. Quoted strings are honoured.
690fn strip_hash_line_comments(s: &str) -> String {
691 let mut out = String::with_capacity(s.len());
692 for line in s.split_inclusive('\n') {
693 let mut quote: Option<char> = None;
694 let mut prev_ws = true;
695 let mut cut: Option<usize> = None;
696 for (i, ch) in line.char_indices() {
697 match quote {
698 Some(q) if ch == q => {
699 quote = None;
700 prev_ws = false;
701 }
702 Some(_) => {
703 prev_ws = false;
704 }
705 None => match ch {
706 '"' | '\'' => {
707 quote = Some(ch);
708 prev_ws = false;
709 }
710 '#' if prev_ws => {
711 cut = Some(i);
712 break;
713 }
714 c if c.is_whitespace() => {
715 prev_ws = true;
716 }
717 _ => {
718 prev_ws = false;
719 }
720 },
721 }
722 }
723 match cut {
724 Some(idx) => {
725 out.push_str(&line[..idx]);
726 if line.ends_with('\n') {
727 out.push('\n');
728 }
729 }
730 None => out.push_str(line),
731 }
732 }
733 out
734}
735
736#[cfg(test)]
737mod summary_config_tests {
738 use super::*;
739
740 #[test]
741 fn parses_multi_key_grouping() {
742 let cfg = SummaryConfig::parse("recall; mean(recall) over k,limit,optimize_for");
743 assert_eq!(cfg.aggregates.len(), 1, "got: {:?}", cfg.aggregates);
744 let agg = &cfg.aggregates[0];
745 assert_eq!(agg.group_by, vec!["k", "limit", "optimize_for"]);
746 assert!(agg.label_key.is_empty());
747 }
748
749 #[test]
750 fn parses_single_key_filter_form_unchanged() {
751 let cfg = SummaryConfig::parse("mean(recall) over profile~label");
752 assert_eq!(cfg.aggregates.len(), 1);
753 let agg = &cfg.aggregates[0];
754 assert!(agg.group_by.is_empty());
755 assert_eq!(agg.label_key, "profile");
756 assert_eq!(agg.label_pattern, "label");
757 }
758}
759
760/// SRD-83 — a scope-tree *level* a stop condition distributes to. The
761/// `each:` selector names one or more of these; the matter walk binds
762/// the predicate at every node of a named level inside the declaring
763/// subtree (a declared, structural fan-out — never inferred from the
764/// predicate's content). Aligned to the executor's `ScopeKind`.
765#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
766#[serde(rename_all = "snake_case")]
767pub enum ScopeLevel {
768 /// The declaring scope node itself (whatever its kind).
769 #[serde(rename = "self")]
770 SelfScope,
771 /// Every op-template node.
772 Op,
773 /// Every phase node.
774 Phase,
775 /// Every scenario node.
776 Scenario,
777 /// The workload root (the whole-run aggregate).
778 Workload,
779}
780
781fn default_each() -> Vec<ScopeLevel> {
782 // Absent `each:` → the declaring scope only. To fan a workload-level
783 // declaration out per-phase, the author writes `each: phase`.
784 vec![ScopeLevel::SelfScope]
785}
786
787/// Accept either a single level (`each: phase`) or a list
788/// (`each: [phase, scenario]`) — the scalar is sugar for a one-element
789/// set.
790fn de_each<'de, D>(d: D) -> Result<Vec<ScopeLevel>, D::Error>
791where
792 D: serde::Deserializer<'de>,
793{
794 #[derive(Deserialize)]
795 #[serde(untagged)]
796 enum OneOrMany {
797 One(ScopeLevel),
798 Many(Vec<ScopeLevel>),
799 }
800 Ok(match OneOrMany::deserialize(d)? {
801 OneOrMany::One(level) => vec![level],
802 OneOrMany::Many(levels) => levels,
803 })
804}
805
806/// SRD-83 follow-up — the FIRING axis (when a condition is evaluated),
807/// as a tagged-union *value* so the field name can't overclaim
808/// periodicity. `continuous` names the existing inline (per drain-loop
809/// turn) evaluation; `phase_end` names the phase-completion aggregation.
810/// A cadence value (`{every: <duration>}`) driving the metrics
811/// `CadenceReporter` registry is a later step and is intentionally NOT
812/// accepted here yet.
813#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
814#[serde(rename_all = "snake_case")]
815pub enum PulseSpec {
816 /// Evaluate inline, once per drain-loop turn (fine-grained; the only
817 /// scope with attempt-level wires).
818 Continuous,
819 /// Evaluate at phase-completion aggregation.
820 PhaseEnd,
821}
822
823/// SRD-83 — one stop condition declared on a shell. A polydat
824/// `condition:`/`when:` predicate over runtime-state wires (`op_count`,
825/// `error_rate`, `elapsed_ms`, `children_failed`, …); a `per:`/`each:`
826/// **detection** distribution selector (which scope levels it is
827/// evaluated at); a `pulse:` firing axis; an `action:`/`effect:`
828/// (`fail` → Interrupted+Failed, `stop` → Interrupted+Succeeded); and an
829/// `at:` **action** target scope (default = the innermost level of
830/// `per:`). When the predicate trips it stops the `at:` scope with the
831/// effect. Detection scope (`per:`) and action scope (`at:`) are
832/// independent.
833#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
834pub struct StopConditionSpec {
835 /// Polydat predicate over runtime-state wires, evaluating to bool.
836 pub when: String,
837 /// Scope levels this predicate is DETECTED/evaluated at (the declared
838 /// fan-out; see [`ScopeLevel`]). Defaults to the declaring scope (`self`).
839 #[serde(default = "default_each", deserialize_with = "de_each")]
840 pub each: Vec<ScopeLevel>,
841 /// Firing trigger (legacy string form). `None` → a sensible default per
842 /// condition kind. Superseded by `pulse:`; retained for compatibility.
843 #[serde(default)]
844 pub trigger: Option<String>,
845 /// Firing pulse — WHEN the predicate is evaluated. `None` → default per
846 /// condition kind (attempt/rate wires → `continuous`; `children_*` →
847 /// `phase_end`).
848 #[serde(default)]
849 pub pulse: Option<PulseSpec>,
850 /// Effect on fire: `"stop"`, `"fail"` or `"abort"`. `None` → `fail`.
851 #[serde(default)]
852 pub effect: Option<String>,
853 /// The ACTION target scope — where the effect lands, independent of
854 /// where it is detected (`each:`). `None` → the innermost (most
855 /// specific) level of `each:`, i.e. act in place (historical
856 /// behaviour). Set e.g. `at: workload` to route a phase-detected stop
857 /// out to the enclosing workload shell.
858 #[serde(default)]
859 pub at: Option<ScopeLevel>,
860}
861
862impl StopConditionSpec {
863 /// SRD-83 Part 5 — the closed `effect:` verb vocabulary.
864 /// `stop` = Interrupted+Succeeded (a clean early halt that keeps the
865 /// partial result); `fail` = Interrupted+Failed; `abort` = `fail`
866 /// plus cancelling in-flight ops.
867 pub const EFFECT_VOCABULARY: [&'static str; 3] = ["stop", "fail", "abort"];
868
869 /// Validate the semantic surface serde cannot: the effect verb.
870 /// The runtime's verb→Outcome map resolves any unrecognized string
871 /// to the shell default, so before this check a typo'd
872 /// `effect: sotp` silently became `fail` — an authoring trap.
873 /// Rejected at workload load instead ("never ignore silently").
874 pub fn validate(&self) -> Result<(), String> {
875 match self.effect.as_deref() {
876 Some(e) if !Self::EFFECT_VOCABULARY.contains(&e) => Err(format!(
877 "unknown stop-condition effect '{e}' on `when: {}` — \
878 expected one of stop|fail|abort",
879 self.when
880 )),
881 _ => Ok(()),
882 }
883 }
884}
885
886fn default_continue_if_each() -> Vec<ScopeLevel> {
887 // SRD-101 — a `continue_if` gate defaults to halting the enclosing
888 // SCENARIO sweep (the comprehension loop it rides), NOT the declaring
889 // node only. This intentionally differs from `StopConditionSpec`'s
890 // `default_each` (`self`): the gate's whole purpose is to bound a sweep.
891 vec![ScopeLevel::Scenario]
892}
893
894/// SRD-101 — a `continue_if` pre-entry sweep gate declared on a
895/// comprehension-bearing scenario step or phase. A polydat `when:` predicate
896/// over the iteration's COORDINATE context (`end_of(p)`, `idx_of(p)`,
897/// outer-scope consts like `effective_max_size`) plus an `each:` scope level.
898/// The walker evaluates it per iteration BEFORE entering the body; while it is
899/// true the iteration runs, and the moment it is false the sweep at `each`
900/// ends gracefully (Interrupted+Succeeded — see SRD-101 §4). Aligns with
901/// [`StopConditionSpec`] (shares `when`/`each` and the `ScopedExpr` machinery),
902/// but is a pre-entry gate with continue polarity and a fixed graceful effect.
903#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
904pub struct ContinueIfSpec {
905 /// Polydat predicate over the coordinate context. The sweep continues
906 /// while it is true and halts (gracefully) the moment it is false.
907 pub when: String,
908 /// Scope level whose sweep ends on a false predicate. Defaults to
909 /// `scenario` (the enclosing comprehension); `workload` halts the run.
910 /// (For a `continue_if` gate this level is both detection and action —
911 /// the full `each:`/`at:` split for gates is a later step.)
912 #[serde(default = "default_continue_if_each", deserialize_with = "de_each")]
913 pub each: Vec<ScopeLevel>,
914}
915
916/// Retry-backoff settings carried by the map form of `tries:`
917/// (`tries: {count: N, backoff: {ratio, min, max}}`). Each field is
918/// optional — a missing key falls back to the op's standalone
919/// `retry_backoff*` param, then the built-in default. Durations are kept
920/// as raw strings (e.g. `"100ms"`, `"10s"`) and parsed at wrap time by the
921/// runtime, so this crate needs no time parser.
922#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
923pub struct BackoffSpec {
924 /// Geometric growth factor applied per retry: attempt `k`'s wait is
925 /// `min * ratio^(k-1)`, capped at `max`. `2.0` (the default) doubles;
926 /// `1.0` holds the wait constant at `min`. `None` = default.
927 #[serde(default)]
928 pub ratio: Option<f64>,
929 /// Backoff floor — the first retry's wait (a duration string).
930 /// `None` = default (`100ms`). `"0"` disables pacing entirely.
931 #[serde(default)]
932 pub min: Option<String>,
933 /// Backoff ceiling — the wait never exceeds this (a duration string).
934 /// `None` = default (`10s`).
935 #[serde(default)]
936 pub max: Option<String>,
937}
938
939/// `throttle:` — adaptive backpressure governor: boolean sugar
940/// (`throttle: true` = all defaults) or the full spec map.
941#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
942#[serde(untagged)]
943pub enum ThrottleField {
944 /// `throttle: true` (defaults) / `throttle: false` (explicit off).
945 Enabled(bool),
946 /// Full spec map.
947 Spec(ThrottleSpec),
948}
949
950impl ThrottleField {
951 /// Normalize: `true` → the default spec, `false` → `None`.
952 pub fn to_spec(&self) -> Option<ThrottleSpec> {
953 match self {
954 ThrottleField::Enabled(true) => Some(ThrottleSpec::default()),
955 ThrottleField::Enabled(false) => None,
956 ThrottleField::Spec(s) => Some(s.clone()),
957 }
958 }
959}
960
961/// Adaptive backpressure governor parameters (SRD-83 §throttle).
962/// The governor keeps the WINDOWED attempt-failure fraction — the
963/// see-through-retries saturation signal — under `high` by walking
964/// the named dynamic control down multiplicatively, and recovers it
965/// toward the authored ceiling while the window stays under `low`.
966#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
967#[serde(deny_unknown_fields)]
968pub struct ThrottleSpec {
969 /// Windowed attempt-failure fraction that triggers a back-off.
970 #[serde(default = "throttle_default_high")]
971 pub high: f64,
972 /// Fraction below which the governor recovers toward the
973 /// authored ceiling. Default: `high / 5`.
974 #[serde(default)]
975 pub low: Option<f64>,
976 /// The dynamic control to walk: `concurrency` (default) or `rate`.
977 #[serde(default = "throttle_default_control")]
978 pub control: String,
979 /// Initial offered value (slow-start seed). Default: `floor` —
980 /// the governor assumes the most fragile target and PROVES
981 /// headroom by doubling through clean windows. Declare a higher
982 /// start only for targets known to be robust at phase entry.
983 #[serde(default)]
984 pub start: Option<f64>,
985 /// Never throttle below this value.
986 #[serde(default = "throttle_default_floor")]
987 pub floor: f64,
988 /// Evaluation window (duration string, e.g. "2s").
989 #[serde(default = "throttle_default_window")]
990 pub window: String,
991}
992
993fn throttle_default_high() -> f64 {
994 0.05
995}
996fn throttle_default_control() -> String {
997 "concurrency".to_string()
998}
999fn throttle_default_floor() -> f64 {
1000 1.0
1001}
1002fn throttle_default_window() -> String {
1003 "2s".to_string()
1004}
1005
1006impl Default for ThrottleSpec {
1007 fn default() -> Self {
1008 Self {
1009 high: throttle_default_high(),
1010 low: None,
1011 control: throttle_default_control(),
1012 start: None,
1013 floor: throttle_default_floor(),
1014 window: throttle_default_window(),
1015 }
1016 }
1017}
1018
1019/// SRD-109 — the time-dimension aggregate a key-metric designation
1020/// carries. MANDATORY on every designation: there are no implied
1021/// aggregates, so `rows: result_success` (no qualifier) is a parse
1022/// error naming this vocabulary. Defined over the stored samples of
1023/// one instance within the row scope's activation window — which,
1024/// per the SRD-42 amendment, are last-write-wins point samples with
1025/// PromQL semantics.
1026#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1027pub enum KeyAgg {
1028 Min,
1029 Max,
1030 Avg,
1031 Last,
1032 First,
1033 Median,
1034 Stddev,
1035 Sum,
1036 Count,
1037 /// Derived: increase over the activation span, per second.
1038 Rate,
1039 /// Derived: the activation's wall clock (family-less — `span()`).
1040 Span,
1041 /// Derived: last − first over the activation.
1042 Delta,
1043}
1044
1045impl KeyAgg {
1046 /// The suggestion list every qualification error carries.
1047 pub const VOCAB: &'static str = "min, max, avg, last, first, median, stddev, sum, count; \
1048 derived: rate(F), span(), delta(F)";
1049
1050 pub fn parse(name: &str) -> Option<Self> {
1051 Some(match name {
1052 "min" => Self::Min,
1053 "max" => Self::Max,
1054 "avg" => Self::Avg,
1055 "last" => Self::Last,
1056 "first" => Self::First,
1057 "median" => Self::Median,
1058 "stddev" => Self::Stddev,
1059 "sum" => Self::Sum,
1060 "count" => Self::Count,
1061 "rate" => Self::Rate,
1062 "span" => Self::Span,
1063 "delta" => Self::Delta,
1064 _ => return None,
1065 })
1066 }
1067}
1068
1069/// SRD-109 — one key-metric designation on an execution node:
1070/// `column: agg(family)`. Designating key metrics both names the
1071/// node's measurables and attaches the node to the table row of its
1072/// nearest enclosing anchor (or the spine). `family` is empty for
1073/// the family-less `span()`.
1074#[derive(Debug, Clone, Serialize, Deserialize)]
1075pub struct KeyMetric {
1076 pub column: String,
1077 pub agg: KeyAgg,
1078 pub family: String,
1079}
1080
1081/// A workload phase: runs as a separate Activity with its own
1082/// cycle count, concurrency, rate limit, and op selection.
1083#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1084pub struct WorkloadPhase {
1085 /// Number of stanzas for this phase. Each stanza executes all
1086 /// ops in sequence once. String type to support Polydat constant
1087 /// references like `"{train_count, dimensions: Default::default(),}"`. Default 1 (one stanza).
1088 #[serde(default)]
1089 pub cycles: Option<String>,
1090 /// Concurrency (async fibers). String type to support Polydat constant
1091 /// or workload param references like `"{concurrency}"`. Default 1.
1092 #[serde(default)]
1093 pub concurrency: Option<String>,
1094 /// Rate limit (ops/sec). A number, or a `{param}` / iter-var
1095 /// reference resolved at the phase gather (the SRD-83
1096 /// `timeout:` discipline: a rate that cannot be resolved
1097 /// fails the phase up front — it never silently becomes
1098 /// "unrated"). Default unlimited.
1099 #[serde(default)]
1100 pub rate: Option<String>,
1101 /// SRD-82 Part 6 — daemon phase. When `true`, this phase runs
1102 /// CONCURRENTLY with its foreground sibling phases (off the
1103 /// scenario's foreground concurrency budget) and is stopped
1104 /// cooperatively when the scope's foreground phases complete (a
1105 /// background "daemon unit" at the phase shell). Its own scope gives
1106 /// it an independent cursor base. Pair with an open-extent cursor
1107 /// (e.g. `until_elapsed`) so it runs for the foreground's duration.
1108 #[serde(default)]
1109 pub daemon: bool,
1110 /// Adapter override for this phase.
1111 #[serde(default)]
1112 pub adapter: Option<String>,
1113 /// Error routing spec override.
1114 #[serde(default)]
1115 pub errors: Option<String>,
1116 /// Total-attempts budget for this phase's ops. `tries:` is the SIGIL for
1117 /// the conditional tries wrapper (SRD-82 Part 3b): when NO budget
1118 /// resolves anywhere in scope (op field, this phase field, the
1119 /// workload-root `tries` param, or an in-scope `tries` wire), the
1120 /// wrapper is not constructed and the op runs single-attempt. `1` = the
1121 /// same single-attempt behaviour, explicitly (shadows an inherited
1122 /// budget); `0` = ops FAIL WITHOUT EXECUTING; `N ≥ 2` = up to N total
1123 /// attempts on adapter-retryable errors (CQL timeouts/overloads).
1124 /// `None` = inherit.
1125 #[serde(default)]
1126 pub tries: Option<u32>,
1127 /// Retry-backoff overrides parsed from the map form of `tries:`
1128 /// (`tries: {count: N, backoff: {ratio, min, max}}`). `None` when the
1129 /// sugared numeric form was used (or `tries` absent) — the wrapper then
1130 /// falls back to the op's standalone `retry_backoff*` params or the
1131 /// built-in defaults (ratio 2.0, min 100ms, max 10s). See
1132 /// [`BackoffSpec`].
1133 #[serde(default)]
1134 pub tries_backoff: Option<BackoffSpec>,
1135 /// SRD-82/92 cross-level wrapper (scoping P0) — phase-execution pacing.
1136 /// `interval:` is the discriminator for a future `WrapperLevel::Phase`
1137 /// interval wrapper: re-run this phase, sleeping `interval` between runs.
1138 /// A raw duration string (e.g. `"5m"`), parsed at wrap time by the
1139 /// runtime. Declarative today — the phase-level cascade that consumes it
1140 /// is not built yet (see `docs/cross-level-wrapper-cascade-scope.md`).
1141 #[serde(default)]
1142 pub interval: Option<String>,
1143 /// Bound for [`interval`](Self::interval) — how many times to run the
1144 /// phase. `None` alongside `interval` = repeat until the session stops.
1145 #[serde(default)]
1146 pub repeat: Option<u64>,
1147 /// OPT-IN error-rate circuit breaker (e.g. `0.1` = fail this phase
1148 /// once >10% of its ops error, after a 50-op floor). Overrides a
1149 /// session-wide `error_rate_max=` param when one was set. There is
1150 /// NO built-in default (SRD-82 §"AggregateGuard retired as a
1151 /// default") — aggregate health belongs to visible `stop_when:`
1152 /// conditions; this field exists as an explicit shorthand only.
1153 #[serde(default)]
1154 pub error_rate_max: Option<f64>,
1155 /// SRD-83 governance timeout (GAP-12). A duration (`"2.5h"`, `"150ms"`,
1156 /// bare fractional seconds) or a `{param}` reference; on expiry the
1157 /// phase ends Interrupted+Failed with reason class `timeout` — the
1158 /// protocol OUT-OF-RANGE disposition: the system is disqualified at
1159 /// this tier, the partial result is not usable. Desugars at the
1160 /// phase gather into a synthesized, logged `elapsed_ms >` stop
1161 /// condition (the `error_rate_max` precedent). Distinct from a
1162 /// BUDGET: a clean time-boxed measurement is a bounded cursor or a
1163 /// `stop_when … effect: stop` (Interrupted+Succeeded), not this.
1164 #[serde(default)]
1165 pub timeout: Option<String>,
1166 /// SRD-83 — stop conditions for this phase shell. Each is a polydat
1167 /// predicate over runtime-state wires, plus a firing trigger and an
1168 /// effect. Evaluated at triggers; a true predicate stops the phase
1169 /// with its effect.
1170 #[serde(default)]
1171 pub stop_when: Vec<StopConditionSpec>,
1172 /// SRD-83 §throttle — adaptive backpressure governor: keep the
1173 /// windowed attempt-failure fraction under a bound by walking a
1174 /// dynamic control (`concurrency`/`rate`) down under overload and
1175 /// back up on recovery. `throttle: true` = defaults.
1176 #[serde(default, skip_serializing_if = "Option::is_none")]
1177 pub throttle: Option<ThrottleField>,
1178 /// Tag filter to select ops from blocks (e.g., `"block:schema"`).
1179 #[serde(default)]
1180 pub tags: Option<String>,
1181 /// Inline ops for this phase (parsed into `ParsedOp` list).
1182 #[serde(default)]
1183 pub ops: Vec<ParsedOp>,
1184 /// Phase template iteration: `"var in expr"`.
1185 /// The phase is instantiated once per element of the Polydat expression
1186 /// result (which must be a comma-separated string). Each instance
1187 /// has `{var}` available as a workload param in its ops and config.
1188 ///
1189 /// Example: `for_each: "profile in matching_profiles('{dataset}', '{prefix}')"`
1190 #[serde(default)]
1191 pub for_each: Option<String>,
1192 /// SRD-101 — optional `continue_if` pre-entry gate bounding this phase's
1193 /// `for_each` sweep (see [`ContinueIfSpec`]). Ignored when `for_each` is
1194 /// absent (no sweep to bound).
1195 #[serde(default, skip_serializing_if = "Option::is_none")]
1196 pub continue_if: Option<ContinueIfSpec>,
1197 /// Loop scope mode for `for_each` phases.
1198 ///
1199 /// Controls how the loop context is seeded from the outer scope:
1200 /// - `clean` (default): snapshot of outer scope at loop entry
1201 /// - `inherit`: outer scope's live state (includes prior phase mutations)
1202 #[serde(default)]
1203 pub loop_scope: Option<String>,
1204 /// Iteration scope mode for `for_each` phases.
1205 ///
1206 /// Controls how each iteration is seeded from the loop scope:
1207 /// - `inherit` (default for for_each): each iteration starts from the loop
1208 /// scope's current state. All loop-level variables are implicitly shared
1209 /// with iterations, so iteration N+1 sees what N wrote.
1210 /// - `clean`: each iteration starts from the loop scope snapshot (isolated)
1211 #[serde(default)]
1212 pub iter_scope: Option<String>,
1213 /// Summary report configuration for this phase.
1214 /// Checkpoint declaration: skip-on-resume eligibility plus
1215 /// optional sub-properties (hashing, verify op). `None` =
1216 /// no declaration = phase always re-runs on resume. See
1217 /// SRD-44 §"Eligibility — `checkpoint:` per-phase declaration".
1218 ///
1219 /// Parsed via [`Checkpoint`]'s custom deserialize from the
1220 /// three YAML forms (short string, disabled string/bool,
1221 /// full mapping).
1222 #[serde(default)]
1223 pub checkpoint: Option<Checkpoint>,
1224 /// Names of metrics to surface on the inline progress line
1225 /// and the per-phase ✓ DONE summary. Empty (default) → no
1226 /// extra metrics shown; the status line carries only the
1227 /// universal counters (pct, throughput, ok-rate, errors,
1228 /// retries, concurrency, duration).
1229 ///
1230 /// Each name is matched against the live relevancy
1231 /// aggregates (`recall_at_10`, `precision_at_10`, …) by exact
1232 /// equality. Workloads that compute custom relevancy metrics
1233 /// list the names they want emphasized; nothing is presumed
1234 /// to be present.
1235 ///
1236 /// Example:
1237 /// ```yaml
1238 /// phases:
1239 /// ann_query:
1240 /// status_metrics: [recall_at_10]
1241 /// ```
1242 #[serde(default)]
1243 pub status_metrics: Vec<String>,
1244 /// Phase-level Polydat `bindings:` block (SRD-13c, SRD-13d).
1245 /// Captured on the phase AST so the scope-tree pre-walk
1246 /// (SRD-13d §3) can classify phase-level Polydat content via
1247 /// [`crate::polydat_matter::HasPolydatMatter`] and so the runtime
1248 /// can compose a phase kernel layered between the
1249 /// workload kernel and any op-template kernels.
1250 ///
1251 /// Today the parser ALSO merges this block into per-op
1252 /// bindings (legacy `parse.rs::parse_phases` behaviour) so
1253 /// the existing runtime keeps working unchanged. Once
1254 /// SRD-13d phases 3–9 land (per-template kernels with
1255 /// proper `bind_outer_scope` chaining through the phase
1256 /// kernel), the per-op merge is removed and ops resolve
1257 /// phase bindings via the Polydat scope chain.
1258 #[serde(default, skip_serializing_if = "BindingsDef::is_empty")]
1259 pub bindings: BindingsDef,
1260 /// Phase-level synthetic-metric declarations. Mirror of
1261 /// [`ParsedOp::metrics`] (same [`MetricSpec`] schema and YAML
1262 /// shapes), but evaluated **once at phase completion** against
1263 /// the phase scope kernel rather than per-cycle. Each entry's
1264 /// `value:` is a Polydat expression over phase-scope wires
1265 /// (bindings, captures, params, iter-vars) plus the
1266 /// executor-injected `phase_start` wire (epoch millis at phase
1267 /// start). The canonical phase-duration metric reads a clock via
1268 /// a `volatile` phase binding and subtracts the injected origin:
1269 /// ```yaml
1270 /// bindings: |
1271 /// volatile now_ms := current_epoch_millis()
1272 /// metrics:
1273 /// time_to_index: { value: now_ms - phase_start }
1274 /// ```
1275 /// yielding the phase's wall-clock duration in millis. Empty when
1276 /// absent. No dedicated clock node is needed: `current_epoch_millis()`
1277 /// is a single read, and `phase_start` arrives as plain data, so the
1278 /// expression re-evaluates correctly at the completion-time pull.
1279 /// Declaring the clock read as its own `volatile` binding (rather
1280 /// than nesting it in the metric value) explicitly acknowledges the
1281 /// non-deterministic node, so the phase kernel stays clean under
1282 /// `--strict`.
1283 ///
1284 /// The synthesiser emits `volatile __metric_<name> := <value>`
1285 /// onto the phase kernel (see
1286 /// `nmbrs_runtime::scope::synthesize_metric_binding_name`); the
1287 /// executor pulls each at completion and records it on the
1288 /// phase component as the declared instrument (gauge by default).
1289 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
1290 pub metrics: HashMap<String, MetricSpec>,
1291 /// Dimensions this phase introduces: label NAME → declaration.
1292 ///
1293 /// Declared at the tier that owns the name, per the component tree's
1294 /// label-ownership rule (a name is set on exactly one tier and
1295 /// inherited downward). Values are not enumerated — they arrive from
1296 /// data via a metric's `cell:`.
1297 ///
1298 /// `BTreeMap` for deterministic synthesis order: a coordinate's
1299 /// rendering is what keys a cell, so an order that varied between runs
1300 /// would key one coordinate two ways.
1301 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
1302 pub dimensions: std::collections::BTreeMap<String, DimensionSpec>,
1303 /// Phase-level poll spec — when present, the phase's
1304 /// cycle execution runs in a wall-clock loop until a GK
1305 /// predicate over captures returns `true`. SRD-75.
1306 ///
1307 /// The presence of this field carries semantics beyond
1308 /// the data: it forbids `concurrency > 1` (serial-cycle
1309 /// loop is the unit of work), and it triggers
1310 /// scope-synthesis to allocate `shared` cells on the
1311 /// phase scope for capture names referenced by the
1312 /// predicate / `if:` conditions / metric values so
1313 /// cross-op visibility happens through the canonical
1314 /// Polydat chain (no sidecar HashMap; see SRD-75
1315 /// §"Architectural shape").
1316 #[serde(default, skip_serializing_if = "Option::is_none")]
1317 pub poll: Option<PhasePollSpec>,
1318 /// SRD-86 — when present, the executor dispatches the named optimizer over
1319 /// the phase: it writes each axis as an input wire on the phase's binding
1320 /// kernel and reads the `objective` wire back (the objective is *just a
1321 /// wire read*). Workload-local config; `nmbrs-runtime` maps it to its
1322 /// optimizer contract and discovers the optimizer via the link-time
1323 /// registry (`nmbrs describe optimizers`).
1324 ///
1325 /// **Sugar:** a bare **string** value is shorthand for `{ objective: <str> }`
1326 /// with every other field defaulted (`method: sweep`, no `servo:`) — so
1327 /// `optimize: "0 - err_rate"` ≡ `optimize: { objective: "0 - err_rate" }`.
1328 /// See `de_optimize`.
1329 #[serde(
1330 default,
1331 deserialize_with = "de_optimize",
1332 skip_serializing_if = "Option::is_none"
1333 )]
1334 pub optimize: Option<OptimizeBlock>,
1335 /// SRD-109 — key-metric designations: `key_metrics: {column:
1336 /// "agg(family)", ...}`. Aggregate qualification is mandatory
1337 /// (no implied aggregates); the report synthesizer attaches
1338 /// these columns to the row of the phase's nearest enclosing
1339 /// anchor, or the spine. Empty = spine-only via the SRD-91
1340 /// instrument contract defaults.
1341 #[serde(default)]
1342 pub key_metrics: Vec<KeyMetric>,
1343}
1344
1345/// A phase `optimize:` value: **either** a bare string — sugar for
1346/// `{ objective: <string> }` with every other field defaulted — **or** a full
1347/// [`OptimizeBlock`] map. The untagged enum tries `Inline` first, so a scalar
1348/// value never reaches the map variant. Shared by the serde-derive path
1349/// ([`de_optimize`]) and the hand-rolled phase parser
1350/// (`parse::*` via [`OptimizeBlock::from_yaml_value`]).
1351#[derive(Deserialize)]
1352#[serde(untagged)]
1353enum OptimizeSpec {
1354 Inline(String),
1355 Block(OptimizeBlock),
1356}
1357
1358impl From<OptimizeSpec> for OptimizeBlock {
1359 fn from(spec: OptimizeSpec) -> Self {
1360 match spec {
1361 // SRD-86 string sugar: the whole value IS the objective expression.
1362 OptimizeSpec::Inline(objective) => OptimizeBlock {
1363 method: default_optimize_method(),
1364 objective,
1365 servo: Vec::new(),
1366 max_evals: default_optimize_max_evals(),
1367 seed: default_optimize_seed(),
1368 params: HashMap::new(),
1369 },
1370 OptimizeSpec::Block(b) => b,
1371 }
1372 }
1373}
1374
1375impl OptimizeBlock {
1376 /// Parse a phase `optimize:` value from already-parsed JSON, applying the
1377 /// string sugar (a bare string ≡ `{ objective: <string> }`). Used by the
1378 /// hand-rolled phase parser, which builds [`WorkloadPhase`] field-by-field
1379 /// rather than through the derive (so it doesn't see `de_optimize`).
1380 ///
1381 /// Branches explicitly rather than going through the untagged
1382 /// `OptimizeSpec` so a malformed *map* keeps its precise serde error
1383 /// (e.g. `missing field 'objective'`) instead of the untagged enum's
1384 /// generic "did not match any variant".
1385 pub fn from_yaml_value(v: &serde_json::Value) -> Result<OptimizeBlock, serde_json::Error> {
1386 if let Some(s) = v.as_str() {
1387 Ok(OptimizeSpec::Inline(s.to_string()).into())
1388 } else {
1389 serde_json::from_value::<OptimizeBlock>(v.clone())
1390 }
1391 }
1392}
1393
1394/// Deserialize a phase `optimize:` value via [`OptimizeSpec`] — a bare string is
1395/// sugar for `{ objective: <string> }`, a map is a full [`OptimizeBlock`]
1396/// (SRD-86):
1397///
1398/// ```yaml
1399/// optimize: |
1400/// 0 - metricsql_scalar("sum(rate(errors_total[3s]))")
1401/// ```
1402fn de_optimize<'de, D>(d: D) -> Result<Option<OptimizeBlock>, D::Error>
1403where
1404 D: serde::Deserializer<'de>,
1405{
1406 Ok(Option::<OptimizeSpec>::deserialize(d)?.map(Into::into))
1407}
1408
1409/// SRD-86 — a phase `optimize:` block. The optimizer **maximizes** the
1410/// `objective` wire by writing the `axes` input wires on the phase kernel.
1411#[derive(Debug, Clone, Serialize, Deserialize)]
1412pub struct OptimizeBlock {
1413 /// Registered optimizer name (`cmaes`, `nelder_mead`, … — see
1414 /// `nmbrs describe optimizers`). Defaults to `sweep` (the identity: evaluate
1415 /// every coordinate and report the best), so a plain "find the best by
1416 /// sweeping" search omits this field; set an adaptive method to search a
1417 /// large or continuous space without enumerating it.
1418 #[serde(default = "default_optimize_method")]
1419 pub method: String,
1420 /// The objective the optimizer **maximizes** (SRD-86 §10). Two forms:
1421 /// a **bare wire reference** — a single identifier naming a phase-kernel
1422 /// output (a `bindings:` entry), read directly; or an **inline polydat
1423 /// expression** (anything with operators / calls, e.g.
1424 /// `objective: "0 - metricsql_scalar(\"sum(rate(errors_total[3s]))\")"`),
1425 /// which is lowered to a synthesized `__objective` binding on the phase
1426 /// kernel (`scope::objective_wire`) so no separate `bindings:` entry is
1427 /// needed. An objective reading a windowed/live metric settles per setting;
1428 /// a deterministic one takes the one-shot read.
1429 pub objective: String,
1430 /// Search axes to actuate as **live controls** — servoed (retargeted without
1431 /// restarting the phase) rather than stepped through by re-running the phase
1432 /// (SRD-86 §4). Every axis is a coordinate (step-through / re-run) by default;
1433 /// naming one here opts it into servoing. Accepts a single name (`servo:
1434 /// concurrency`) or a list (`servo: [concurrency, rate]`). A servoed var
1435 /// resolves to a control either directly (its name IS a control — `servo:
1436 /// concurrency` / `servo: rate`) or indirectly (it feeds one via a `{var}`
1437 /// bind — `concurrency: "{conc}"`, then `servo: conc`). It is validated: it
1438 /// must resolve to a control AND the objective must be a windowed metric the
1439 /// servo can settle — else a clear error, never a silent downgrade.
1440 #[serde(default, deserialize_with = "de_string_or_seq")]
1441 pub servo: Vec<String>,
1442 #[serde(default = "default_optimize_max_evals")]
1443 pub max_evals: usize,
1444 #[serde(default = "default_optimize_seed")]
1445 pub seed: u64,
1446 /// Optimizer-specific knobs (e.g. `{ lambda: 8 }`).
1447 #[serde(default)]
1448 pub params: HashMap<String, f64>,
1449}
1450
1451/// Deserialize a single string OR a sequence of strings into a `Vec<String>` —
1452/// lets `servo: conc` and `servo: [conc, rate]` both parse.
1453fn de_string_or_seq<'de, D>(d: D) -> Result<Vec<String>, D::Error>
1454where
1455 D: serde::Deserializer<'de>,
1456{
1457 #[derive(Deserialize)]
1458 #[serde(untagged)]
1459 enum OneOrMany {
1460 One(String),
1461 Many(Vec<String>),
1462 }
1463 Ok(match OneOrMany::deserialize(d)? {
1464 OneOrMany::One(s) => vec![s],
1465 OneOrMany::Many(v) => v,
1466 })
1467}
1468
1469fn default_optimize_method() -> String {
1470 "sweep".to_string()
1471}
1472fn default_optimize_max_evals() -> usize {
1473 100
1474}
1475fn default_optimize_seed() -> u64 {
1476 1
1477}
1478
1479/// Phase-level `poll:` block (SRD-75). When set on a
1480/// `WorkloadPhase`, the runner wraps the phase's cycle
1481/// execution in a wall-clock loop that re-runs all ops
1482/// per iteration until `until` (a Polydat boolean expression
1483/// over captures) returns `true` or `timeout_ms` elapses.
1484///
1485/// Differs from the per-op `PollingDispenser` (SRD-32):
1486/// per-op poll wraps a SINGLE op with row-count /
1487/// json-path emptiness termination; phase-poll wraps
1488/// MULTIPLE ops with predicate-over-captures termination.
1489/// They coexist; per-op poll is the right tool when a
1490/// single op's response is sufficient to signal
1491/// completion.
1492#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1493pub struct PhasePollSpec {
1494 /// Polydat boolean expression evaluated against the phase
1495 /// scope kernel after each iteration. Compiles into
1496 /// the phase scope as `__poll_until := <until>`;
1497 /// dynamic (re-evaluates per pull) per SRD-11's "two
1498 /// evaluation lifecycles" rule. Required.
1499 pub until: String,
1500 /// Sleep between iterations, milliseconds. A number or a
1501 /// `{param}` / iter-var reference resolved at the phase
1502 /// gather (unresolvable ⇒ the phase fails up front). Default
1503 /// `1000` (one second).
1504 #[serde(default)]
1505 pub interval_ms: Option<String>,
1506 /// Overall wall-clock cap, milliseconds. Same
1507 /// number-or-reference contract as `interval_ms`. The loop
1508 /// returns a `poll_timeout` error if exceeded. Default
1509 /// `300000` (5 minutes).
1510 #[serde(default)]
1511 pub timeout_ms: Option<String>,
1512 /// Consecutive retryable inner-op errors tolerated
1513 /// before propagation. Same number-or-reference contract
1514 /// as `interval_ms`. `0` (default) = strict: any
1515 /// retryable error fails the phase immediately.
1516 /// Mirrors per-op `PollingDispenser` semantics.
1517 #[serde(default)]
1518 pub max_error_retries: Option<String>,
1519 /// Named metric (gauge) written via `ctx.wires.write`
1520 /// when the loop terminates successfully. Value =
1521 /// elapsed wall-clock; unit decoded from the
1522 /// trailing suffix (`_s` / `_ms` / `_ns` / …) per
1523 /// the existing `duration_value_for_metric_name`
1524 /// convention. Same contract as per-op poll's
1525 /// `metric_name`. Default `None` (no metric).
1526 #[serde(default, skip_serializing_if = "Option::is_none")]
1527 pub metric_name: Option<String>,
1528 /// What to do when the wall-clock `timeout_ms`
1529 /// expires without satisfying `until`. SRD-75
1530 /// §"Workload-load validation" — the workload-author
1531 /// declares whether a stuck synchronizer is a
1532 /// recoverable phase-error or a workload-invalidating
1533 /// event.
1534 ///
1535 /// - `error` (default) — phase fails; the outer
1536 /// scenario's error-routing policy decides whether
1537 /// to continue to sibling phases. Suitable when a
1538 /// single cell's failed synchronization doesn't
1539 /// invalidate the rest of the sweep (rare).
1540 /// - `abort` — calls `session_signals::request_stop()`
1541 /// in addition to setting the phase's stop_flag.
1542 /// The scenario walker observes the global stop and
1543 /// terminates the whole run. Use when the
1544 /// predicate's satisfaction is a precondition for
1545 /// any downstream phase being meaningful — e.g.
1546 /// ensure_compacted in the CQL sweep: if the table
1547 /// never reaches `sstables == 1`, every subsequent
1548 /// query phase runs against an un-compacted table
1549 /// and produces meaningless results.
1550 #[serde(default, skip_serializing_if = "Option::is_none")]
1551 pub on_timeout: Option<String>,
1552 /// SRD-75 (C5) — strict-gate selectors. Each entry is a
1553 /// `metric()`-style selector (`"family, key=value, …"`) that MUST
1554 /// resolve to a registered instrument within the gate's grace
1555 /// window (the first poll interval); an unresolved selector is a
1556 /// hard `poll_require` error failing the phase. This is the
1557 /// runtime guard for coordination gates whose `until` reads
1558 /// another phase's live metrics — an unregistered family reads
1559 /// 0.0 silently, so a typo'd selector otherwise passes the gate
1560 /// instantly or hangs it to timeout. Deliberately poll-only:
1561 /// `stop_when`'s lenient reads stay as SRD-83 sanctions them
1562 /// ("family not yet present" is a legitimate not-yet state for a
1563 /// stop predicate; for a gate it is a bug).
1564 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1565 pub require: Vec<String>,
1566}
1567
1568/// Per-phase checkpoint declaration. Three legal forms in YAML:
1569///
1570/// - `checkpoint: idempotent` — short form, equivalent to
1571/// `Checkpoint { idempotent: true, hashed: true, verify: None }`.
1572/// - `checkpoint: none` (or `false`, or `no`) — explicitly not
1573/// skip-eligible. Equivalent to no declaration; the phase
1574/// always re-runs on resume.
1575/// - `checkpoint: { idempotent: true, hashed: true, verify: ... }`
1576/// — full mapping form with sub-properties.
1577///
1578/// See SRD-44 §"Forms" and §"Sub-properties" for the full
1579/// contract. The `Default` is "skip-eligible with hashing on,
1580/// no verify" — what the short form `idempotent` produces.
1581#[derive(Debug, Clone, Serialize, PartialEq)]
1582pub struct Checkpoint {
1583 /// Marks this phase as skip-eligible on resume. `false`
1584 /// here is equivalent to `checkpoint: none` and means the
1585 /// phase always re-runs.
1586 pub idempotent: bool,
1587 /// When `true` (the default for any set checkpoint
1588 /// declaration), the resume planner additionally verifies
1589 /// that the freshly-pre-mapped phase's compiled program
1590 /// hash matches the saved one before honouring the saved
1591 /// status. `false` is the operator opt-out — "trust
1592 /// structural identity (yaml_path + coords) alone".
1593 pub hashed: bool,
1594 /// Optional verify op-template body. When present, the
1595 /// resume planner runs this op against the live system
1596 /// before classifying the phase as Skip; verify failure
1597 /// reclassifies to re-run with wholesale purge.
1598 /// Currently typed as a generic YAML value — the runtime
1599 /// re-parses it through the op-template grammar so the
1600 /// existing pipeline (SRD-32 wrappers, SRD-03 status-
1601 /// determination invariants) governs the verify
1602 /// execution.
1603 pub verify: Option<serde_json::Value>,
1604}
1605
1606impl Default for Checkpoint {
1607 fn default() -> Self {
1608 Self {
1609 idempotent: true,
1610 hashed: true,
1611 verify: None,
1612 }
1613 }
1614}
1615
1616impl<'de> serde::Deserialize<'de> for Checkpoint {
1617 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1618 where
1619 D: serde::Deserializer<'de>,
1620 {
1621 // The YAML accepts a short form (`idempotent` / `none`)
1622 // or a mapping with sub-properties — one spelling per
1623 // meaning; a bool or bare null is an error naming them. Serde's
1624 // visitor pattern lets us handle each input shape
1625 // directly without going through a typed-value
1626 // intermediate, which means this works equally well
1627 // for the YAML parser path and the JSON-staged path
1628 // (parse.rs walks `serde_json::Map` for phases).
1629 struct CheckpointVisitor;
1630 impl<'de> serde::de::Visitor<'de> for CheckpointVisitor {
1631 type Value = Checkpoint;
1632
1633 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1634 f.write_str("checkpoint declaration: 'idempotent', 'none', or a mapping with sub-properties")
1635 }
1636
1637 fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Checkpoint, E> {
1638 match s {
1639 "idempotent" => Ok(Checkpoint::default()),
1640 "none" => Ok(Checkpoint {
1641 idempotent: false,
1642 hashed: true,
1643 verify: None,
1644 }),
1645 "true" | "false" => Err(E::custom(format!(
1646 "checkpoint: {s} is not a checkpoint form; \
1647 write `checkpoint: {}`",
1648 if s == "true" { "idempotent" } else { "none" }
1649 ))),
1650 other => Err(E::custom(format!(
1651 "checkpoint: unknown short form '{other}'; \
1652 expected 'idempotent', 'none', or a mapping"
1653 ))),
1654 }
1655 }
1656
1657 fn visit_string<E: serde::de::Error>(self, s: String) -> Result<Checkpoint, E> {
1658 self.visit_str(&s)
1659 }
1660
1661 fn visit_bool<E: serde::de::Error>(self, b: bool) -> Result<Checkpoint, E> {
1662 self.visit_str(if b { "true" } else { "false" })
1663 }
1664
1665 fn visit_unit<E: serde::de::Error>(self) -> Result<Checkpoint, E> {
1666 Err(E::custom(
1667 "checkpoint: empty value; write `checkpoint: idempotent` \
1668 or `checkpoint: none`",
1669 ))
1670 }
1671
1672 fn visit_map<M>(self, mut map: M) -> Result<Checkpoint, M::Error>
1673 where
1674 M: serde::de::MapAccess<'de>,
1675 {
1676 let mut idempotent = true;
1677 let mut hashed = true;
1678 let mut verify: Option<serde_json::Value> = None;
1679 while let Some(key) = map.next_key::<String>()? {
1680 match key.as_str() {
1681 "idempotent" => idempotent = map.next_value::<bool>()?,
1682 "hashed" => hashed = map.next_value::<bool>()?,
1683 "verify" => verify = Some(map.next_value::<serde_json::Value>()?),
1684 other => {
1685 return Err(serde::de::Error::custom(format!(
1686 "checkpoint: unknown key '{other}'; \
1687 expected 'idempotent', 'hashed', or 'verify'"
1688 )));
1689 }
1690 }
1691 }
1692 Ok(Checkpoint {
1693 idempotent,
1694 hashed,
1695 verify,
1696 })
1697 }
1698 }
1699 deserializer.deserialize_any(CheckpointVisitor)
1700 }
1701}
1702
1703/// A node in a scenario execution tree.
1704///
1705/// Scenarios are trees of phases and control flow constructs.
1706/// Nesting is supported to arbitrary depth. All nodes are
1707/// evaluated dynamically at runtime — no pre-flattening.
1708///
1709/// `cycle` is immutable — loop constructs declare their own
1710/// counter variables for iteration indices.
1711///
1712/// All iteration shapes (`for_each` single-clause,
1713/// `for_combinations`, `for_each_union`) collapse into one
1714/// `Comprehension` variant carrying the canonical
1715/// [`polydat::iteration::comprehension::Comprehension`] AST —
1716/// the operator-tree form of the algebra layer. The
1717/// structural variant (`Cartesian` / `Union` / `Clause` /
1718/// `Zip`) is the discriminator; `Filter` and `Order` wrap
1719/// the body when the workload declares `where` / `order`.
1720/// See SRD-18b §"Iteration as a First-Class Concept" and
1721/// `polydat/docs/design/comprehension_cutover_contact_surfaces.md`.
1722#[derive(Debug, Clone, Serialize, Deserialize)]
1723pub enum ScenarioNode {
1724 /// A single phase to execute.
1725 Phase(String),
1726 /// Iteration node — single-clause for_each, multi-clause
1727 /// for_combinations, or for_each_union all map here. The
1728 /// `Comprehension` AST captures the iteration shape; the
1729 /// runtime executes the cross-product of clauses for the
1730 /// Cartesian mode and the concatenation of sub-spaces'
1731 /// products for Union mode.
1732 ///
1733 /// YAML forms (all normalize to this variant):
1734 /// ```yaml
1735 /// # Single clause
1736 /// - for_each: "k in 10,100"
1737 ///
1738 /// # Multi-clause cross product
1739 /// - for_each: "profile in profiles, k in {k_values}"
1740 ///
1741 /// # Multi-clause cross product (map form)
1742 /// - for_combinations:
1743 /// profile: "matching_profiles('{dataset}', '{prefix}')"
1744 /// k: "{k_values}"
1745 ///
1746 /// # Union of sub-spaces
1747 /// - for_each:
1748 /// - "k in 10, limit in 10,20,30"
1749 /// - "k in 100, limit in 100,200,300"
1750 /// ```
1751 Comprehension {
1752 comprehension: polydat::iteration::comprehension::Comprehension,
1753 children: Vec<ScenarioNode>,
1754 /// SRD-101 — optional `continue_if` pre-entry gate bounding this
1755 /// sweep: evaluated per iteration before the body; a false predicate
1756 /// halts the sweep at its `each` scope, gracefully.
1757 #[serde(default, skip_serializing_if = "Option::is_none")]
1758 continue_if: Option<ContinueIfSpec>,
1759 /// SRD-109 — table-row anchor: `anchor: <view>` declares one
1760 /// report-table row per iteration of this sweep, in the view
1761 /// of that name. Views sharing a name must share coordinate
1762 /// label sets. Key metrics designated on phases beneath this
1763 /// node attach to its rows.
1764 #[serde(default, skip_serializing_if = "Option::is_none")]
1765 anchor: Option<String>,
1766 },
1767 /// Execute children while condition is true (test after).
1768 DoWhile {
1769 condition: String,
1770 counter: Option<String>,
1771 children: Vec<ScenarioNode>,
1772 },
1773 /// Execute children until condition becomes true (test after).
1774 DoUntil {
1775 condition: String,
1776 counter: Option<String>,
1777 children: Vec<ScenarioNode>,
1778 },
1779 /// Logical inclusion of another scenario by name.
1780 ///
1781 /// Wherever this node appears (top-level of a scenario, inside
1782 /// a `phases:` list under a `for_each` / `for_combinations` /
1783 /// `for_each_union`, etc.), it expands to the children of the
1784 /// named scenario at execution time. The wrapper is preserved
1785 /// (not flattened) so the scope tree retains the include
1786 /// hierarchy and the renderer can show the operator which
1787 /// scenario each group of phases came from.
1788 ///
1789 /// Resolution happens once after parsing
1790 /// (see `crate::parse::resolve_scenario_includes`); cycles
1791 /// (`A` includes `B` includes `A`) are rejected with a clear
1792 /// error naming the cycle path.
1793 ///
1794 /// YAML form:
1795 /// ```yaml
1796 /// scenarios:
1797 /// smoke:
1798 /// - schema
1799 /// - rampup
1800 /// bench:
1801 /// - scenario: smoke
1802 /// - for_each: "k in 10,100"
1803 /// phases:
1804 /// - scenario: smoke
1805 /// - search
1806 /// ```
1807 IncludedScenario {
1808 name: String,
1809 children: Vec<ScenarioNode>,
1810 },
1811 /// Scenario-tree-level Polydat bindings block — the canonical way
1812 /// to introduce a scope-local layer of bound names anywhere
1813 /// in the scenario tree.
1814 ///
1815 /// `source` is Polydat matter text exactly as a phase-level
1816 /// `bindings:` block would contain. Anything the Polydat grammar
1817 /// accepts is valid: `const NAME := <literal>`, derived
1818 /// bindings (`scaled := mul(workload_limit, 2)`), shared
1819 /// cells, init bindings, etc. Workload-param `{name}` and
1820 /// string-interpolation references resolve through the
1821 /// scope chain at kernel build time — no separate
1822 /// preprocessing pass.
1823 ///
1824 /// `Bindings` is also the canonical lowered form of `set:`.
1825 /// The parser recognizes `set: { name: value, ... }` as
1826 /// syntactic sugar and emits a `Bindings` node whose
1827 /// `source` is `final <name> := <polydat-literal>\n` (one line
1828 /// per pair, declaration order preserved). So
1829 ///
1830 /// ```yaml
1831 /// - set: { mode: verbose }
1832 /// phases:
1833 /// - announce
1834 /// ```
1835 ///
1836 /// is semantically identical to
1837 ///
1838 /// ```yaml
1839 /// - bindings: |
1840 /// const mode := "verbose"
1841 /// phases:
1842 /// - announce
1843 /// ```
1844 ///
1845 /// Both produce one `Bindings` node. Authors keep the
1846 /// short `set:` form for the common override case; the
1847 /// long form unlocks the full Polydat grammar (derived
1848 /// bindings, expressions referencing other in-scope
1849 /// names, etc.) without any new variant.
1850 ///
1851 /// Lexical-shadow semantics are uniform with phase-level
1852 /// `bindings:`: a `const NAME := <value>` shadows any
1853 /// upstream binding for `NAME` over this node's `children`
1854 /// subtree. The shadow is enforced via the local-final
1855 /// transit-suppression rule in `materialize_wiring_from_outer`
1856 /// — the same mechanism every other scope uses.
1857 ///
1858 /// Composition example (two siblings, each defining its
1859 /// own value for the same name; the included subtree is
1860 /// physically cloned per include site so encapsulation is
1861 /// per-instance):
1862 ///
1863 /// ```yaml
1864 /// scenarios:
1865 /// fanout:
1866 /// - set: { mode: verbose }
1867 /// phases:
1868 /// - scenario: load_test
1869 /// - set: { mode: quiet }
1870 /// phases:
1871 /// - scenario: load_test
1872 /// ```
1873 Bindings {
1874 source: String,
1875 children: Vec<ScenarioNode>,
1876 },
1877}
1878
1879/// Legacy alias.
1880pub type ScenarioStep = ScenarioNode;
1881
1882/// How bindings are defined for an op.
1883///
1884/// Two modes:
1885/// - **Map**: Legacy nosqlbench-style `name: "FuncA(); FuncB()"` chains.
1886/// Each binding is independent; inheritance merges at key level.
1887/// - **PolydatSource**: Native Polydat grammar as a multiline string. The entire
1888/// binding block is a single Polydat program with coordinates, named outputs,
1889/// and full DAG wiring. Replaces (not merges with) any inherited bindings.
1890#[derive(Debug, Clone, Serialize, Deserialize)]
1891#[serde(untagged)]
1892pub enum BindingsDef {
1893 /// Legacy nosqlbench-style: name → expression chain.
1894 Map(HashMap<String, String>),
1895 /// Native Polydat grammar source text.
1896 PolydatSource(String),
1897}
1898
1899impl Default for BindingsDef {
1900 fn default() -> Self {
1901 BindingsDef::Map(HashMap::new())
1902 }
1903}
1904
1905impl BindingsDef {
1906 /// Returns true if there are no bindings defined.
1907 pub fn is_empty(&self) -> bool {
1908 match self {
1909 BindingsDef::Map(m) => m.is_empty(),
1910 BindingsDef::PolydatSource(s) => s.trim().is_empty(),
1911 }
1912 }
1913
1914 /// Get the map view (for legacy code). Returns empty map for PolydatSource.
1915 pub fn as_map(&self) -> &HashMap<String, String> {
1916 static EMPTY: std::sync::LazyLock<HashMap<String, String>> =
1917 std::sync::LazyLock::new(HashMap::new);
1918 match self {
1919 BindingsDef::Map(m) => m,
1920 BindingsDef::PolydatSource(_) => &EMPTY,
1921 }
1922 }
1923
1924 /// Insert a key-value pair (legacy map mode). Converts PolydatSource to Map.
1925 pub fn insert(&mut self, key: String, value: String) {
1926 match self {
1927 BindingsDef::Map(m) => {
1928 m.insert(key, value);
1929 }
1930 _ => {
1931 let mut m = HashMap::new();
1932 m.insert(key, value);
1933 *self = BindingsDef::Map(m);
1934 }
1935 }
1936 }
1937}
1938
1939/// SRD-108 Part B — the typed interface an abstract op slot
1940/// declares: wires the blueprint scope guarantees (`needs`),
1941/// wires the bound implementation must deliver via captures
1942/// (`yields`), and wires it must deliver by projecting the
1943/// result body via `result:` bindings (`results`, SRD-109 Part
1944/// 3), each `name -> polydat type`. A workload writes the type as
1945/// its polydat keyword (`u64`, `f64`, `str`, `vec_f32`, `vec_i64`,
1946/// …); the parser resolves it through
1947/// [`crate::port_types::resolve_type_keyword`], and the maps
1948/// serialize each type back as that keyword. BTreeMaps so the
1949/// SRD-107 config digest serializes stably.
1950#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1951pub struct OpInterface {
1952 #[serde(
1953 default,
1954 skip_serializing_if = "std::collections::BTreeMap::is_empty",
1955 with = "crate::port_types::keyword_map"
1956 )]
1957 pub needs: std::collections::BTreeMap<String, polydat::ast::PortType>,
1958 #[serde(
1959 default,
1960 skip_serializing_if = "std::collections::BTreeMap::is_empty",
1961 with = "crate::port_types::keyword_map"
1962 )]
1963 pub yields: std::collections::BTreeMap<String, polydat::ast::PortType>,
1964 #[serde(
1965 default,
1966 skip_serializing_if = "std::collections::BTreeMap::is_empty",
1967 with = "crate::port_types::keyword_map"
1968 )]
1969 pub results: std::collections::BTreeMap<String, polydat::ast::PortType>,
1970}
1971
1972/// A normalized op template — the canonical form.
1973#[derive(Debug, Clone, Serialize, Deserialize)]
1974pub struct ParsedOp {
1975 pub name: String,
1976 #[serde(default, skip_serializing_if = "Option::is_none")]
1977 pub description: Option<String>,
1978 /// The operation payload: field name → value.
1979 /// The statement is always under `"stmt"` after normalization.
1980 /// The original field name that carried the statement (e.g., `"raw"`,
1981 /// `"simple"`, `"prepared"`, `"stmt"`) is preserved in `stmt_type`
1982 /// for adapters that dispatch on execution mode.
1983 pub op: HashMap<String, serde_json::Value>,
1984 /// Binding definitions: either a name→expression map (legacy) or
1985 /// a Polydat grammar source string (native).
1986 #[serde(default, skip_serializing_if = "BindingsDef::is_empty")]
1987 pub bindings: BindingsDef,
1988 /// Configuration parameters.
1989 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
1990 pub params: HashMap<String, serde_json::Value>,
1991 /// Tags for filtering and metadata.
1992 #[serde(default)]
1993 pub tags: HashMap<String, String>,
1994 /// Optional condition expression (from YAML `if:` field).
1995 /// Evaluated per cycle before the op executes. If the result
1996 /// is falsy (false, 0, empty string, None), the op is skipped.
1997 #[serde(default, skip_serializing_if = "Option::is_none")]
1998 pub condition: Option<String>,
1999 /// Optional delay specification (from YAML `delay:` field).
2000 /// Two surface forms:
2001 /// - Bare string: `delay: <name>` — a Polydat binding name
2002 /// producing the pre-op delay value (u64 = ns, f64 = ms).
2003 /// - Map: `delay: { before: <name>, after: <name> }` —
2004 /// independent pre-op and post-op delays; both subkeys
2005 /// are optional but at least one must be set.
2006 #[serde(default, skip_serializing_if = "Option::is_none")]
2007 pub delay: Option<DelaySpec>,
2008 /// SRD-40b synthetic-metric declarations. Each entry
2009 /// publishes one metric family per cycle, valued by a GK
2010 /// expression evaluated in the op's bound scope. Empty
2011 /// when absent. Map key is the metric name and the
2012 /// **default family name**; `MetricSpec::family` overrides
2013 /// it when set. See SRD-40b §1 for the schema, §2 for
2014 /// sugared forms (bare-string / list with wire-expression
2015 /// entries).
2016 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
2017 pub metrics: HashMap<String, MetricSpec>,
2018 /// Dimensional placement of the op's OWN measurements: dimension
2019 /// name → polydat expression, the grammar of [`MetricSpec::cell`].
2020 ///
2021 /// Each cycle's service time, relevancy scores and validation
2022 /// outcomes are recorded in the cell the expressions name for that
2023 /// cycle, beside the phase's totals (which are unchanged). Each
2024 /// dimension must be declared on the phase (`dimensions:`).
2025 ///
2026 /// Ordered for the reason `MetricSpec::cell` is: the canonical
2027 /// rendering of a coordinate keys its cell.
2028 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
2029 pub cell: std::collections::BTreeMap<String, String>,
2030 /// SRD-66 result-bindings. Vari-structured: string is
2031 /// Polydat source, list is a sequence of fragments, map is
2032 /// named-key short-forms with a composite-map output.
2033 /// `None` ⇒ no result wires; the result wrapper is a
2034 /// no-op for this op.
2035 #[serde(default, skip_serializing_if = "Option::is_none")]
2036 pub result: Option<ResultSpec>,
2037 /// Optional `traverse:` block — CUSTOMISES the always-installed result
2038 /// traversal layer; it does not select it. Like `result:`, absence means
2039 /// "default behaviour", not "no traversal".
2040 #[serde(default, skip_serializing_if = "Option::is_none")]
2041 pub traverse: Option<TraverseSpec>,
2042 /// SRD-32a Push 3 — per-op wrapper-composition override.
2043 /// When present, this op uses the named order instead of
2044 /// the workload-root or runtime-default tiebreaker order.
2045 /// Shadows the workload-root `wrappers:` block entirely
2046 /// (no merge).
2047 #[serde(default, skip_serializing_if = "Option::is_none")]
2048 pub wrappers: Option<WrappersConfig>,
2049 /// Capture-point specs extracted at parse time from any
2050 /// string-valued entry in `op`. Each spec names a column the
2051 /// result body carries and the wire it should be written to
2052 /// via `ctx.wires.write` at cycle time. The `slurp` flag
2053 /// selects between single-row (`[name]`) and all-rows
2054 /// (`[@name]`) extraction.
2055 ///
2056 /// The parser strips the bracket syntax from the source op
2057 /// fields after harvesting the spec, so adapters consume
2058 /// clean text (e.g. `SELECT [key] FROM ...` becomes
2059 /// `SELECT key FROM ...`). Downstream wrappers read this
2060 /// list directly — no re-parsing of the op's text fields.
2061 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2062 pub captures: Vec<crate::bindpoints::CapturePoint>,
2063 /// SRD-108 Part B — present when this op was declared as an
2064 /// ABSTRACT slot (`abstract:` body): the interface a bound
2065 /// implementation must satisfy. Retained on the bound op so
2066 /// pre-map synthesis can verify `yields` against the compiled
2067 /// op-template program.
2068 #[serde(default, skip_serializing_if = "Option::is_none")]
2069 pub abstract_interface: Option<OpInterface>,
2070 /// SRD-108 Part B — `true` once an implementation has been
2071 /// bound into this slot. An op with an interface but
2072 /// `interface_bound == false` at run initiation is a load
2073 /// error ("abstract op unbound").
2074 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2075 pub interface_bound: bool,
2076 /// Daemon-fiber declaration. When set to a non-`Disabled`
2077 /// value, dispatches of this op from the cycle-pool spawn
2078 /// onto a daemon fiber instead of running inline. Daemons
2079 /// stay in scope of the phase so their failures bubble up;
2080 /// the cycle-pool fiber continues immediately to the next
2081 /// op without awaiting.
2082 ///
2083 /// YAML forms accepted:
2084 /// - `daemon: false` / `daemon: 0` → not a daemon (cycle-pool op).
2085 /// - `daemon: true` / `daemon: 1` → daemon, max 1 concurrent
2086 /// fiber per phase activation.
2087 /// - `daemon: <N>` (N ≥ 1) → daemon, max N concurrent
2088 /// fibers per phase activation.
2089 ///
2090 /// The cap is enforced at spawn time: when the cycle-pool
2091 /// dispatches the op and the live-fiber count is already at
2092 /// N, the spawn errors and the phase fails with a clear
2093 /// stop_reason. There's no queuing — exceeding the cap is a
2094 /// workload-design error, not backpressure to absorb.
2095 ///
2096 /// Per-op-name dedup: daemons are tracked by op-template
2097 /// name. Subsequent dispatches of the same name silently
2098 /// succeed up to the cap; over the cap they fail loud.
2099 /// Natural daemon exit (Completed / Cancelled / Errored /
2100 /// TimedOut / Panicked) decrements the count, freeing a
2101 /// slot for the next dispatch.
2102 ///
2103 /// Use case: a long-running server call (e.g.
2104 /// `forceKeyspaceCompaction`) that the workload wants to
2105 /// fire while a sibling op concurrently observes progress.
2106 /// The daemon op stays in scope so its failures bubble up;
2107 /// the cycle-pool op runs alongside without serialisation.
2108 ///
2109 /// Parser invariants when `daemon` is `MaxFibers(_)`:
2110 /// - `cycles:` and `ratio:` on this op are rejected — the
2111 /// daemon's dispatch cadence is governed by the cycle-pool
2112 /// walks, not by cycles-per-second.
2113 /// - `if:` / `while:` apply as usual; a falsy guard skips
2114 /// the dispatch with no spawn.
2115 #[serde(default, skip_serializing_if = "DaemonSpec::is_disabled")]
2116 pub daemon: DaemonSpec,
2117 /// How long the phase waits for this daemon's in-flight
2118 /// future to drop after sending the stop signal. Past the
2119 /// window, the phase records a daemon-shutdown failure and
2120 /// fails. Per-op override of the activity-level default
2121 /// (5000 ms).
2122 ///
2123 /// Only meaningful when `daemon` is `MaxFibers(_)`.
2124 #[serde(default, skip_serializing_if = "Option::is_none")]
2125 pub daemon_cancel_grace_ms: Option<u64>,
2126 /// Polydat boolean expression evaluated on the daemon's fiber
2127 /// inside the wrapper stack. When set, the daemon body runs
2128 /// a loop: while the condition is truthy, dispatch the
2129 /// inner op; when falsy or stop-signalled, exit.
2130 ///
2131 /// `while:` composes inside `if:` (which gates whether the
2132 /// loop starts at all) and outside the per-op-rate
2133 /// throttling (which paces iterations).
2134 ///
2135 /// Parser invariants:
2136 /// - `while:` on a non-daemon op is currently allowed but
2137 /// blocks the cycle-pool fiber until the loop exits. The
2138 /// common use case is daemon + while.
2139 #[serde(default, skip_serializing_if = "Option::is_none")]
2140 pub while_cond: Option<String>,
2141 /// Per-op rate spec governing the iteration cadence of the
2142 /// while-loop (or per-cycle dispatch for non-loop ops).
2143 /// Format: `"<N>"` (N/s, bare integer), `"<N>/s"`,
2144 /// `"<N>/m"`, `"<N>/h"`. Each op with `rate:` gets its own
2145 /// `RateLimiter` at phase init — INDEPENDENT of the
2146 /// activity-level `rate:` and of other ops' rate limiters.
2147 ///
2148 /// `rate: 0` is "unlimited" (no throttling).
2149 #[serde(default, skip_serializing_if = "Option::is_none")]
2150 pub rate: Option<String>,
2151}
2152
2153/// Daemon-fiber capacity declaration. The on-disk surface
2154/// accepts multiple YAML scalar shapes (bool / int / string)
2155/// that all map into this two-variant enum.
2156///
2157/// `Disabled` is the default — the op runs on the cycle-pool
2158/// fiber inline like everything else. `MaxFibers(N)` opts in
2159/// to daemon-fiber dispatch with a per-op-name cap of N.
2160#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2161pub enum DaemonSpec {
2162 #[default]
2163 Disabled,
2164 MaxFibers(u32),
2165}
2166
2167impl DaemonSpec {
2168 pub fn is_disabled(&self) -> bool {
2169 matches!(self, DaemonSpec::Disabled)
2170 }
2171 pub fn max_fibers(&self) -> Option<u32> {
2172 match self {
2173 DaemonSpec::Disabled => None,
2174 DaemonSpec::MaxFibers(n) => Some(*n),
2175 }
2176 }
2177}
2178
2179impl serde::Serialize for DaemonSpec {
2180 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2181 match self {
2182 DaemonSpec::Disabled => s.serialize_bool(false),
2183 DaemonSpec::MaxFibers(1) => s.serialize_bool(true),
2184 DaemonSpec::MaxFibers(n) => s.serialize_u32(*n),
2185 }
2186 }
2187}
2188
2189impl<'de> serde::Deserialize<'de> for DaemonSpec {
2190 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
2191 let v = serde_json::Value::deserialize(d)?;
2192 parse_daemon_spec_value(&v).map_err(serde::de::Error::custom)
2193 }
2194}
2195
2196/// Parse a YAML/JSON scalar into a `DaemonSpec`.
2197///
2198/// Accepted forms:
2199/// - `true` / `1` / `"true"` / `"on"` → `MaxFibers(1)`
2200/// - `false` / `0` / `"false"` / `"off"` → `Disabled`
2201/// - non-negative integer N ≥ 1 → `MaxFibers(N)`
2202/// - non-negative integer 0 → `Disabled`
2203///
2204/// Rejected forms (returns descriptive error):
2205/// - negative integers
2206/// - non-integer numbers (1.5, NaN, ...)
2207/// - strings other than the accepted set
2208/// - null, arrays, objects
2209///
2210/// Public so the unit + proptest layers can exercise it
2211/// directly without a full YAML round-trip.
2212pub fn parse_daemon_spec_value(v: &serde_json::Value) -> Result<DaemonSpec, String> {
2213 match v {
2214 serde_json::Value::Bool(true) => Ok(DaemonSpec::MaxFibers(1)),
2215 serde_json::Value::Bool(false) => Ok(DaemonSpec::Disabled),
2216 serde_json::Value::Number(n) => {
2217 if let Some(u) = n.as_u64() {
2218 if u == 0 {
2219 Ok(DaemonSpec::Disabled)
2220 } else if u <= u32::MAX as u64 {
2221 Ok(DaemonSpec::MaxFibers(u as u32))
2222 } else {
2223 Err(format!(
2224 "daemon: {u} exceeds u32::MAX — caps above {} \
2225 aren't supported (and don't make practical sense)",
2226 u32::MAX,
2227 ))
2228 }
2229 } else if n.as_i64().is_some_and(|i| i < 0) {
2230 Err(format!(
2231 "daemon: {n} — negative integers are invalid. \
2232 Use 0 or false to disable, or a positive \
2233 integer for the max-fibers cap.",
2234 ))
2235 } else {
2236 Err(format!(
2237 "daemon: {n} — non-integer numbers are invalid. \
2238 Use a boolean or a non-negative integer.",
2239 ))
2240 }
2241 }
2242 serde_json::Value::String(s) => match s.as_str() {
2243 "true" => Ok(DaemonSpec::MaxFibers(1)),
2244 "false" => Ok(DaemonSpec::Disabled),
2245 other => Err(format!(
2246 "daemon: \"{other}\" — not a daemon setting; \
2247 write true / false or a non-negative integer cap.",
2248 )),
2249 },
2250 serde_json::Value::Null => {
2251 Err("daemon: null is not a valid value. Use false to disable.".into())
2252 }
2253 other => Err(format!(
2254 "daemon: {other:?} — only boolean, integer, or string forms \
2255 are accepted.",
2256 )),
2257 }
2258}
2259
2260/// Per-op delay specification. Two surface forms on YAML:
2261/// - Bare string `delay: <name>` → `Before(<name>)`: a GK
2262/// binding name producing the pre-op delay value (u64 ns,
2263/// f64 ms).
2264/// - Map `delay: { before: <name>, after: <name> }` →
2265/// `BeforeAfter`: independent pre-op and post-op delays.
2266/// Both subkeys are optional; an empty map is a parse error.
2267#[derive(Debug, Clone, PartialEq, Eq)]
2268pub enum DelaySpec {
2269 /// Single pre-op delay. Equivalent to BeforeAfter { Some, None }
2270 /// at runtime; the discriminant exists so YAML round-trip
2271 /// preserves the author's chosen surface form.
2272 Before(String),
2273 BeforeAfter {
2274 before: Option<String>,
2275 after: Option<String>,
2276 },
2277}
2278
2279impl DelaySpec {
2280 /// Pre-op delay binding name, if any.
2281 pub fn before(&self) -> Option<&str> {
2282 match self {
2283 DelaySpec::Before(n) => Some(n.as_str()),
2284 DelaySpec::BeforeAfter { before, .. } => before.as_deref(),
2285 }
2286 }
2287 /// Post-op delay binding name, if any.
2288 pub fn after(&self) -> Option<&str> {
2289 match self {
2290 DelaySpec::Before(_) => None,
2291 DelaySpec::BeforeAfter { after, .. } => after.as_deref(),
2292 }
2293 }
2294 /// Every binding name this spec references. Used by scope
2295 /// synthesis to ensure the names land on the per-op kernel.
2296 pub fn names(&self) -> Vec<&str> {
2297 match self {
2298 DelaySpec::Before(n) => vec![n.as_str()],
2299 DelaySpec::BeforeAfter { before, after } => {
2300 let mut out = Vec::with_capacity(2);
2301 if let Some(b) = before.as_deref() {
2302 out.push(b);
2303 }
2304 if let Some(a) = after.as_deref() {
2305 out.push(a);
2306 }
2307 out
2308 }
2309 }
2310 }
2311}
2312
2313impl serde::Serialize for DelaySpec {
2314 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2315 use serde::ser::SerializeMap;
2316 match self {
2317 DelaySpec::Before(name) => s.serialize_str(name),
2318 DelaySpec::BeforeAfter { before, after } => {
2319 let mut m = s.serialize_map(None)?;
2320 if let Some(b) = before {
2321 m.serialize_entry("before", b)?;
2322 }
2323 if let Some(a) = after {
2324 m.serialize_entry("after", a)?;
2325 }
2326 m.end()
2327 }
2328 }
2329 }
2330}
2331
2332impl<'de> serde::Deserialize<'de> for DelaySpec {
2333 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
2334 let v = serde_json::Value::deserialize(d)?;
2335 parse_delay_spec_value(&v).map_err(serde::de::Error::custom)
2336 }
2337}
2338
2339/// Parse a YAML/JSON value into a `DelaySpec`.
2340///
2341/// Accepted:
2342/// - non-empty string → `Before(<string>)`
2343/// - object with `before` and/or `after` keys → `BeforeAfter`
2344///
2345/// Rejected (descriptive error):
2346/// - empty string
2347/// - empty object
2348/// - object with unknown keys
2349/// - object whose `before` / `after` values aren't strings
2350/// - null, arrays, numbers, booleans
2351///
2352/// Public for unit tests + smoke validation.
2353pub fn parse_delay_spec_value(v: &serde_json::Value) -> Result<DelaySpec, String> {
2354 match v {
2355 serde_json::Value::String(s) => {
2356 let trimmed = s.trim();
2357 if trimmed.is_empty() {
2358 Err("delay: empty string is not a valid binding name".into())
2359 } else {
2360 Ok(DelaySpec::Before(trimmed.to_string()))
2361 }
2362 }
2363 serde_json::Value::Object(map) => {
2364 let mut before: Option<String> = None;
2365 let mut after: Option<String> = None;
2366 for (k, v) in map {
2367 match k.as_str() {
2368 "before" => {
2369 before = match v {
2370 serde_json::Value::String(s) => {
2371 let t = s.trim();
2372 if t.is_empty() {
2373 return Err(
2374 "delay.before: empty string is not a valid binding name"
2375 .into(),
2376 );
2377 }
2378 Some(t.to_string())
2379 }
2380 other => {
2381 return Err(format!(
2382 "delay.before: expected string, got {other:?}",
2383 ));
2384 }
2385 };
2386 }
2387 "after" => {
2388 after = match v {
2389 serde_json::Value::String(s) => {
2390 let t = s.trim();
2391 if t.is_empty() {
2392 return Err(
2393 "delay.after: empty string is not a valid binding name"
2394 .into(),
2395 );
2396 }
2397 Some(t.to_string())
2398 }
2399 other => {
2400 return Err(
2401 format!("delay.after: expected string, got {other:?}",),
2402 );
2403 }
2404 };
2405 }
2406 other => {
2407 return Err(format!(
2408 "delay: unknown key `{other}` — accepted: `before`, `after`",
2409 ));
2410 }
2411 }
2412 }
2413 if before.is_none() && after.is_none() {
2414 Err("delay: map form must set at least one of `before` / `after`".into())
2415 } else {
2416 Ok(DelaySpec::BeforeAfter { before, after })
2417 }
2418 }
2419 serde_json::Value::Null => {
2420 Err("delay: null is not a valid value. Omit the field instead.".into())
2421 }
2422 other => Err(format!(
2423 "delay: {other:?} — accepted forms are a binding-name string or \
2424 a map `{{ before: <name>, after: <name> }}`",
2425 )),
2426 }
2427}
2428
2429#[cfg(test)]
2430mod delay_spec_tests {
2431 use super::*;
2432 use serde_json::json;
2433
2434 #[test]
2435 fn parse_bare_string_is_before() {
2436 let spec = parse_delay_spec_value(&json!("ticks")).unwrap();
2437 assert_eq!(spec, DelaySpec::Before("ticks".into()));
2438 }
2439
2440 #[test]
2441 fn parse_trimmed_string() {
2442 let spec = parse_delay_spec_value(&json!(" ticks ")).unwrap();
2443 assert_eq!(spec, DelaySpec::Before("ticks".into()));
2444 }
2445
2446 #[test]
2447 fn parse_map_with_both() {
2448 let spec = parse_delay_spec_value(&json!({
2449 "before": "pre", "after": "post"
2450 }))
2451 .unwrap();
2452 assert_eq!(
2453 spec,
2454 DelaySpec::BeforeAfter {
2455 before: Some("pre".into()),
2456 after: Some("post".into()),
2457 }
2458 );
2459 }
2460
2461 #[test]
2462 fn parse_map_before_only() {
2463 let spec = parse_delay_spec_value(&json!({ "before": "pre" })).unwrap();
2464 assert_eq!(
2465 spec,
2466 DelaySpec::BeforeAfter {
2467 before: Some("pre".into()),
2468 after: None,
2469 }
2470 );
2471 }
2472
2473 #[test]
2474 fn parse_map_after_only() {
2475 let spec = parse_delay_spec_value(&json!({ "after": "post" })).unwrap();
2476 assert_eq!(
2477 spec,
2478 DelaySpec::BeforeAfter {
2479 before: None,
2480 after: Some("post".into()),
2481 }
2482 );
2483 }
2484
2485 #[test]
2486 fn parse_rejects_empty_string() {
2487 assert!(parse_delay_spec_value(&json!("")).is_err());
2488 assert!(parse_delay_spec_value(&json!(" ")).is_err());
2489 }
2490
2491 #[test]
2492 fn parse_rejects_empty_map() {
2493 assert!(parse_delay_spec_value(&json!({})).is_err());
2494 }
2495
2496 #[test]
2497 fn parse_rejects_unknown_key() {
2498 let e = parse_delay_spec_value(&json!({
2499 "before": "pre", "during": "mid"
2500 }))
2501 .unwrap_err();
2502 assert!(e.contains("during"));
2503 }
2504
2505 #[test]
2506 fn parse_rejects_non_string_value() {
2507 assert!(parse_delay_spec_value(&json!({ "before": 5 })).is_err());
2508 assert!(parse_delay_spec_value(&json!({ "after": true })).is_err());
2509 assert!(parse_delay_spec_value(&json!({ "before": null })).is_err());
2510 }
2511
2512 #[test]
2513 fn parse_rejects_null_top_level() {
2514 assert!(parse_delay_spec_value(&json!(null)).is_err());
2515 }
2516
2517 #[test]
2518 fn parse_rejects_array() {
2519 assert!(parse_delay_spec_value(&json!(["pre"])).is_err());
2520 }
2521
2522 #[test]
2523 fn parse_rejects_number() {
2524 assert!(parse_delay_spec_value(&json!(1.5)).is_err());
2525 assert!(parse_delay_spec_value(&json!(100)).is_err());
2526 }
2527
2528 #[test]
2529 fn parse_rejects_empty_after_value() {
2530 assert!(parse_delay_spec_value(&json!({ "after": "" })).is_err());
2531 }
2532
2533 #[test]
2534 fn round_trip_before_serializes_as_string() {
2535 let spec = DelaySpec::Before("ticks".into());
2536 let v = serde_json::to_value(&spec).unwrap();
2537 assert_eq!(v, json!("ticks"));
2538 let parsed: DelaySpec = serde_json::from_value(v).unwrap();
2539 assert_eq!(parsed, spec);
2540 }
2541
2542 #[test]
2543 fn round_trip_map_serializes_as_object() {
2544 let spec = DelaySpec::BeforeAfter {
2545 before: Some("pre".into()),
2546 after: Some("post".into()),
2547 };
2548 let v = serde_json::to_value(&spec).unwrap();
2549 assert_eq!(v.get("before"), Some(&json!("pre")));
2550 assert_eq!(v.get("after"), Some(&json!("post")));
2551 let parsed: DelaySpec = serde_json::from_value(v).unwrap();
2552 assert_eq!(parsed, spec);
2553 }
2554
2555 #[test]
2556 fn names_returns_all_referenced() {
2557 assert_eq!(DelaySpec::Before("x".into()).names(), vec!["x"]);
2558 let spec = DelaySpec::BeforeAfter {
2559 before: Some("a".into()),
2560 after: Some("b".into()),
2561 };
2562 assert_eq!(spec.names(), vec!["a", "b"]);
2563 let only_before = DelaySpec::BeforeAfter {
2564 before: Some("a".into()),
2565 after: None,
2566 };
2567 assert_eq!(only_before.names(), vec!["a"]);
2568 }
2569
2570 #[test]
2571 fn accessors_return_correct_names() {
2572 let s = DelaySpec::Before("x".into());
2573 assert_eq!(s.before(), Some("x"));
2574 assert_eq!(s.after(), None);
2575 let s = DelaySpec::BeforeAfter {
2576 before: Some("a".into()),
2577 after: Some("b".into()),
2578 };
2579 assert_eq!(s.before(), Some("a"));
2580 assert_eq!(s.after(), Some("b"));
2581 }
2582}
2583
2584#[cfg(test)]
2585mod daemon_spec_tests {
2586 use super::*;
2587 use serde_json::json;
2588
2589 #[test]
2590 fn bool_true_is_max_1() {
2591 assert_eq!(
2592 parse_daemon_spec_value(&json!(true)).unwrap(),
2593 DaemonSpec::MaxFibers(1)
2594 );
2595 }
2596 #[test]
2597 fn bool_false_is_disabled() {
2598 assert_eq!(
2599 parse_daemon_spec_value(&json!(false)).unwrap(),
2600 DaemonSpec::Disabled
2601 );
2602 }
2603 #[test]
2604 fn int_0_is_disabled() {
2605 assert_eq!(
2606 parse_daemon_spec_value(&json!(0)).unwrap(),
2607 DaemonSpec::Disabled
2608 );
2609 }
2610 #[test]
2611 fn int_1_is_max_1() {
2612 assert_eq!(
2613 parse_daemon_spec_value(&json!(1)).unwrap(),
2614 DaemonSpec::MaxFibers(1)
2615 );
2616 }
2617 #[test]
2618 fn int_n_is_max_n() {
2619 assert_eq!(
2620 parse_daemon_spec_value(&json!(10)).unwrap(),
2621 DaemonSpec::MaxFibers(10)
2622 );
2623 }
2624 #[test]
2625 fn str_true_and_false_are_the_string_forms() {
2626 assert_eq!(
2627 parse_daemon_spec_value(&json!("true")).unwrap(),
2628 DaemonSpec::MaxFibers(1)
2629 );
2630 assert_eq!(
2631 parse_daemon_spec_value(&json!("false")).unwrap(),
2632 DaemonSpec::Disabled
2633 );
2634 for retired in ["on", "off", "ON", "TRUE"] {
2635 assert!(
2636 parse_daemon_spec_value(&json!(retired)).is_err(),
2637 "{retired} must not be read as a daemon setting"
2638 );
2639 }
2640 }
2641 #[test]
2642 fn negative_int_rejected() {
2643 assert!(parse_daemon_spec_value(&json!(-1)).is_err());
2644 assert!(parse_daemon_spec_value(&json!(-100)).is_err());
2645 }
2646 #[test]
2647 fn float_rejected() {
2648 assert!(parse_daemon_spec_value(&json!(1.5)).is_err());
2649 }
2650 #[test]
2651 fn unknown_string_rejected() {
2652 assert!(parse_daemon_spec_value(&json!("garbage")).is_err());
2653 assert!(parse_daemon_spec_value(&json!("yes")).is_err());
2654 }
2655 #[test]
2656 fn null_rejected() {
2657 assert!(parse_daemon_spec_value(&json!(null)).is_err());
2658 }
2659 #[test]
2660 fn array_object_rejected() {
2661 assert!(parse_daemon_spec_value(&json!([1, 2])).is_err());
2662 assert!(parse_daemon_spec_value(&json!({"max": 5})).is_err());
2663 }
2664 #[test]
2665 fn round_trip_disabled() {
2666 let s = serde_json::to_value(DaemonSpec::Disabled).unwrap();
2667 assert_eq!(parse_daemon_spec_value(&s).unwrap(), DaemonSpec::Disabled);
2668 }
2669 #[test]
2670 fn round_trip_max_1_serialises_as_bool() {
2671 let s = serde_json::to_value(DaemonSpec::MaxFibers(1)).unwrap();
2672 assert_eq!(s, json!(true));
2673 assert_eq!(
2674 parse_daemon_spec_value(&s).unwrap(),
2675 DaemonSpec::MaxFibers(1)
2676 );
2677 }
2678 #[test]
2679 fn round_trip_max_n_serialises_as_int() {
2680 let s = serde_json::to_value(DaemonSpec::MaxFibers(5)).unwrap();
2681 assert_eq!(s, json!(5));
2682 assert_eq!(
2683 parse_daemon_spec_value(&s).unwrap(),
2684 DaemonSpec::MaxFibers(5)
2685 );
2686 }
2687}
2688
2689/// `traverse:` — knobs on the result-traversal layer.
2690///
2691/// The layer itself is always installed (`result:` and `metrics:` declare it
2692/// as `requires_inner`, and the composition resolver enforces that at init),
2693/// so this block only tunes behaviour that is otherwise fixed.
2694#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2695pub struct TraverseSpec {
2696 /// Base JSON Pointer (RFC 6901) applied to the result body BEFORE any
2697 /// capture is resolved, re-rooting the document.
2698 ///
2699 /// Every capture otherwise repeats the same prefix — `/value/0/x`,
2700 /// `/value/0/y` — which is the shape envelope responses force
2701 /// (`{value, status, …}`).
2702 #[serde(default, skip_serializing_if = "Option::is_none")]
2703 pub path: Option<String>,
2704 /// What to do when a declared capture resolves to nothing.
2705 #[serde(default)]
2706 pub on_missing: OnMissing,
2707}
2708
2709/// Policy for a capture that resolved to nothing.
2710#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
2711#[serde(rename_all = "lowercase")]
2712pub enum OnMissing {
2713 /// Bind `None` and continue — the historical behaviour, and the default
2714 /// so existing workloads are unaffected.
2715 #[default]
2716 Ignore,
2717 /// Log it. For a capture that is legitimately sometimes absent but whose
2718 /// absence you still want to see.
2719 Warn,
2720 /// Fail the op. For a capture whose absence means the query or the schema
2721 /// changed under you — which otherwise reads identically to "measured,
2722 /// and it was absent".
2723 Error,
2724}
2725
2726/// SRD-40b §1 schema for one synthetic-metric declaration on
2727/// an op template.
2728#[derive(Debug, Clone, Serialize, Deserialize)]
2729pub struct MetricSpec {
2730 /// Required. A Polydat expression evaluated in the op's bound
2731 /// scope. A bare binding name is the canonical form when
2732 /// the formula belongs in a `bindings:` block; any GK
2733 /// expression that produces a numeric result is also
2734 /// valid. See SRD-40b §4.
2735 pub value: String,
2736 /// Optional override of the family name. Defaults to the
2737 /// map key on `ParsedOp.metrics`. SRD-40b §1.
2738 #[serde(default, skip_serializing_if = "Option::is_none")]
2739 pub family: Option<String>,
2740 /// Optional metric type. Defaults to `Gauge` per SRD-40b §1.
2741 #[serde(default, skip_serializing_if = "Option::is_none")]
2742 pub kind: Option<MetricKind>,
2743 /// Optional OpenMetrics unit suffix (`ms`, `bytes`, …).
2744 /// When set, lands in BOTH the family-name suffix and the
2745 /// `metric_family.unit` column per SRD-40a §4.3.
2746 #[serde(default, skip_serializing_if = "Option::is_none")]
2747 pub unit: Option<String>,
2748 /// Optional generation-time numeric sanitiser using
2749 /// Excel-style hash patterns (`#.##`, `0.000`, etc.).
2750 /// Translated at registration time into a round op that
2751 /// runs before the value is recorded on the instrument;
2752 /// storage holds the sanitised number. SRD-40b §1.
2753 #[serde(default, skip_serializing_if = "Option::is_none")]
2754 pub format: Option<String>,
2755 /// Optional dimensional placement: dimension name → a Polydat
2756 /// expression producing that dimension's value for this sample.
2757 ///
2758 /// A metric identity is its label set with the family name promoted
2759 /// into it, a closed 1:1 association. `cell:` therefore does not
2760 /// attach a label to a sample — it selects the dimensional CELL the
2761 /// sample belongs to, REFINING the identity its registration site
2762 /// already composes. One value per cell, one family per cell, and the
2763 /// existing duplicate-family check keeps working unchanged.
2764 ///
2765 /// `BTreeMap` so synthesis order is deterministic: the coordinate's
2766 /// rendering is what keys a cell, and a map that iterated differently
2767 /// between runs would key the same coordinate two ways.
2768 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
2769 pub cell: std::collections::BTreeMap<String, String>,
2770}
2771
2772/// A dimension a scope introduces: the label NAME whose values arrive from
2773/// data, declared once at the tier that owns it.
2774///
2775/// The name is a structural declaration; only the value varies per cell.
2776/// `Component::attach` enforces the same rule on the runtime tree — a label
2777/// name is owned by exactly one tier and inherited downward — so declaring
2778/// the name here is what lets that be checked against the program before a
2779/// cycle runs, rather than surfacing as an attach-time panic.
2780#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2781pub struct DimensionSpec {
2782 /// Value type. `str` today — label values are strings, and a
2783 /// dimension whose values came from a float would key cells on
2784 /// formatting rather than on identity.
2785 #[serde(default)]
2786 pub value_type: DimensionType,
2787}
2788
2789/// Declared value type of a [`DimensionSpec`].
2790#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
2791#[serde(rename_all = "lowercase")]
2792pub enum DimensionType {
2793 #[default]
2794 Str,
2795}
2796
2797/// Metric type discriminator. SRD-40b §1.
2798#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2799#[serde(rename_all = "lowercase")]
2800pub enum MetricKind {
2801 /// Current-state observation; per-cycle `set(value)`.
2802 /// Default per SRD-40b §1.
2803 Gauge,
2804 /// Distribution sample; per-cycle `record(value)`.
2805 Histogram,
2806 /// Monotonic running total; per-cycle `inc_by(value)`.
2807 Counter,
2808}
2809
2810impl Default for MetricKind {
2811 /// SRD-40b §1: gauge is the default — synthetic values are
2812 /// most often current-state observations.
2813 fn default() -> Self {
2814 MetricKind::Gauge
2815 }
2816}
2817
2818/// SRD-66 result-bindings declaration. Vari-structured to
2819/// match the three YAML shapes the user can write:
2820///
2821/// - **String**: a multi-line Polydat source block. Each
2822/// `<name> := <expr>` assignment declares one result wire.
2823/// - **List**: a sequence of nested `ResultSpec`s; each
2824/// element processes in order and contributes its
2825/// declarations.
2826/// - **Map**: named-key short-forms (`count`, `ok`,
2827/// path-expr, or any other string treated as a GK
2828/// expression). Map shape additionally produces a
2829/// composite-map wire (deferred — see Push 2 follow-ups).
2830///
2831/// SRD-40b §5.1's mapping form is preserved as the map
2832/// shape with two refinements: any non-built-in non-path
2833/// string is a Polydat expression (no `(`-detector magic), and
2834/// the composite-map output is added.
2835#[derive(Debug, Clone, Serialize, Deserialize)]
2836#[serde(untagged)]
2837pub enum ResultSpec {
2838 /// Polydat source block — one or more `<name> := <expr>`
2839 /// assignments separated by newlines. The pre-bound
2840 /// wires (`body`, `count`, `ok`, captures) are
2841 /// available; references resolve via the standard
2842 /// closure-binding rule (polydat module matter detects
2843 /// linkages).
2844 String(String),
2845 /// Sequence of fragments. Each element is itself a
2846 /// `ResultSpec` (string or map; nested lists are parsed
2847 /// but unconventional). Fragments concatenate into one
2848 /// result-bindings scope; key collisions across map-
2849 /// shape fragments are a hard error.
2850 List(Vec<ResultSpec>),
2851 /// Named-key short-forms. Each value is one of:
2852 /// `"count"`, `"ok"`, a path expression (no parens), or
2853 /// any other string treated as a Polydat expression. Map
2854 /// shape also produces a composite-map wire keyed by
2855 /// the YAML keys.
2856 Map(std::collections::BTreeMap<String, String>),
2857}
2858
2859/// Legacy alias for backwards compatibility during Push 2.
2860/// Drops once every consumer migrates to `ResultSpec`.
2861pub type ResultWireSpec = LegacyResultWireSpec;
2862
2863#[derive(Debug, Clone, Serialize, Deserialize)]
2864#[serde(untagged)]
2865pub enum LegacyResultWireSpec {
2866 String(String),
2867 Object {
2868 source: String,
2869 #[serde(default, skip_serializing_if = "Option::is_none")]
2870 default: Option<String>,
2871 },
2872}
2873
2874impl LegacyResultWireSpec {
2875 pub fn source(&self) -> &str {
2876 match self {
2877 LegacyResultWireSpec::String(s) => s,
2878 LegacyResultWireSpec::Object { source, .. } => source,
2879 }
2880 }
2881}
2882
2883impl ResultSpec {
2884 /// Walk the spec tree (handling list-shape recursion)
2885 /// and yield every (wire-name, source-expr) pair the
2886 /// spec ultimately declares.
2887 ///
2888 /// For map-shape entries, the source is whatever the
2889 /// user wrote (`count` / `ok` / path-expr / Polydat expr).
2890 /// For string-shape entries, the source is the entire
2891 /// Polydat block — the caller compiles it as a unit and
2892 /// extracts wire names from the LHS of each `:=`
2893 /// assignment.
2894 pub fn walk_fragments<F: FnMut(ResultFragment<'_>)>(&self, mut on: F) {
2895 self.walk_fragments_inner(&mut on);
2896 }
2897
2898 fn walk_fragments_inner<F: FnMut(ResultFragment<'_>)>(&self, on: &mut F) {
2899 match self {
2900 ResultSpec::String(s) => on(ResultFragment::Source(s)),
2901 ResultSpec::List(items) => {
2902 for item in items {
2903 item.walk_fragments_inner(on);
2904 }
2905 }
2906 ResultSpec::Map(entries) => {
2907 for (name, source) in entries {
2908 on(ResultFragment::Named { name, source });
2909 }
2910 }
2911 }
2912 }
2913
2914 /// True when the spec declares no wires. Used by the
2915 /// wrapper-trigger to skip wrapping when `result:` was
2916 /// explicitly empty.
2917 pub fn is_empty(&self) -> bool {
2918 match self {
2919 ResultSpec::String(s) => s.trim().is_empty(),
2920 ResultSpec::List(items) => items.iter().all(|i| i.is_empty()),
2921 ResultSpec::Map(entries) => entries.is_empty(),
2922 }
2923 }
2924}
2925
2926/// One step of `ResultSpec::walk_fragments`. Either a
2927/// string-shape source block (compile as a Polydat module) or a
2928/// map-shape `(name, source)` pair (compile as a single
2929/// `name := source` binding).
2930pub enum ResultFragment<'a> {
2931 Source(&'a str),
2932 Named { name: &'a str, source: &'a str },
2933}
2934
2935impl ParsedOp {
2936 /// Create a minimal ParsedOp with just a name and stmt.
2937 pub fn simple(name: &str, stmt: &str) -> Self {
2938 let mut op = HashMap::new();
2939 op.insert(
2940 "stmt".to_string(),
2941 serde_json::Value::String(stmt.to_string()),
2942 );
2943 Self {
2944 traverse: None,
2945 name: name.to_string(),
2946 description: None,
2947 op,
2948 bindings: BindingsDef::default(),
2949 params: HashMap::new(),
2950 tags: HashMap::new(),
2951 condition: None,
2952 delay: None,
2953 metrics: HashMap::new(),
2954 cell: std::collections::BTreeMap::new(),
2955 result: None,
2956 wrappers: None,
2957 captures: Vec::new(),
2958 abstract_interface: None,
2959 interface_bound: false,
2960 daemon: DaemonSpec::Disabled,
2961 daemon_cancel_grace_ms: None,
2962 while_cond: None,
2963 rate: None,
2964 }
2965 }
2966}