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-113 — one key-metric designation on an execution node:
1070/// `column: agg(family)`, where matchers in braces and, for a family
1071/// of the session sampler, a sample mode may follow the family
1072/// (`avg(sysmon_cgroup_cpu_cores{cgroup="node"}, within)`; SRD-118
1073/// §10.1). Designating key metrics both names the
1074/// node's measurables and attaches the node to the table row of its
1075/// nearest enclosing anchor (or the spine). `family` is empty for
1076/// the family-less `span()`.
1077#[derive(Debug, Clone, Serialize, Deserialize)]
1078pub struct KeyMetric {
1079 pub column: String,
1080 pub agg: KeyAgg,
1081 pub family: String,
1082 /// The matchers written in braces after the family, without the
1083 /// braces: they select among the family's series. Empty for none.
1084 #[serde(default)]
1085 pub matchers: String,
1086 /// The sample mode written after the family, for a family of the
1087 /// session sampler: which of its samples count toward the phase
1088 /// (SRD-118 §5.1). `None` for the default.
1089 #[serde(default)]
1090 pub samples: Option<String>,
1091}
1092
1093/// A workload phase: runs as a separate Activity with its own
1094/// cycle count, concurrency, rate limit, and op selection.
1095#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1096pub struct WorkloadPhase {
1097 /// Number of stanzas for this phase. Each stanza executes all
1098 /// ops in sequence once. String type to support Polydat constant
1099 /// references like `"{train_count, dimensions: Default::default(),}"`. Default 1 (one stanza).
1100 #[serde(default)]
1101 pub cycles: Option<String>,
1102 /// Concurrency (async fibers). String type to support Polydat constant
1103 /// or workload param references like `"{concurrency}"`. Default 1.
1104 #[serde(default)]
1105 pub concurrency: Option<String>,
1106 /// Rate limit (ops/sec). A number, or a `{param}` / iter-var
1107 /// reference resolved at the phase gather (the SRD-83
1108 /// `timeout:` discipline: a rate that cannot be resolved
1109 /// fails the phase up front — it never silently becomes
1110 /// "unrated"). Default unlimited.
1111 #[serde(default)]
1112 pub rate: Option<String>,
1113 /// SRD-82 Part 6 — daemon phase. When `true`, this phase runs
1114 /// CONCURRENTLY with its foreground sibling phases (off the
1115 /// scenario's foreground concurrency budget) and is stopped
1116 /// cooperatively when the scope's foreground phases complete (a
1117 /// background "daemon unit" at the phase shell). Its own scope gives
1118 /// it an independent cursor base. Pair with an open-extent cursor
1119 /// (e.g. `until_elapsed`) so it runs for the foreground's duration.
1120 #[serde(default)]
1121 pub daemon: bool,
1122 /// Adapter override for this phase.
1123 #[serde(default)]
1124 pub adapter: Option<String>,
1125 /// Error routing spec override.
1126 #[serde(default)]
1127 pub errors: Option<String>,
1128 /// Total-attempts budget for this phase's ops. `tries:` is the SIGIL for
1129 /// the conditional tries wrapper (SRD-82 Part 3b): when NO budget
1130 /// resolves anywhere in scope (op field, this phase field, the
1131 /// workload-root `tries` param, or an in-scope `tries` wire), the
1132 /// wrapper is not constructed and the op runs single-attempt. `1` = the
1133 /// same single-attempt behaviour, explicitly (shadows an inherited
1134 /// budget); `0` = ops FAIL WITHOUT EXECUTING; `N ≥ 2` = up to N total
1135 /// attempts on adapter-retryable errors (CQL timeouts/overloads).
1136 /// `None` = inherit.
1137 #[serde(default)]
1138 pub tries: Option<u32>,
1139 /// Retry-backoff overrides parsed from the map form of `tries:`
1140 /// (`tries: {count: N, backoff: {ratio, min, max}}`). `None` when the
1141 /// sugared numeric form was used (or `tries` absent) — the wrapper then
1142 /// falls back to the op's standalone `retry_backoff*` params or the
1143 /// built-in defaults (ratio 2.0, min 100ms, max 10s). See
1144 /// [`BackoffSpec`].
1145 #[serde(default)]
1146 pub tries_backoff: Option<BackoffSpec>,
1147 /// SRD-82/92 cross-level wrapper (scoping P0) — phase-execution pacing.
1148 /// `interval:` is the discriminator for a future `WrapperLevel::Phase`
1149 /// interval wrapper: re-run this phase, sleeping `interval` between runs.
1150 /// A raw duration string (e.g. `"5m"`), parsed at wrap time by the
1151 /// runtime. Declarative today — the phase-level cascade that consumes it
1152 /// is not built yet (see `docs/cross-level-wrapper-cascade-scope.md`).
1153 #[serde(default)]
1154 pub interval: Option<String>,
1155 /// Bound for [`interval`](Self::interval) — how many times to run the
1156 /// phase. `None` alongside `interval` = repeat until the session stops.
1157 #[serde(default)]
1158 pub repeat: Option<u64>,
1159 /// OPT-IN error-rate circuit breaker (e.g. `0.1` = fail this phase
1160 /// once >10% of its ops error, after a 50-op floor). Overrides a
1161 /// session-wide `error_rate_max=` param when one was set. There is
1162 /// NO built-in default (SRD-82 §"AggregateGuard retired as a
1163 /// default") — aggregate health belongs to visible `stop_when:`
1164 /// conditions; this field exists as an explicit shorthand only.
1165 #[serde(default)]
1166 pub error_rate_max: Option<f64>,
1167 /// SRD-83 governance timeout (GAP-12). A duration (`"2.5h"`, `"150ms"`,
1168 /// bare fractional seconds) or a `{param}` reference; on expiry the
1169 /// phase ends Interrupted+Failed with reason class `timeout` — the
1170 /// protocol OUT-OF-RANGE disposition: the system is disqualified at
1171 /// this tier, the partial result is not usable. Desugars at the
1172 /// phase gather into a synthesized, logged `elapsed_ms >` stop
1173 /// condition (the `error_rate_max` precedent). Distinct from a
1174 /// BUDGET: a clean time-boxed measurement is a bounded cursor or a
1175 /// `stop_when … effect: stop` (Interrupted+Succeeded), not this.
1176 #[serde(default)]
1177 pub timeout: Option<String>,
1178 /// SRD-83 — stop conditions for this phase shell. Each is a polydat
1179 /// predicate over runtime-state wires, plus a firing trigger and an
1180 /// effect. Evaluated at triggers; a true predicate stops the phase
1181 /// with its effect.
1182 #[serde(default)]
1183 pub stop_when: Vec<StopConditionSpec>,
1184 /// SRD-83 §throttle — adaptive backpressure governor: keep the
1185 /// windowed attempt-failure fraction under a bound by walking a
1186 /// dynamic control (`concurrency`/`rate`) down under overload and
1187 /// back up on recovery. `throttle: true` = defaults.
1188 #[serde(default, skip_serializing_if = "Option::is_none")]
1189 pub throttle: Option<ThrottleField>,
1190 /// Tag filter to select ops from blocks (e.g., `"block:schema"`).
1191 #[serde(default)]
1192 pub tags: Option<String>,
1193 /// Inline ops for this phase (parsed into `ParsedOp` list).
1194 #[serde(default)]
1195 pub ops: Vec<ParsedOp>,
1196 /// Phase template iteration: `"var in expr"`.
1197 /// The phase is instantiated once per element of the Polydat expression
1198 /// result (which must be a comma-separated string). Each instance
1199 /// has `{var}` available as a workload param in its ops and config.
1200 ///
1201 /// Example: `for_each: "profile in matching_profiles('{dataset}', '{prefix}')"`
1202 #[serde(default)]
1203 pub for_each: Option<String>,
1204 /// SRD-101 — optional `continue_if` pre-entry gate bounding this phase's
1205 /// `for_each` sweep (see [`ContinueIfSpec`]). Ignored when `for_each` is
1206 /// absent (no sweep to bound).
1207 #[serde(default, skip_serializing_if = "Option::is_none")]
1208 pub continue_if: Option<ContinueIfSpec>,
1209 /// Loop scope mode for `for_each` phases.
1210 ///
1211 /// Controls how the loop context is seeded from the outer scope:
1212 /// - `clean` (default): snapshot of outer scope at loop entry
1213 /// - `inherit`: outer scope's live state (includes prior phase mutations)
1214 #[serde(default)]
1215 pub loop_scope: Option<String>,
1216 /// Iteration scope mode for `for_each` phases.
1217 ///
1218 /// Controls how each iteration is seeded from the loop scope:
1219 /// - `inherit` (default for for_each): each iteration starts from the loop
1220 /// scope's current state. All loop-level variables are implicitly shared
1221 /// with iterations, so iteration N+1 sees what N wrote.
1222 /// - `clean`: each iteration starts from the loop scope snapshot (isolated)
1223 #[serde(default)]
1224 pub iter_scope: Option<String>,
1225 /// Summary report configuration for this phase.
1226 /// Checkpoint declaration: skip-on-resume eligibility plus
1227 /// optional sub-properties (hashing, verify op). `None` =
1228 /// no declaration = phase always re-runs on resume. See
1229 /// SRD-44 §"Eligibility — `checkpoint:` per-phase declaration".
1230 ///
1231 /// Parsed via [`Checkpoint`]'s custom deserialize from the
1232 /// three YAML forms (short string, disabled string/bool,
1233 /// full mapping).
1234 #[serde(default)]
1235 pub checkpoint: Option<Checkpoint>,
1236 /// Names of metrics to surface on the inline progress line
1237 /// and the per-phase ✓ DONE summary. Empty (default) → no
1238 /// extra metrics shown; the status line carries only the
1239 /// universal counters (pct, throughput, ok-rate, errors,
1240 /// retries, concurrency, duration).
1241 ///
1242 /// Each name is matched against the live relevancy
1243 /// aggregates (`recall_at_10`, `precision_at_10`, …) by exact
1244 /// equality. Workloads that compute custom relevancy metrics
1245 /// list the names they want emphasized; nothing is presumed
1246 /// to be present.
1247 ///
1248 /// Example:
1249 /// ```yaml
1250 /// phases:
1251 /// ann_query:
1252 /// status_metrics: [recall_at_10]
1253 /// ```
1254 #[serde(default)]
1255 pub status_metrics: Vec<String>,
1256 /// Phase-level Polydat `bindings:` block (SRD-13c, SRD-13d).
1257 /// Captured on the phase AST so the scope-tree pre-walk
1258 /// (SRD-13d §3) can classify phase-level Polydat content via
1259 /// [`crate::polydat_matter::HasPolydatMatter`] and so the runtime
1260 /// can compose a phase kernel layered between the
1261 /// workload kernel and any op-template kernels.
1262 ///
1263 /// Today the parser ALSO merges this block into per-op
1264 /// bindings (legacy `parse.rs::parse_phases` behaviour) so
1265 /// the existing runtime keeps working unchanged. Once
1266 /// SRD-13d phases 3–9 land (per-template kernels with
1267 /// proper `bind_outer_scope` chaining through the phase
1268 /// kernel), the per-op merge is removed and ops resolve
1269 /// phase bindings via the Polydat scope chain.
1270 #[serde(default, skip_serializing_if = "BindingsDef::is_empty")]
1271 pub bindings: BindingsDef,
1272 /// Phase-level synthetic-metric declarations. Mirror of
1273 /// [`ParsedOp::metrics`] (same [`MetricSpec`] schema and YAML
1274 /// shapes), but evaluated **once at phase completion** against
1275 /// the phase scope kernel rather than per-cycle. Each entry's
1276 /// `value:` is a Polydat expression over phase-scope wires
1277 /// (bindings, captures, params, iter-vars) plus the
1278 /// executor-injected `phase_start` wire (epoch millis at phase
1279 /// start). The canonical phase-duration metric reads a clock via
1280 /// a `volatile` phase binding and subtracts the injected origin:
1281 /// ```yaml
1282 /// bindings: |
1283 /// volatile now_ms := current_epoch_millis()
1284 /// metrics:
1285 /// time_to_index: { value: now_ms - phase_start }
1286 /// ```
1287 /// yielding the phase's wall-clock duration in millis. Empty when
1288 /// absent. No dedicated clock node is needed: `current_epoch_millis()`
1289 /// is a single read, and `phase_start` arrives as plain data, so the
1290 /// expression re-evaluates correctly at the completion-time pull.
1291 /// Declaring the clock read as its own `volatile` binding (rather
1292 /// than nesting it in the metric value) explicitly acknowledges the
1293 /// non-deterministic node, so the phase kernel stays clean under
1294 /// `--strict`.
1295 ///
1296 /// The synthesiser emits `volatile __metric_<name> := <value>`
1297 /// onto the phase kernel (see
1298 /// `nmbrs_runtime::scope::synthesize_metric_binding_name`); the
1299 /// executor pulls each at completion and records it on the
1300 /// phase component as the declared instrument (gauge by default).
1301 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
1302 pub metrics: HashMap<String, MetricSpec>,
1303 /// Dimensions this phase introduces: label NAME → declaration.
1304 ///
1305 /// Declared at the tier that owns the name, per the component tree's
1306 /// label-ownership rule (a name is set on exactly one tier and
1307 /// inherited downward). Values are not enumerated — they arrive from
1308 /// data via a metric's `cell:`.
1309 ///
1310 /// `BTreeMap` for deterministic synthesis order: a coordinate's
1311 /// rendering is what keys a cell, so an order that varied between runs
1312 /// would key one coordinate two ways.
1313 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
1314 pub dimensions: std::collections::BTreeMap<String, DimensionSpec>,
1315 /// Phase-level poll spec — when present, the phase's
1316 /// cycle execution runs in a wall-clock loop until a GK
1317 /// predicate over captures returns `true`. SRD-75.
1318 ///
1319 /// The presence of this field carries semantics beyond
1320 /// the data: it forbids `concurrency > 1` (serial-cycle
1321 /// loop is the unit of work), and it triggers
1322 /// scope-synthesis to allocate `shared` cells on the
1323 /// phase scope for capture names referenced by the
1324 /// predicate / `if:` conditions / metric values so
1325 /// cross-op visibility happens through the canonical
1326 /// Polydat chain (no sidecar HashMap; see SRD-75
1327 /// §"Architectural shape").
1328 #[serde(default, skip_serializing_if = "Option::is_none")]
1329 pub poll: Option<PhasePollSpec>,
1330 /// SRD-86 — when present, the executor dispatches the named optimizer over
1331 /// the phase: it writes each axis as an input wire on the phase's binding
1332 /// kernel and reads the `objective` wire back (the objective is *just a
1333 /// wire read*). Workload-local config; `nmbrs-runtime` maps it to its
1334 /// optimizer contract and discovers the optimizer via the link-time
1335 /// registry (`nmbrs describe optimizers`).
1336 ///
1337 /// **Sugar:** a bare **string** value is shorthand for `{ objective: <str> }`
1338 /// with every other field defaulted (`method: sweep`, no `servo:`) — so
1339 /// `optimize: "0 - err_rate"` ≡ `optimize: { objective: "0 - err_rate" }`.
1340 /// See `de_optimize`.
1341 #[serde(
1342 default,
1343 deserialize_with = "de_optimize",
1344 skip_serializing_if = "Option::is_none"
1345 )]
1346 pub optimize: Option<OptimizeBlock>,
1347 /// SRD-109 — key-metric designations: `key_metrics: {column:
1348 /// "agg(family)", ...}`. Aggregate qualification is mandatory
1349 /// (no implied aggregates); the report synthesizer attaches
1350 /// these columns to the row of the phase's nearest enclosing
1351 /// anchor, or the spine. Empty = spine-only via the SRD-91
1352 /// instrument contract defaults.
1353 #[serde(default)]
1354 pub key_metrics: Vec<KeyMetric>,
1355}
1356
1357/// A phase `optimize:` value: **either** a bare string — sugar for
1358/// `{ objective: <string> }` with every other field defaulted — **or** a full
1359/// [`OptimizeBlock`] map. The untagged enum tries `Inline` first, so a scalar
1360/// value never reaches the map variant. Shared by the serde-derive path
1361/// ([`de_optimize`]) and the hand-rolled phase parser
1362/// (`parse::*` via [`OptimizeBlock::from_yaml_value`]).
1363#[derive(Deserialize)]
1364#[serde(untagged)]
1365enum OptimizeSpec {
1366 Inline(String),
1367 Block(OptimizeBlock),
1368}
1369
1370impl From<OptimizeSpec> for OptimizeBlock {
1371 fn from(spec: OptimizeSpec) -> Self {
1372 match spec {
1373 // SRD-86 string sugar: the whole value IS the objective expression.
1374 OptimizeSpec::Inline(objective) => OptimizeBlock {
1375 method: default_optimize_method(),
1376 objective,
1377 servo: Vec::new(),
1378 max_evals: default_optimize_max_evals(),
1379 seed: default_optimize_seed(),
1380 params: HashMap::new(),
1381 },
1382 OptimizeSpec::Block(b) => b,
1383 }
1384 }
1385}
1386
1387impl OptimizeBlock {
1388 /// Parse a phase `optimize:` value from already-parsed JSON, applying the
1389 /// string sugar (a bare string ≡ `{ objective: <string> }`). Used by the
1390 /// hand-rolled phase parser, which builds [`WorkloadPhase`] field-by-field
1391 /// rather than through the derive (so it doesn't see `de_optimize`).
1392 ///
1393 /// Branches explicitly rather than going through the untagged
1394 /// `OptimizeSpec` so a malformed *map* keeps its precise serde error
1395 /// (e.g. `missing field 'objective'`) instead of the untagged enum's
1396 /// generic "did not match any variant".
1397 pub fn from_yaml_value(v: &serde_json::Value) -> Result<OptimizeBlock, serde_json::Error> {
1398 if let Some(s) = v.as_str() {
1399 Ok(OptimizeSpec::Inline(s.to_string()).into())
1400 } else {
1401 serde_json::from_value::<OptimizeBlock>(v.clone())
1402 }
1403 }
1404}
1405
1406/// Deserialize a phase `optimize:` value via [`OptimizeSpec`] — a bare string is
1407/// sugar for `{ objective: <string> }`, a map is a full [`OptimizeBlock`]
1408/// (SRD-86):
1409///
1410/// ```yaml
1411/// optimize: |
1412/// 0 - metricsql_scalar("sum(rate(errors_total[3s]))")
1413/// ```
1414fn de_optimize<'de, D>(d: D) -> Result<Option<OptimizeBlock>, D::Error>
1415where
1416 D: serde::Deserializer<'de>,
1417{
1418 Ok(Option::<OptimizeSpec>::deserialize(d)?.map(Into::into))
1419}
1420
1421/// SRD-86 — a phase `optimize:` block. The optimizer **maximizes** the
1422/// `objective` wire by writing the `axes` input wires on the phase kernel.
1423#[derive(Debug, Clone, Serialize, Deserialize)]
1424pub struct OptimizeBlock {
1425 /// Registered optimizer name (`cmaes`, `nelder_mead`, … — see
1426 /// `nmbrs describe optimizers`). Defaults to `sweep` (the identity: evaluate
1427 /// every coordinate and report the best), so a plain "find the best by
1428 /// sweeping" search omits this field; set an adaptive method to search a
1429 /// large or continuous space without enumerating it.
1430 #[serde(default = "default_optimize_method")]
1431 pub method: String,
1432 /// The objective the optimizer **maximizes** (SRD-86 §10). Two forms:
1433 /// a **bare wire reference** — a single identifier naming a phase-kernel
1434 /// output (a `bindings:` entry), read directly; or an **inline polydat
1435 /// expression** (anything with operators / calls, e.g.
1436 /// `objective: "0 - metricsql_scalar(\"sum(rate(errors_total[3s]))\")"`),
1437 /// which is lowered to a synthesized `__objective` binding on the phase
1438 /// kernel (`scope::objective_wire`) so no separate `bindings:` entry is
1439 /// needed. An objective reading a windowed/live metric settles per setting;
1440 /// a deterministic one takes the one-shot read.
1441 pub objective: String,
1442 /// Search axes to actuate as **live controls** — servoed (retargeted without
1443 /// restarting the phase) rather than stepped through by re-running the phase
1444 /// (SRD-86 §4). Every axis is a coordinate (step-through / re-run) by default;
1445 /// naming one here opts it into servoing. Accepts a single name (`servo:
1446 /// concurrency`) or a list (`servo: [concurrency, rate]`). A servoed var
1447 /// resolves to a control either directly (its name IS a control — `servo:
1448 /// concurrency` / `servo: rate`) or indirectly (it feeds one via a `{var}`
1449 /// bind — `concurrency: "{conc}"`, then `servo: conc`). It is validated: it
1450 /// must resolve to a control AND the objective must be a windowed metric the
1451 /// servo can settle — else a clear error, never a silent downgrade.
1452 #[serde(default, deserialize_with = "de_string_or_seq")]
1453 pub servo: Vec<String>,
1454 #[serde(default = "default_optimize_max_evals")]
1455 pub max_evals: usize,
1456 #[serde(default = "default_optimize_seed")]
1457 pub seed: u64,
1458 /// Optimizer-specific knobs (e.g. `{ lambda: 8 }`).
1459 #[serde(default)]
1460 pub params: HashMap<String, f64>,
1461}
1462
1463/// Deserialize a single string OR a sequence of strings into a `Vec<String>` —
1464/// lets `servo: conc` and `servo: [conc, rate]` both parse.
1465fn de_string_or_seq<'de, D>(d: D) -> Result<Vec<String>, D::Error>
1466where
1467 D: serde::Deserializer<'de>,
1468{
1469 #[derive(Deserialize)]
1470 #[serde(untagged)]
1471 enum OneOrMany {
1472 One(String),
1473 Many(Vec<String>),
1474 }
1475 Ok(match OneOrMany::deserialize(d)? {
1476 OneOrMany::One(s) => vec![s],
1477 OneOrMany::Many(v) => v,
1478 })
1479}
1480
1481fn default_optimize_method() -> String {
1482 "sweep".to_string()
1483}
1484fn default_optimize_max_evals() -> usize {
1485 100
1486}
1487fn default_optimize_seed() -> u64 {
1488 1
1489}
1490
1491/// Phase-level `poll:` block (SRD-75). When set on a
1492/// `WorkloadPhase`, the runner wraps the phase's cycle
1493/// execution in a wall-clock loop that re-runs all ops
1494/// per iteration until `until` (a Polydat boolean expression
1495/// over captures) returns `true` or `timeout_ms` elapses.
1496///
1497/// Differs from the per-op `PollingDispenser` (SRD-32):
1498/// per-op poll wraps a SINGLE op with row-count /
1499/// json-path emptiness termination; phase-poll wraps
1500/// MULTIPLE ops with predicate-over-captures termination.
1501/// They coexist; per-op poll is the right tool when a
1502/// single op's response is sufficient to signal
1503/// completion.
1504#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1505pub struct PhasePollSpec {
1506 /// Polydat boolean expression evaluated against the phase
1507 /// scope kernel after each iteration. Compiles into
1508 /// the phase scope as `__poll_until := <until>`;
1509 /// dynamic (re-evaluates per pull) per SRD-11's "two
1510 /// evaluation lifecycles" rule. Required.
1511 pub until: String,
1512 /// Sleep between iterations, milliseconds. A number or a
1513 /// `{param}` / iter-var reference resolved at the phase
1514 /// gather (unresolvable ⇒ the phase fails up front). Default
1515 /// `1000` (one second).
1516 #[serde(default)]
1517 pub interval_ms: Option<String>,
1518 /// Overall wall-clock cap, milliseconds. Same
1519 /// number-or-reference contract as `interval_ms`. The loop
1520 /// returns a `poll_timeout` error if exceeded. Default
1521 /// `300000` (5 minutes).
1522 #[serde(default)]
1523 pub timeout_ms: Option<String>,
1524 /// Consecutive retryable inner-op errors tolerated
1525 /// before propagation. Same number-or-reference contract
1526 /// as `interval_ms`. `0` (default) = strict: any
1527 /// retryable error fails the phase immediately.
1528 /// Mirrors per-op `PollingDispenser` semantics.
1529 #[serde(default)]
1530 pub max_error_retries: Option<String>,
1531 /// Named metric (gauge) written via `ctx.wires.write`
1532 /// when the loop terminates successfully. Value =
1533 /// elapsed wall-clock; unit decoded from the
1534 /// trailing suffix (`_s` / `_ms` / `_ns` / …) per
1535 /// the existing `duration_value_for_metric_name`
1536 /// convention. Same contract as per-op poll's
1537 /// `metric_name`. Default `None` (no metric).
1538 #[serde(default, skip_serializing_if = "Option::is_none")]
1539 pub metric_name: Option<String>,
1540 /// What to do when the wall-clock `timeout_ms`
1541 /// expires without satisfying `until`. SRD-75
1542 /// §"Workload-load validation" — the workload-author
1543 /// declares whether a stuck synchronizer is a
1544 /// recoverable phase-error or a workload-invalidating
1545 /// event.
1546 ///
1547 /// - `error` (default) — phase fails; the outer
1548 /// scenario's error-routing policy decides whether
1549 /// to continue to sibling phases. Suitable when a
1550 /// single cell's failed synchronization doesn't
1551 /// invalidate the rest of the sweep (rare).
1552 /// - `abort` — calls `session_signals::request_stop()`
1553 /// in addition to setting the phase's stop_flag.
1554 /// The scenario walker observes the global stop and
1555 /// terminates the whole run. Use when the
1556 /// predicate's satisfaction is a precondition for
1557 /// any downstream phase being meaningful — e.g.
1558 /// ensure_compacted in the CQL sweep: if the table
1559 /// never reaches `sstables == 1`, every subsequent
1560 /// query phase runs against an un-compacted table
1561 /// and produces meaningless results.
1562 #[serde(default, skip_serializing_if = "Option::is_none")]
1563 pub on_timeout: Option<String>,
1564 /// SRD-75 (C5) — strict-gate selectors. Each entry is a
1565 /// `metric()`-style selector (`"family, key=value, …"`) that MUST
1566 /// resolve to a registered instrument within the gate's grace
1567 /// window (the first poll interval); an unresolved selector is a
1568 /// hard `poll_require` error failing the phase. This is the
1569 /// runtime guard for coordination gates whose `until` reads
1570 /// another phase's live metrics — an unregistered family reads
1571 /// 0.0 silently, so a typo'd selector otherwise passes the gate
1572 /// instantly or hangs it to timeout. Deliberately poll-only:
1573 /// `stop_when`'s lenient reads stay as SRD-83 sanctions them
1574 /// ("family not yet present" is a legitimate not-yet state for a
1575 /// stop predicate; for a gate it is a bug).
1576 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1577 pub require: Vec<String>,
1578}
1579
1580/// Per-phase checkpoint declaration. Three legal forms in YAML:
1581///
1582/// - `checkpoint: idempotent` — short form, equivalent to
1583/// `Checkpoint { idempotent: true, hashed: true, verify: None }`.
1584/// - `checkpoint: none` (or `false`, or `no`) — explicitly not
1585/// skip-eligible. Equivalent to no declaration; the phase
1586/// always re-runs on resume.
1587/// - `checkpoint: { idempotent: true, hashed: true, verify: ... }`
1588/// — full mapping form with sub-properties.
1589///
1590/// See SRD-44 §"Forms" and §"Sub-properties" for the full
1591/// contract. The `Default` is "skip-eligible with hashing on,
1592/// no verify" — what the short form `idempotent` produces.
1593#[derive(Debug, Clone, Serialize, PartialEq)]
1594pub struct Checkpoint {
1595 /// Marks this phase as skip-eligible on resume. `false`
1596 /// here is equivalent to `checkpoint: none` and means the
1597 /// phase always re-runs.
1598 pub idempotent: bool,
1599 /// When `true` (the default for any set checkpoint
1600 /// declaration), the resume planner additionally verifies
1601 /// that the freshly-pre-mapped phase's compiled program
1602 /// hash matches the saved one before honouring the saved
1603 /// status. `false` is the operator opt-out — "trust
1604 /// structural identity (yaml_path + coords) alone".
1605 pub hashed: bool,
1606 /// Optional verify op-template body. When present, the
1607 /// resume planner runs this op against the live system
1608 /// before classifying the phase as Skip; verify failure
1609 /// reclassifies to re-run with wholesale purge.
1610 /// Currently typed as a generic YAML value — the runtime
1611 /// re-parses it through the op-template grammar so the
1612 /// existing pipeline (SRD-32 wrappers, SRD-03 status-
1613 /// determination invariants) governs the verify
1614 /// execution.
1615 pub verify: Option<serde_json::Value>,
1616}
1617
1618impl Default for Checkpoint {
1619 fn default() -> Self {
1620 Self {
1621 idempotent: true,
1622 hashed: true,
1623 verify: None,
1624 }
1625 }
1626}
1627
1628impl<'de> serde::Deserialize<'de> for Checkpoint {
1629 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1630 where
1631 D: serde::Deserializer<'de>,
1632 {
1633 // The YAML accepts a short form (`idempotent` / `none`)
1634 // or a mapping with sub-properties — one spelling per
1635 // meaning; a bool or bare null is an error naming them. Serde's
1636 // visitor pattern lets us handle each input shape
1637 // directly without going through a typed-value
1638 // intermediate, which means this works equally well
1639 // for the YAML parser path and the JSON-staged path
1640 // (parse.rs walks `serde_json::Map` for phases).
1641 struct CheckpointVisitor;
1642 impl<'de> serde::de::Visitor<'de> for CheckpointVisitor {
1643 type Value = Checkpoint;
1644
1645 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1646 f.write_str("checkpoint declaration: 'idempotent', 'none', or a mapping with sub-properties")
1647 }
1648
1649 fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Checkpoint, E> {
1650 match s {
1651 "idempotent" => Ok(Checkpoint::default()),
1652 "none" => Ok(Checkpoint {
1653 idempotent: false,
1654 hashed: true,
1655 verify: None,
1656 }),
1657 "true" | "false" => Err(E::custom(format!(
1658 "checkpoint: {s} is not a checkpoint form; \
1659 write `checkpoint: {}`",
1660 if s == "true" { "idempotent" } else { "none" }
1661 ))),
1662 other => Err(E::custom(format!(
1663 "checkpoint: unknown short form '{other}'; \
1664 expected 'idempotent', 'none', or a mapping"
1665 ))),
1666 }
1667 }
1668
1669 fn visit_string<E: serde::de::Error>(self, s: String) -> Result<Checkpoint, E> {
1670 self.visit_str(&s)
1671 }
1672
1673 fn visit_bool<E: serde::de::Error>(self, b: bool) -> Result<Checkpoint, E> {
1674 self.visit_str(if b { "true" } else { "false" })
1675 }
1676
1677 fn visit_unit<E: serde::de::Error>(self) -> Result<Checkpoint, E> {
1678 Err(E::custom(
1679 "checkpoint: empty value; write `checkpoint: idempotent` \
1680 or `checkpoint: none`",
1681 ))
1682 }
1683
1684 fn visit_map<M>(self, mut map: M) -> Result<Checkpoint, M::Error>
1685 where
1686 M: serde::de::MapAccess<'de>,
1687 {
1688 let mut idempotent = true;
1689 let mut hashed = true;
1690 let mut verify: Option<serde_json::Value> = None;
1691 while let Some(key) = map.next_key::<String>()? {
1692 match key.as_str() {
1693 "idempotent" => idempotent = map.next_value::<bool>()?,
1694 "hashed" => hashed = map.next_value::<bool>()?,
1695 "verify" => verify = Some(map.next_value::<serde_json::Value>()?),
1696 other => {
1697 return Err(serde::de::Error::custom(format!(
1698 "checkpoint: unknown key '{other}'; \
1699 expected 'idempotent', 'hashed', or 'verify'"
1700 )));
1701 }
1702 }
1703 }
1704 Ok(Checkpoint {
1705 idempotent,
1706 hashed,
1707 verify,
1708 })
1709 }
1710 }
1711 deserializer.deserialize_any(CheckpointVisitor)
1712 }
1713}
1714
1715/// A node in a scenario execution tree.
1716///
1717/// Scenarios are trees of phases and control flow constructs.
1718/// Nesting is supported to arbitrary depth. All nodes are
1719/// evaluated dynamically at runtime — no pre-flattening.
1720///
1721/// `cycle` is immutable — loop constructs declare their own
1722/// counter variables for iteration indices.
1723///
1724/// All iteration shapes (`for_each` single-clause,
1725/// `for_combinations`, `for_each_union`) collapse into one
1726/// `Comprehension` variant carrying the canonical
1727/// [`polydat::iteration::comprehension::Comprehension`] AST —
1728/// the operator-tree form of the algebra layer. The
1729/// structural variant (`Cartesian` / `Union` / `Clause` /
1730/// `Zip`) is the discriminator; `Filter` and `Order` wrap
1731/// the body when the workload declares `where` / `order`.
1732/// See SRD-18b §"Iteration as a First-Class Concept" and
1733/// `polydat/docs/design/comprehension_cutover_contact_surfaces.md`.
1734#[derive(Debug, Clone, Serialize, Deserialize)]
1735pub enum ScenarioNode {
1736 /// A single phase to execute.
1737 Phase(String),
1738 /// Iteration node — single-clause for_each, multi-clause
1739 /// for_combinations, or for_each_union all map here. The
1740 /// `Comprehension` AST captures the iteration shape; the
1741 /// runtime executes the cross-product of clauses for the
1742 /// Cartesian mode and the concatenation of sub-spaces'
1743 /// products for Union mode.
1744 ///
1745 /// YAML forms (all normalize to this variant):
1746 /// ```yaml
1747 /// # Single clause
1748 /// - for_each: "k in 10,100"
1749 ///
1750 /// # Multi-clause cross product
1751 /// - for_each: "profile in profiles, k in {k_values}"
1752 ///
1753 /// # Multi-clause cross product (map form)
1754 /// - for_combinations:
1755 /// profile: "matching_profiles('{dataset}', '{prefix}')"
1756 /// k: "{k_values}"
1757 ///
1758 /// # Union of sub-spaces
1759 /// - for_each:
1760 /// - "k in 10, limit in 10,20,30"
1761 /// - "k in 100, limit in 100,200,300"
1762 /// ```
1763 Comprehension {
1764 comprehension: polydat::iteration::comprehension::Comprehension,
1765 children: Vec<ScenarioNode>,
1766 /// SRD-101 — optional `continue_if` pre-entry gate bounding this
1767 /// sweep: evaluated per iteration before the body; a false predicate
1768 /// halts the sweep at its `each` scope, gracefully.
1769 #[serde(default, skip_serializing_if = "Option::is_none")]
1770 continue_if: Option<ContinueIfSpec>,
1771 /// SRD-109 — table-row anchor: `anchor: <view>` declares one
1772 /// report-table row per iteration of this sweep, in the view
1773 /// of that name. Views sharing a name must share coordinate
1774 /// label sets. Key metrics designated on phases beneath this
1775 /// node attach to its rows.
1776 #[serde(default, skip_serializing_if = "Option::is_none")]
1777 anchor: Option<String>,
1778 },
1779 /// Execute children while condition is true (test after).
1780 DoWhile {
1781 condition: String,
1782 counter: Option<String>,
1783 children: Vec<ScenarioNode>,
1784 },
1785 /// Execute children until condition becomes true (test after).
1786 DoUntil {
1787 condition: String,
1788 counter: Option<String>,
1789 children: Vec<ScenarioNode>,
1790 },
1791 /// Logical inclusion of another scenario by name.
1792 ///
1793 /// Wherever this node appears (top-level of a scenario, inside
1794 /// a `phases:` list under a `for_each` / `for_combinations` /
1795 /// `for_each_union`, etc.), it expands to the children of the
1796 /// named scenario at execution time. The wrapper is preserved
1797 /// (not flattened) so the scope tree retains the include
1798 /// hierarchy and the renderer can show the operator which
1799 /// scenario each group of phases came from.
1800 ///
1801 /// Resolution happens once after parsing
1802 /// (see `crate::parse::resolve_scenario_includes`); cycles
1803 /// (`A` includes `B` includes `A`) are rejected with a clear
1804 /// error naming the cycle path.
1805 ///
1806 /// YAML form:
1807 /// ```yaml
1808 /// scenarios:
1809 /// smoke:
1810 /// - schema
1811 /// - rampup
1812 /// bench:
1813 /// - scenario: smoke
1814 /// - for_each: "k in 10,100"
1815 /// phases:
1816 /// - scenario: smoke
1817 /// - search
1818 /// ```
1819 IncludedScenario {
1820 name: String,
1821 children: Vec<ScenarioNode>,
1822 },
1823 /// Scenario-tree-level Polydat bindings block — the canonical way
1824 /// to introduce a scope-local layer of bound names anywhere
1825 /// in the scenario tree.
1826 ///
1827 /// `source` is Polydat matter text exactly as a phase-level
1828 /// `bindings:` block would contain. Anything the Polydat grammar
1829 /// accepts is valid: `const NAME := <literal>`, derived
1830 /// bindings (`scaled := mul(workload_limit, 2)`), shared
1831 /// cells, init bindings, etc. Workload-param `{name}` and
1832 /// string-interpolation references resolve through the
1833 /// scope chain at kernel build time — no separate
1834 /// preprocessing pass.
1835 ///
1836 /// `Bindings` is also the canonical lowered form of `set:`.
1837 /// The parser recognizes `set: { name: value, ... }` as
1838 /// syntactic sugar and emits a `Bindings` node whose
1839 /// `source` is `final <name> := <polydat-literal>\n` (one line
1840 /// per pair, declaration order preserved). So
1841 ///
1842 /// ```yaml
1843 /// - set: { mode: verbose }
1844 /// phases:
1845 /// - announce
1846 /// ```
1847 ///
1848 /// is semantically identical to
1849 ///
1850 /// ```yaml
1851 /// - bindings: |
1852 /// const mode := "verbose"
1853 /// phases:
1854 /// - announce
1855 /// ```
1856 ///
1857 /// Both produce one `Bindings` node. Authors keep the
1858 /// short `set:` form for the common override case; the
1859 /// long form unlocks the full Polydat grammar (derived
1860 /// bindings, expressions referencing other in-scope
1861 /// names, etc.) without any new variant.
1862 ///
1863 /// Lexical-shadow semantics are uniform with phase-level
1864 /// `bindings:`: a `const NAME := <value>` shadows any
1865 /// upstream binding for `NAME` over this node's `children`
1866 /// subtree. The shadow is enforced via the local-final
1867 /// transit-suppression rule in `materialize_wiring_from_outer`
1868 /// — the same mechanism every other scope uses.
1869 ///
1870 /// Composition example (two siblings, each defining its
1871 /// own value for the same name; the included subtree is
1872 /// physically cloned per include site so encapsulation is
1873 /// per-instance):
1874 ///
1875 /// ```yaml
1876 /// scenarios:
1877 /// fanout:
1878 /// - set: { mode: verbose }
1879 /// phases:
1880 /// - scenario: load_test
1881 /// - set: { mode: quiet }
1882 /// phases:
1883 /// - scenario: load_test
1884 /// ```
1885 Bindings {
1886 source: String,
1887 children: Vec<ScenarioNode>,
1888 },
1889}
1890
1891/// Legacy alias.
1892pub type ScenarioStep = ScenarioNode;
1893
1894/// How bindings are defined for an op.
1895///
1896/// Two modes:
1897/// - **Map**: Legacy nosqlbench-style `name: "FuncA(); FuncB()"` chains.
1898/// Each binding is independent; inheritance merges at key level.
1899/// - **PolydatSource**: Native Polydat grammar as a multiline string. The entire
1900/// binding block is a single Polydat program with coordinates, named outputs,
1901/// and full DAG wiring. Replaces (not merges with) any inherited bindings.
1902#[derive(Debug, Clone, Serialize, Deserialize)]
1903#[serde(untagged)]
1904pub enum BindingsDef {
1905 /// Legacy nosqlbench-style: name → expression chain.
1906 Map(HashMap<String, String>),
1907 /// Native Polydat grammar source text.
1908 PolydatSource(String),
1909}
1910
1911impl Default for BindingsDef {
1912 fn default() -> Self {
1913 BindingsDef::Map(HashMap::new())
1914 }
1915}
1916
1917impl BindingsDef {
1918 /// Returns true if there are no bindings defined.
1919 pub fn is_empty(&self) -> bool {
1920 match self {
1921 BindingsDef::Map(m) => m.is_empty(),
1922 BindingsDef::PolydatSource(s) => s.trim().is_empty(),
1923 }
1924 }
1925
1926 /// Get the map view (for legacy code). Returns empty map for PolydatSource.
1927 pub fn as_map(&self) -> &HashMap<String, String> {
1928 static EMPTY: std::sync::LazyLock<HashMap<String, String>> =
1929 std::sync::LazyLock::new(HashMap::new);
1930 match self {
1931 BindingsDef::Map(m) => m,
1932 BindingsDef::PolydatSource(_) => &EMPTY,
1933 }
1934 }
1935
1936 /// Insert a key-value pair (legacy map mode). Converts PolydatSource to Map.
1937 pub fn insert(&mut self, key: String, value: String) {
1938 match self {
1939 BindingsDef::Map(m) => {
1940 m.insert(key, value);
1941 }
1942 _ => {
1943 let mut m = HashMap::new();
1944 m.insert(key, value);
1945 *self = BindingsDef::Map(m);
1946 }
1947 }
1948 }
1949}
1950
1951/// SRD-108 Part B — the typed interface an abstract op slot
1952/// declares: wires the blueprint scope guarantees (`needs`),
1953/// wires the bound implementation must deliver via captures
1954/// (`yields`), and wires it must deliver by projecting the
1955/// result body via `result:` bindings (`results`, SRD-109 Part
1956/// 3), each `name -> polydat type`. A workload writes the type as
1957/// its polydat keyword (`u64`, `f64`, `str`, `vec_f32`, `vec_i64`,
1958/// …); the parser resolves it through
1959/// [`crate::port_types::resolve_type_keyword`], and the maps
1960/// serialize each type back as that keyword. BTreeMaps so the
1961/// SRD-107 config digest serializes stably.
1962#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1963pub struct OpInterface {
1964 #[serde(
1965 default,
1966 skip_serializing_if = "std::collections::BTreeMap::is_empty",
1967 with = "crate::port_types::keyword_map"
1968 )]
1969 pub needs: std::collections::BTreeMap<String, polydat::ast::PortType>,
1970 #[serde(
1971 default,
1972 skip_serializing_if = "std::collections::BTreeMap::is_empty",
1973 with = "crate::port_types::keyword_map"
1974 )]
1975 pub yields: std::collections::BTreeMap<String, polydat::ast::PortType>,
1976 #[serde(
1977 default,
1978 skip_serializing_if = "std::collections::BTreeMap::is_empty",
1979 with = "crate::port_types::keyword_map"
1980 )]
1981 pub results: std::collections::BTreeMap<String, polydat::ast::PortType>,
1982}
1983
1984/// A normalized op template — the canonical form.
1985#[derive(Debug, Clone, Serialize, Deserialize)]
1986pub struct ParsedOp {
1987 pub name: String,
1988 #[serde(default, skip_serializing_if = "Option::is_none")]
1989 pub description: Option<String>,
1990 /// The operation payload: field name → value.
1991 /// The statement is always under `"stmt"` after normalization.
1992 /// The original field name that carried the statement (e.g., `"raw"`,
1993 /// `"simple"`, `"prepared"`, `"stmt"`) is preserved in `stmt_type`
1994 /// for adapters that dispatch on execution mode.
1995 pub op: HashMap<String, serde_json::Value>,
1996 /// Binding definitions: either a name→expression map (legacy) or
1997 /// a Polydat grammar source string (native).
1998 #[serde(default, skip_serializing_if = "BindingsDef::is_empty")]
1999 pub bindings: BindingsDef,
2000 /// Configuration parameters.
2001 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
2002 pub params: HashMap<String, serde_json::Value>,
2003 /// Tags for filtering and metadata.
2004 #[serde(default)]
2005 pub tags: HashMap<String, String>,
2006 /// Optional condition expression (from YAML `if:` field).
2007 /// Evaluated per cycle before the op executes. If the result
2008 /// is falsy (false, 0, empty string, None), the op is skipped.
2009 #[serde(default, skip_serializing_if = "Option::is_none")]
2010 pub condition: Option<String>,
2011 /// Optional delay specification (from YAML `delay:` field).
2012 /// Two surface forms:
2013 /// - Bare string: `delay: <name>` — a Polydat binding name
2014 /// producing the pre-op delay value (u64 = ns, f64 = ms).
2015 /// - Map: `delay: { before: <name>, after: <name> }` —
2016 /// independent pre-op and post-op delays; both subkeys
2017 /// are optional but at least one must be set.
2018 #[serde(default, skip_serializing_if = "Option::is_none")]
2019 pub delay: Option<DelaySpec>,
2020 /// SRD-40b synthetic-metric declarations. Each entry
2021 /// publishes one metric family per cycle, valued by a GK
2022 /// expression evaluated in the op's bound scope. Empty
2023 /// when absent. Map key is the metric name and the
2024 /// **default family name**; `MetricSpec::family` overrides
2025 /// it when set. See SRD-40b §1 for the schema, §2 for
2026 /// sugared forms (bare-string / list with wire-expression
2027 /// entries).
2028 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
2029 pub metrics: HashMap<String, MetricSpec>,
2030 /// Dimensional placement of the op's OWN measurements: dimension
2031 /// name → polydat expression, the grammar of [`MetricSpec::cell`].
2032 ///
2033 /// Each cycle's service time, relevancy scores and validation
2034 /// outcomes are recorded in the cell the expressions name for that
2035 /// cycle, beside the phase's totals (which are unchanged). Each
2036 /// dimension must be declared on the phase (`dimensions:`).
2037 ///
2038 /// Ordered for the reason `MetricSpec::cell` is: the canonical
2039 /// rendering of a coordinate keys its cell.
2040 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
2041 pub cell: std::collections::BTreeMap<String, String>,
2042 /// SRD-66 result-bindings. Vari-structured: string is
2043 /// Polydat source, list is a sequence of fragments, map is
2044 /// named-key short-forms with a composite-map output.
2045 /// `None` ⇒ no result wires; the result wrapper is a
2046 /// no-op for this op.
2047 #[serde(default, skip_serializing_if = "Option::is_none")]
2048 pub result: Option<ResultSpec>,
2049 /// Optional `traverse:` block — CUSTOMISES the always-installed result
2050 /// traversal layer; it does not select it. Like `result:`, absence means
2051 /// "default behaviour", not "no traversal".
2052 #[serde(default, skip_serializing_if = "Option::is_none")]
2053 pub traverse: Option<TraverseSpec>,
2054 /// SRD-32a Push 3 — per-op wrapper-composition override.
2055 /// When present, this op uses the named order instead of
2056 /// the workload-root or runtime-default tiebreaker order.
2057 /// Shadows the workload-root `wrappers:` block entirely
2058 /// (no merge).
2059 #[serde(default, skip_serializing_if = "Option::is_none")]
2060 pub wrappers: Option<WrappersConfig>,
2061 /// Capture-point specs extracted at parse time from any
2062 /// string-valued entry in `op`. Each spec names a column the
2063 /// result body carries and the wire it should be written to
2064 /// via `ctx.wires.write` at cycle time. The `slurp` flag
2065 /// selects between single-row (`[name]`) and all-rows
2066 /// (`[@name]`) extraction.
2067 ///
2068 /// The parser strips the bracket syntax from the source op
2069 /// fields after harvesting the spec, so adapters consume
2070 /// clean text (e.g. `SELECT [key] FROM ...` becomes
2071 /// `SELECT key FROM ...`). Downstream wrappers read this
2072 /// list directly — no re-parsing of the op's text fields.
2073 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2074 pub captures: Vec<crate::bindpoints::CapturePoint>,
2075 /// SRD-108 Part B — present when this op was declared as an
2076 /// ABSTRACT slot (`abstract:` body): the interface a bound
2077 /// implementation must satisfy. Retained on the bound op so
2078 /// pre-map synthesis can verify `yields` against the compiled
2079 /// op-template program.
2080 #[serde(default, skip_serializing_if = "Option::is_none")]
2081 pub abstract_interface: Option<OpInterface>,
2082 /// SRD-108 Part B — `true` once an implementation has been
2083 /// bound into this slot. An op with an interface but
2084 /// `interface_bound == false` at run initiation is a load
2085 /// error ("abstract op unbound").
2086 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2087 pub interface_bound: bool,
2088 /// Daemon-fiber declaration. When set to a non-`Disabled`
2089 /// value, dispatches of this op from the cycle-pool spawn
2090 /// onto a daemon fiber instead of running inline. Daemons
2091 /// stay in scope of the phase so their failures bubble up;
2092 /// the cycle-pool fiber continues immediately to the next
2093 /// op without awaiting.
2094 ///
2095 /// YAML forms accepted:
2096 /// - `daemon: false` / `daemon: 0` → not a daemon (cycle-pool op).
2097 /// - `daemon: true` / `daemon: 1` → daemon, max 1 concurrent
2098 /// fiber per phase activation.
2099 /// - `daemon: <N>` (N ≥ 1) → daemon, max N concurrent
2100 /// fibers per phase activation.
2101 ///
2102 /// The cap is enforced at spawn time: when the cycle-pool
2103 /// dispatches the op and the live-fiber count is already at
2104 /// N, the spawn errors and the phase fails with a clear
2105 /// stop_reason. There's no queuing — exceeding the cap is a
2106 /// workload-design error, not backpressure to absorb.
2107 ///
2108 /// Per-op-name dedup: daemons are tracked by op-template
2109 /// name. Subsequent dispatches of the same name silently
2110 /// succeed up to the cap; over the cap they fail loud.
2111 /// Natural daemon exit (Completed / Cancelled / Errored /
2112 /// TimedOut / Panicked) decrements the count, freeing a
2113 /// slot for the next dispatch.
2114 ///
2115 /// Use case: a long-running server call (e.g.
2116 /// `forceKeyspaceCompaction`) that the workload wants to
2117 /// fire while a sibling op concurrently observes progress.
2118 /// The daemon op stays in scope so its failures bubble up;
2119 /// the cycle-pool op runs alongside without serialisation.
2120 ///
2121 /// Parser invariants when `daemon` is `MaxFibers(_)`:
2122 /// - `cycles:` and `ratio:` on this op are rejected — the
2123 /// daemon's dispatch cadence is governed by the cycle-pool
2124 /// walks, not by cycles-per-second.
2125 /// - `if:` / `while:` apply as usual; a falsy guard skips
2126 /// the dispatch with no spawn.
2127 #[serde(default, skip_serializing_if = "DaemonSpec::is_disabled")]
2128 pub daemon: DaemonSpec,
2129 /// How long the phase waits for this daemon's in-flight
2130 /// future to drop after sending the stop signal. Past the
2131 /// window, the phase records a daemon-shutdown failure and
2132 /// fails. Per-op override of the activity-level default
2133 /// (5000 ms).
2134 ///
2135 /// Only meaningful when `daemon` is `MaxFibers(_)`.
2136 #[serde(default, skip_serializing_if = "Option::is_none")]
2137 pub daemon_cancel_grace_ms: Option<u64>,
2138 /// Polydat boolean expression evaluated on the daemon's fiber
2139 /// inside the wrapper stack. When set, the daemon body runs
2140 /// a loop: while the condition is truthy, dispatch the
2141 /// inner op; when falsy or stop-signalled, exit.
2142 ///
2143 /// `while:` composes inside `if:` (which gates whether the
2144 /// loop starts at all) and outside the per-op-rate
2145 /// throttling (which paces iterations).
2146 ///
2147 /// Parser invariants:
2148 /// - `while:` on a non-daemon op is currently allowed but
2149 /// blocks the cycle-pool fiber until the loop exits. The
2150 /// common use case is daemon + while.
2151 #[serde(default, skip_serializing_if = "Option::is_none")]
2152 pub while_cond: Option<String>,
2153 /// Per-op rate spec governing the iteration cadence of the
2154 /// while-loop (or per-cycle dispatch for non-loop ops).
2155 /// Format: `"<N>"` (N/s, bare integer), `"<N>/s"`,
2156 /// `"<N>/m"`, `"<N>/h"`. Each op with `rate:` gets its own
2157 /// `RateLimiter` at phase init — INDEPENDENT of the
2158 /// activity-level `rate:` and of other ops' rate limiters.
2159 ///
2160 /// `rate: 0` is "unlimited" (no throttling).
2161 #[serde(default, skip_serializing_if = "Option::is_none")]
2162 pub rate: Option<String>,
2163}
2164
2165/// Daemon-fiber capacity declaration. The on-disk surface
2166/// accepts multiple YAML scalar shapes (bool / int / string)
2167/// that all map into this two-variant enum.
2168///
2169/// `Disabled` is the default — the op runs on the cycle-pool
2170/// fiber inline like everything else. `MaxFibers(N)` opts in
2171/// to daemon-fiber dispatch with a per-op-name cap of N.
2172#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2173pub enum DaemonSpec {
2174 #[default]
2175 Disabled,
2176 MaxFibers(u32),
2177}
2178
2179impl DaemonSpec {
2180 pub fn is_disabled(&self) -> bool {
2181 matches!(self, DaemonSpec::Disabled)
2182 }
2183 pub fn max_fibers(&self) -> Option<u32> {
2184 match self {
2185 DaemonSpec::Disabled => None,
2186 DaemonSpec::MaxFibers(n) => Some(*n),
2187 }
2188 }
2189}
2190
2191impl serde::Serialize for DaemonSpec {
2192 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2193 match self {
2194 DaemonSpec::Disabled => s.serialize_bool(false),
2195 DaemonSpec::MaxFibers(1) => s.serialize_bool(true),
2196 DaemonSpec::MaxFibers(n) => s.serialize_u32(*n),
2197 }
2198 }
2199}
2200
2201impl<'de> serde::Deserialize<'de> for DaemonSpec {
2202 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
2203 let v = serde_json::Value::deserialize(d)?;
2204 parse_daemon_spec_value(&v).map_err(serde::de::Error::custom)
2205 }
2206}
2207
2208/// Parse a YAML/JSON scalar into a `DaemonSpec`.
2209///
2210/// Accepted forms:
2211/// - `true` / `1` / `"true"` / `"on"` → `MaxFibers(1)`
2212/// - `false` / `0` / `"false"` / `"off"` → `Disabled`
2213/// - non-negative integer N ≥ 1 → `MaxFibers(N)`
2214/// - non-negative integer 0 → `Disabled`
2215///
2216/// Rejected forms (returns descriptive error):
2217/// - negative integers
2218/// - non-integer numbers (1.5, NaN, ...)
2219/// - strings other than the accepted set
2220/// - null, arrays, objects
2221///
2222/// Public so the unit + proptest layers can exercise it
2223/// directly without a full YAML round-trip.
2224pub fn parse_daemon_spec_value(v: &serde_json::Value) -> Result<DaemonSpec, String> {
2225 match v {
2226 serde_json::Value::Bool(true) => Ok(DaemonSpec::MaxFibers(1)),
2227 serde_json::Value::Bool(false) => Ok(DaemonSpec::Disabled),
2228 serde_json::Value::Number(n) => {
2229 if let Some(u) = n.as_u64() {
2230 if u == 0 {
2231 Ok(DaemonSpec::Disabled)
2232 } else if u <= u32::MAX as u64 {
2233 Ok(DaemonSpec::MaxFibers(u as u32))
2234 } else {
2235 Err(format!(
2236 "daemon: {u} exceeds u32::MAX — caps above {} \
2237 aren't supported (and don't make practical sense)",
2238 u32::MAX,
2239 ))
2240 }
2241 } else if n.as_i64().is_some_and(|i| i < 0) {
2242 Err(format!(
2243 "daemon: {n} — negative integers are invalid. \
2244 Use 0 or false to disable, or a positive \
2245 integer for the max-fibers cap.",
2246 ))
2247 } else {
2248 Err(format!(
2249 "daemon: {n} — non-integer numbers are invalid. \
2250 Use a boolean or a non-negative integer.",
2251 ))
2252 }
2253 }
2254 serde_json::Value::String(s) => match s.as_str() {
2255 "true" => Ok(DaemonSpec::MaxFibers(1)),
2256 "false" => Ok(DaemonSpec::Disabled),
2257 other => Err(format!(
2258 "daemon: \"{other}\" — not a daemon setting; \
2259 write true / false or a non-negative integer cap.",
2260 )),
2261 },
2262 serde_json::Value::Null => {
2263 Err("daemon: null is not a valid value. Use false to disable.".into())
2264 }
2265 other => Err(format!(
2266 "daemon: {other:?} — only boolean, integer, or string forms \
2267 are accepted.",
2268 )),
2269 }
2270}
2271
2272/// Per-op delay specification. Two surface forms on YAML:
2273/// - Bare string `delay: <name>` → `Before(<name>)`: a GK
2274/// binding name producing the pre-op delay value (u64 ns,
2275/// f64 ms).
2276/// - Map `delay: { before: <name>, after: <name> }` →
2277/// `BeforeAfter`: independent pre-op and post-op delays.
2278/// Both subkeys are optional; an empty map is a parse error.
2279#[derive(Debug, Clone, PartialEq, Eq)]
2280pub enum DelaySpec {
2281 /// Single pre-op delay. Equivalent to BeforeAfter { Some, None }
2282 /// at runtime; the discriminant exists so YAML round-trip
2283 /// preserves the author's chosen surface form.
2284 Before(String),
2285 BeforeAfter {
2286 before: Option<String>,
2287 after: Option<String>,
2288 },
2289}
2290
2291impl DelaySpec {
2292 /// Pre-op delay binding name, if any.
2293 pub fn before(&self) -> Option<&str> {
2294 match self {
2295 DelaySpec::Before(n) => Some(n.as_str()),
2296 DelaySpec::BeforeAfter { before, .. } => before.as_deref(),
2297 }
2298 }
2299 /// Post-op delay binding name, if any.
2300 pub fn after(&self) -> Option<&str> {
2301 match self {
2302 DelaySpec::Before(_) => None,
2303 DelaySpec::BeforeAfter { after, .. } => after.as_deref(),
2304 }
2305 }
2306 /// Every binding name this spec references. Used by scope
2307 /// synthesis to ensure the names land on the per-op kernel.
2308 pub fn names(&self) -> Vec<&str> {
2309 match self {
2310 DelaySpec::Before(n) => vec![n.as_str()],
2311 DelaySpec::BeforeAfter { before, after } => {
2312 let mut out = Vec::with_capacity(2);
2313 if let Some(b) = before.as_deref() {
2314 out.push(b);
2315 }
2316 if let Some(a) = after.as_deref() {
2317 out.push(a);
2318 }
2319 out
2320 }
2321 }
2322 }
2323}
2324
2325impl serde::Serialize for DelaySpec {
2326 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2327 use serde::ser::SerializeMap;
2328 match self {
2329 DelaySpec::Before(name) => s.serialize_str(name),
2330 DelaySpec::BeforeAfter { before, after } => {
2331 let mut m = s.serialize_map(None)?;
2332 if let Some(b) = before {
2333 m.serialize_entry("before", b)?;
2334 }
2335 if let Some(a) = after {
2336 m.serialize_entry("after", a)?;
2337 }
2338 m.end()
2339 }
2340 }
2341 }
2342}
2343
2344impl<'de> serde::Deserialize<'de> for DelaySpec {
2345 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
2346 let v = serde_json::Value::deserialize(d)?;
2347 parse_delay_spec_value(&v).map_err(serde::de::Error::custom)
2348 }
2349}
2350
2351/// Parse a YAML/JSON value into a `DelaySpec`.
2352///
2353/// Accepted:
2354/// - non-empty string → `Before(<string>)`
2355/// - object with `before` and/or `after` keys → `BeforeAfter`
2356///
2357/// Rejected (descriptive error):
2358/// - empty string
2359/// - empty object
2360/// - object with unknown keys
2361/// - object whose `before` / `after` values aren't strings
2362/// - null, arrays, numbers, booleans
2363///
2364/// Public for unit tests + smoke validation.
2365pub fn parse_delay_spec_value(v: &serde_json::Value) -> Result<DelaySpec, String> {
2366 match v {
2367 serde_json::Value::String(s) => {
2368 let trimmed = s.trim();
2369 if trimmed.is_empty() {
2370 Err("delay: empty string is not a valid binding name".into())
2371 } else {
2372 Ok(DelaySpec::Before(trimmed.to_string()))
2373 }
2374 }
2375 serde_json::Value::Object(map) => {
2376 let mut before: Option<String> = None;
2377 let mut after: Option<String> = None;
2378 for (k, v) in map {
2379 match k.as_str() {
2380 "before" => {
2381 before = match v {
2382 serde_json::Value::String(s) => {
2383 let t = s.trim();
2384 if t.is_empty() {
2385 return Err(
2386 "delay.before: empty string is not a valid binding name"
2387 .into(),
2388 );
2389 }
2390 Some(t.to_string())
2391 }
2392 other => {
2393 return Err(format!(
2394 "delay.before: expected string, got {other:?}",
2395 ));
2396 }
2397 };
2398 }
2399 "after" => {
2400 after = match v {
2401 serde_json::Value::String(s) => {
2402 let t = s.trim();
2403 if t.is_empty() {
2404 return Err(
2405 "delay.after: empty string is not a valid binding name"
2406 .into(),
2407 );
2408 }
2409 Some(t.to_string())
2410 }
2411 other => {
2412 return Err(
2413 format!("delay.after: expected string, got {other:?}",),
2414 );
2415 }
2416 };
2417 }
2418 other => {
2419 return Err(format!(
2420 "delay: unknown key `{other}` — accepted: `before`, `after`",
2421 ));
2422 }
2423 }
2424 }
2425 if before.is_none() && after.is_none() {
2426 Err("delay: map form must set at least one of `before` / `after`".into())
2427 } else {
2428 Ok(DelaySpec::BeforeAfter { before, after })
2429 }
2430 }
2431 serde_json::Value::Null => {
2432 Err("delay: null is not a valid value. Omit the field instead.".into())
2433 }
2434 other => Err(format!(
2435 "delay: {other:?} — accepted forms are a binding-name string or \
2436 a map `{{ before: <name>, after: <name> }}`",
2437 )),
2438 }
2439}
2440
2441#[cfg(test)]
2442mod delay_spec_tests {
2443 use super::*;
2444 use serde_json::json;
2445
2446 #[test]
2447 fn parse_bare_string_is_before() {
2448 let spec = parse_delay_spec_value(&json!("ticks")).unwrap();
2449 assert_eq!(spec, DelaySpec::Before("ticks".into()));
2450 }
2451
2452 #[test]
2453 fn parse_trimmed_string() {
2454 let spec = parse_delay_spec_value(&json!(" ticks ")).unwrap();
2455 assert_eq!(spec, DelaySpec::Before("ticks".into()));
2456 }
2457
2458 #[test]
2459 fn parse_map_with_both() {
2460 let spec = parse_delay_spec_value(&json!({
2461 "before": "pre", "after": "post"
2462 }))
2463 .unwrap();
2464 assert_eq!(
2465 spec,
2466 DelaySpec::BeforeAfter {
2467 before: Some("pre".into()),
2468 after: Some("post".into()),
2469 }
2470 );
2471 }
2472
2473 #[test]
2474 fn parse_map_before_only() {
2475 let spec = parse_delay_spec_value(&json!({ "before": "pre" })).unwrap();
2476 assert_eq!(
2477 spec,
2478 DelaySpec::BeforeAfter {
2479 before: Some("pre".into()),
2480 after: None,
2481 }
2482 );
2483 }
2484
2485 #[test]
2486 fn parse_map_after_only() {
2487 let spec = parse_delay_spec_value(&json!({ "after": "post" })).unwrap();
2488 assert_eq!(
2489 spec,
2490 DelaySpec::BeforeAfter {
2491 before: None,
2492 after: Some("post".into()),
2493 }
2494 );
2495 }
2496
2497 #[test]
2498 fn parse_rejects_empty_string() {
2499 assert!(parse_delay_spec_value(&json!("")).is_err());
2500 assert!(parse_delay_spec_value(&json!(" ")).is_err());
2501 }
2502
2503 #[test]
2504 fn parse_rejects_empty_map() {
2505 assert!(parse_delay_spec_value(&json!({})).is_err());
2506 }
2507
2508 #[test]
2509 fn parse_rejects_unknown_key() {
2510 let e = parse_delay_spec_value(&json!({
2511 "before": "pre", "during": "mid"
2512 }))
2513 .unwrap_err();
2514 assert!(e.contains("during"));
2515 }
2516
2517 #[test]
2518 fn parse_rejects_non_string_value() {
2519 assert!(parse_delay_spec_value(&json!({ "before": 5 })).is_err());
2520 assert!(parse_delay_spec_value(&json!({ "after": true })).is_err());
2521 assert!(parse_delay_spec_value(&json!({ "before": null })).is_err());
2522 }
2523
2524 #[test]
2525 fn parse_rejects_null_top_level() {
2526 assert!(parse_delay_spec_value(&json!(null)).is_err());
2527 }
2528
2529 #[test]
2530 fn parse_rejects_array() {
2531 assert!(parse_delay_spec_value(&json!(["pre"])).is_err());
2532 }
2533
2534 #[test]
2535 fn parse_rejects_number() {
2536 assert!(parse_delay_spec_value(&json!(1.5)).is_err());
2537 assert!(parse_delay_spec_value(&json!(100)).is_err());
2538 }
2539
2540 #[test]
2541 fn parse_rejects_empty_after_value() {
2542 assert!(parse_delay_spec_value(&json!({ "after": "" })).is_err());
2543 }
2544
2545 #[test]
2546 fn round_trip_before_serializes_as_string() {
2547 let spec = DelaySpec::Before("ticks".into());
2548 let v = serde_json::to_value(&spec).unwrap();
2549 assert_eq!(v, json!("ticks"));
2550 let parsed: DelaySpec = serde_json::from_value(v).unwrap();
2551 assert_eq!(parsed, spec);
2552 }
2553
2554 #[test]
2555 fn round_trip_map_serializes_as_object() {
2556 let spec = DelaySpec::BeforeAfter {
2557 before: Some("pre".into()),
2558 after: Some("post".into()),
2559 };
2560 let v = serde_json::to_value(&spec).unwrap();
2561 assert_eq!(v.get("before"), Some(&json!("pre")));
2562 assert_eq!(v.get("after"), Some(&json!("post")));
2563 let parsed: DelaySpec = serde_json::from_value(v).unwrap();
2564 assert_eq!(parsed, spec);
2565 }
2566
2567 #[test]
2568 fn names_returns_all_referenced() {
2569 assert_eq!(DelaySpec::Before("x".into()).names(), vec!["x"]);
2570 let spec = DelaySpec::BeforeAfter {
2571 before: Some("a".into()),
2572 after: Some("b".into()),
2573 };
2574 assert_eq!(spec.names(), vec!["a", "b"]);
2575 let only_before = DelaySpec::BeforeAfter {
2576 before: Some("a".into()),
2577 after: None,
2578 };
2579 assert_eq!(only_before.names(), vec!["a"]);
2580 }
2581
2582 #[test]
2583 fn accessors_return_correct_names() {
2584 let s = DelaySpec::Before("x".into());
2585 assert_eq!(s.before(), Some("x"));
2586 assert_eq!(s.after(), None);
2587 let s = DelaySpec::BeforeAfter {
2588 before: Some("a".into()),
2589 after: Some("b".into()),
2590 };
2591 assert_eq!(s.before(), Some("a"));
2592 assert_eq!(s.after(), Some("b"));
2593 }
2594}
2595
2596#[cfg(test)]
2597mod daemon_spec_tests {
2598 use super::*;
2599 use serde_json::json;
2600
2601 #[test]
2602 fn bool_true_is_max_1() {
2603 assert_eq!(
2604 parse_daemon_spec_value(&json!(true)).unwrap(),
2605 DaemonSpec::MaxFibers(1)
2606 );
2607 }
2608 #[test]
2609 fn bool_false_is_disabled() {
2610 assert_eq!(
2611 parse_daemon_spec_value(&json!(false)).unwrap(),
2612 DaemonSpec::Disabled
2613 );
2614 }
2615 #[test]
2616 fn int_0_is_disabled() {
2617 assert_eq!(
2618 parse_daemon_spec_value(&json!(0)).unwrap(),
2619 DaemonSpec::Disabled
2620 );
2621 }
2622 #[test]
2623 fn int_1_is_max_1() {
2624 assert_eq!(
2625 parse_daemon_spec_value(&json!(1)).unwrap(),
2626 DaemonSpec::MaxFibers(1)
2627 );
2628 }
2629 #[test]
2630 fn int_n_is_max_n() {
2631 assert_eq!(
2632 parse_daemon_spec_value(&json!(10)).unwrap(),
2633 DaemonSpec::MaxFibers(10)
2634 );
2635 }
2636 #[test]
2637 fn str_true_and_false_are_the_string_forms() {
2638 assert_eq!(
2639 parse_daemon_spec_value(&json!("true")).unwrap(),
2640 DaemonSpec::MaxFibers(1)
2641 );
2642 assert_eq!(
2643 parse_daemon_spec_value(&json!("false")).unwrap(),
2644 DaemonSpec::Disabled
2645 );
2646 for retired in ["on", "off", "ON", "TRUE"] {
2647 assert!(
2648 parse_daemon_spec_value(&json!(retired)).is_err(),
2649 "{retired} must not be read as a daemon setting"
2650 );
2651 }
2652 }
2653 #[test]
2654 fn negative_int_rejected() {
2655 assert!(parse_daemon_spec_value(&json!(-1)).is_err());
2656 assert!(parse_daemon_spec_value(&json!(-100)).is_err());
2657 }
2658 #[test]
2659 fn float_rejected() {
2660 assert!(parse_daemon_spec_value(&json!(1.5)).is_err());
2661 }
2662 #[test]
2663 fn unknown_string_rejected() {
2664 assert!(parse_daemon_spec_value(&json!("garbage")).is_err());
2665 assert!(parse_daemon_spec_value(&json!("yes")).is_err());
2666 }
2667 #[test]
2668 fn null_rejected() {
2669 assert!(parse_daemon_spec_value(&json!(null)).is_err());
2670 }
2671 #[test]
2672 fn array_object_rejected() {
2673 assert!(parse_daemon_spec_value(&json!([1, 2])).is_err());
2674 assert!(parse_daemon_spec_value(&json!({"max": 5})).is_err());
2675 }
2676 #[test]
2677 fn round_trip_disabled() {
2678 let s = serde_json::to_value(DaemonSpec::Disabled).unwrap();
2679 assert_eq!(parse_daemon_spec_value(&s).unwrap(), DaemonSpec::Disabled);
2680 }
2681 #[test]
2682 fn round_trip_max_1_serialises_as_bool() {
2683 let s = serde_json::to_value(DaemonSpec::MaxFibers(1)).unwrap();
2684 assert_eq!(s, json!(true));
2685 assert_eq!(
2686 parse_daemon_spec_value(&s).unwrap(),
2687 DaemonSpec::MaxFibers(1)
2688 );
2689 }
2690 #[test]
2691 fn round_trip_max_n_serialises_as_int() {
2692 let s = serde_json::to_value(DaemonSpec::MaxFibers(5)).unwrap();
2693 assert_eq!(s, json!(5));
2694 assert_eq!(
2695 parse_daemon_spec_value(&s).unwrap(),
2696 DaemonSpec::MaxFibers(5)
2697 );
2698 }
2699}
2700
2701/// `traverse:` — knobs on the result-traversal layer.
2702///
2703/// The layer itself is always installed (`result:` and `metrics:` declare it
2704/// as `requires_inner`, and the composition resolver enforces that at init),
2705/// so this block only tunes behaviour that is otherwise fixed.
2706#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2707pub struct TraverseSpec {
2708 /// Base JSON Pointer (RFC 6901) applied to the result body BEFORE any
2709 /// capture is resolved, re-rooting the document.
2710 ///
2711 /// Every capture otherwise repeats the same prefix — `/value/0/x`,
2712 /// `/value/0/y` — which is the shape envelope responses force
2713 /// (`{value, status, …}`).
2714 #[serde(default, skip_serializing_if = "Option::is_none")]
2715 pub path: Option<String>,
2716 /// What to do when a declared capture resolves to nothing.
2717 #[serde(default)]
2718 pub on_missing: OnMissing,
2719}
2720
2721/// Policy for a capture that resolved to nothing.
2722#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
2723#[serde(rename_all = "lowercase")]
2724pub enum OnMissing {
2725 /// Bind `None` and continue — the historical behaviour, and the default
2726 /// so existing workloads are unaffected.
2727 #[default]
2728 Ignore,
2729 /// Log it. For a capture that is legitimately sometimes absent but whose
2730 /// absence you still want to see.
2731 Warn,
2732 /// Fail the op. For a capture whose absence means the query or the schema
2733 /// changed under you — which otherwise reads identically to "measured,
2734 /// and it was absent".
2735 Error,
2736}
2737
2738/// SRD-40b §1 schema for one synthetic-metric declaration on
2739/// an op template.
2740#[derive(Debug, Clone, Serialize, Deserialize)]
2741pub struct MetricSpec {
2742 /// Required. A Polydat expression evaluated in the op's bound
2743 /// scope. A bare binding name is the canonical form when
2744 /// the formula belongs in a `bindings:` block; any GK
2745 /// expression that produces a numeric result is also
2746 /// valid. See SRD-40b §4.
2747 pub value: String,
2748 /// Optional override of the family name. Defaults to the
2749 /// map key on `ParsedOp.metrics`. SRD-40b §1.
2750 #[serde(default, skip_serializing_if = "Option::is_none")]
2751 pub family: Option<String>,
2752 /// Optional metric type. Defaults to `Gauge` per SRD-40b §1.
2753 #[serde(default, skip_serializing_if = "Option::is_none")]
2754 pub kind: Option<MetricKind>,
2755 /// Optional OpenMetrics unit suffix (`ms`, `bytes`, …).
2756 /// When set, lands in BOTH the family-name suffix and the
2757 /// `metric_family.unit` column per SRD-40a §4.3.
2758 #[serde(default, skip_serializing_if = "Option::is_none")]
2759 pub unit: Option<String>,
2760 /// Optional generation-time numeric sanitiser using
2761 /// Excel-style hash patterns (`#.##`, `0.000`, etc.).
2762 /// Translated at registration time into a round op that
2763 /// runs before the value is recorded on the instrument;
2764 /// storage holds the sanitised number. SRD-40b §1.
2765 #[serde(default, skip_serializing_if = "Option::is_none")]
2766 pub format: Option<String>,
2767 /// Optional dimensional placement: dimension name → a Polydat
2768 /// expression producing that dimension's value for this sample.
2769 ///
2770 /// A metric identity is its label set with the family name promoted
2771 /// into it, a closed 1:1 association. `cell:` therefore does not
2772 /// attach a label to a sample — it selects the dimensional CELL the
2773 /// sample belongs to, REFINING the identity its registration site
2774 /// already composes. One value per cell, one family per cell, and the
2775 /// existing duplicate-family check keeps working unchanged.
2776 ///
2777 /// `BTreeMap` so synthesis order is deterministic: the coordinate's
2778 /// rendering is what keys a cell, and a map that iterated differently
2779 /// between runs would key the same coordinate two ways.
2780 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
2781 pub cell: std::collections::BTreeMap<String, String>,
2782}
2783
2784/// A dimension a scope introduces: the label NAME whose values arrive from
2785/// data, declared once at the tier that owns it.
2786///
2787/// The name is a structural declaration; only the value varies per cell.
2788/// `Component::attach` enforces the same rule on the runtime tree — a label
2789/// name is owned by exactly one tier and inherited downward — so declaring
2790/// the name here is what lets that be checked against the program before a
2791/// cycle runs, rather than surfacing as an attach-time panic.
2792#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2793pub struct DimensionSpec {
2794 /// Value type. `str` today — label values are strings, and a
2795 /// dimension whose values came from a float would key cells on
2796 /// formatting rather than on identity.
2797 #[serde(default)]
2798 pub value_type: DimensionType,
2799}
2800
2801/// Declared value type of a [`DimensionSpec`].
2802#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
2803#[serde(rename_all = "lowercase")]
2804pub enum DimensionType {
2805 #[default]
2806 Str,
2807}
2808
2809/// Metric type discriminator. SRD-40b §1.
2810#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2811#[serde(rename_all = "lowercase")]
2812pub enum MetricKind {
2813 /// Current-state observation; per-cycle `set(value)`.
2814 /// Default per SRD-40b §1.
2815 Gauge,
2816 /// Distribution sample; per-cycle `record(value)`.
2817 Histogram,
2818 /// Monotonic running total; per-cycle `inc_by(value)`.
2819 Counter,
2820}
2821
2822impl Default for MetricKind {
2823 /// SRD-40b §1: gauge is the default — synthetic values are
2824 /// most often current-state observations.
2825 fn default() -> Self {
2826 MetricKind::Gauge
2827 }
2828}
2829
2830/// SRD-66 result-bindings declaration. Vari-structured to
2831/// match the three YAML shapes the user can write:
2832///
2833/// - **String**: a multi-line Polydat source block. Each
2834/// `<name> := <expr>` assignment declares one result wire.
2835/// - **List**: a sequence of nested `ResultSpec`s; each
2836/// element processes in order and contributes its
2837/// declarations.
2838/// - **Map**: named-key short-forms (`count`, `ok`,
2839/// path-expr, or any other string treated as a GK
2840/// expression). Map shape additionally produces a
2841/// composite-map wire (deferred — see Push 2 follow-ups).
2842///
2843/// SRD-40b §5.1's mapping form is preserved as the map
2844/// shape with two refinements: any non-built-in non-path
2845/// string is a Polydat expression (no `(`-detector magic), and
2846/// the composite-map output is added.
2847#[derive(Debug, Clone, Serialize, Deserialize)]
2848#[serde(untagged)]
2849pub enum ResultSpec {
2850 /// Polydat source block — one or more `<name> := <expr>`
2851 /// assignments separated by newlines. The pre-bound
2852 /// wires (`body`, `count`, `ok`, captures) are
2853 /// available; references resolve via the standard
2854 /// closure-binding rule (polydat module matter detects
2855 /// linkages).
2856 String(String),
2857 /// Sequence of fragments. Each element is itself a
2858 /// `ResultSpec` (string or map; nested lists are parsed
2859 /// but unconventional). Fragments concatenate into one
2860 /// result-bindings scope; key collisions across map-
2861 /// shape fragments are a hard error.
2862 List(Vec<ResultSpec>),
2863 /// Named-key short-forms. Each value is one of:
2864 /// `"count"`, `"ok"`, a path expression (no parens), or
2865 /// any other string treated as a Polydat expression. Map
2866 /// shape also produces a composite-map wire keyed by
2867 /// the YAML keys.
2868 Map(std::collections::BTreeMap<String, String>),
2869}
2870
2871/// Legacy alias for backwards compatibility during Push 2.
2872/// Drops once every consumer migrates to `ResultSpec`.
2873pub type ResultWireSpec = LegacyResultWireSpec;
2874
2875#[derive(Debug, Clone, Serialize, Deserialize)]
2876#[serde(untagged)]
2877pub enum LegacyResultWireSpec {
2878 String(String),
2879 Object {
2880 source: String,
2881 #[serde(default, skip_serializing_if = "Option::is_none")]
2882 default: Option<String>,
2883 },
2884}
2885
2886impl LegacyResultWireSpec {
2887 pub fn source(&self) -> &str {
2888 match self {
2889 LegacyResultWireSpec::String(s) => s,
2890 LegacyResultWireSpec::Object { source, .. } => source,
2891 }
2892 }
2893}
2894
2895impl ResultSpec {
2896 /// Walk the spec tree (handling list-shape recursion)
2897 /// and yield every (wire-name, source-expr) pair the
2898 /// spec ultimately declares.
2899 ///
2900 /// For map-shape entries, the source is whatever the
2901 /// user wrote (`count` / `ok` / path-expr / Polydat expr).
2902 /// For string-shape entries, the source is the entire
2903 /// Polydat block — the caller compiles it as a unit and
2904 /// extracts wire names from the LHS of each `:=`
2905 /// assignment.
2906 pub fn walk_fragments<F: FnMut(ResultFragment<'_>)>(&self, mut on: F) {
2907 self.walk_fragments_inner(&mut on);
2908 }
2909
2910 fn walk_fragments_inner<F: FnMut(ResultFragment<'_>)>(&self, on: &mut F) {
2911 match self {
2912 ResultSpec::String(s) => on(ResultFragment::Source(s)),
2913 ResultSpec::List(items) => {
2914 for item in items {
2915 item.walk_fragments_inner(on);
2916 }
2917 }
2918 ResultSpec::Map(entries) => {
2919 for (name, source) in entries {
2920 on(ResultFragment::Named { name, source });
2921 }
2922 }
2923 }
2924 }
2925
2926 /// True when the spec declares no wires. Used by the
2927 /// wrapper-trigger to skip wrapping when `result:` was
2928 /// explicitly empty.
2929 pub fn is_empty(&self) -> bool {
2930 match self {
2931 ResultSpec::String(s) => s.trim().is_empty(),
2932 ResultSpec::List(items) => items.iter().all(|i| i.is_empty()),
2933 ResultSpec::Map(entries) => entries.is_empty(),
2934 }
2935 }
2936}
2937
2938/// One step of `ResultSpec::walk_fragments`. Either a
2939/// string-shape source block (compile as a Polydat module) or a
2940/// map-shape `(name, source)` pair (compile as a single
2941/// `name := source` binding).
2942pub enum ResultFragment<'a> {
2943 Source(&'a str),
2944 Named { name: &'a str, source: &'a str },
2945}
2946
2947impl ParsedOp {
2948 /// Create a minimal ParsedOp with just a name and stmt.
2949 pub fn simple(name: &str, stmt: &str) -> Self {
2950 let mut op = HashMap::new();
2951 op.insert(
2952 "stmt".to_string(),
2953 serde_json::Value::String(stmt.to_string()),
2954 );
2955 Self {
2956 traverse: None,
2957 name: name.to_string(),
2958 description: None,
2959 op,
2960 bindings: BindingsDef::default(),
2961 params: HashMap::new(),
2962 tags: HashMap::new(),
2963 condition: None,
2964 delay: None,
2965 metrics: HashMap::new(),
2966 cell: std::collections::BTreeMap::new(),
2967 result: None,
2968 wrappers: None,
2969 captures: Vec::new(),
2970 abstract_interface: None,
2971 interface_bound: false,
2972 daemon: DaemonSpec::Disabled,
2973 daemon_cancel_grace_ms: None,
2974 while_cond: None,
2975 rate: None,
2976 }
2977 }
2978}