Skip to main content

nmbrs_workload/
parse.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! YAML workload parser and normalizer.
5//!
6//! Parses a YAML workload definition and normalizes all shorthand
7//! forms into the canonical `ParsedOp` model.
8
9use crate::model::{
10    BindingsDef, ContinueIfSpec, MetricSpec, ParsedOp, ScenarioNode, ScopeLevel, StopConditionSpec,
11    Workload, WorkloadPhase,
12};
13use crate::template::expand_templates;
14use polydat::iteration::comprehension::Comprehension;
15use polydat::iteration::comprehension::spec::{ComprehensionSpec, ForSpec, parse_inline};
16use serde_json::Value as JVal;
17use std::collections::HashMap;
18
19/// Parse a YAML workload string into a normalized Workload.
20///
21/// In-memory entry point: callers that have already resolved the
22/// source text. **Rejects `extends:`** because there is no
23/// resolution context for the relative path (no including-file
24/// directory). Callers that need `extends:` support must use
25/// [`parse_workload_from_path`].
26pub fn parse_workload(
27    yaml_source: &str,
28    params: &HashMap<String, String>,
29) -> Result<Workload, String> {
30    // Stage 1: TEMPLATE expansion
31    let expanded = expand_templates(yaml_source, params);
32
33    // Stage 2: Parse YAML into generic Value
34    let mut doc: JVal =
35        serde_yaml::from_str(&expanded).map_err(|e| format!("YAML parse error: {e}"))?;
36
37    // SRD-72: `extends:` requires a resolution context. The
38    // text-only entry point has no including-file directory, so
39    // a top-level `extends:` here is unresolvable. Direct the
40    // caller to `parse_workload_from_path` instead.
41    if doc.get("extends").is_some() {
42        return Err(
43            "workload declares `extends:` but parse_workload was called \
44             without a file path; use parse_workload_from_path instead"
45                .to_string(),
46        );
47    }
48
49    // Stage 2.5: op templates. Every op that `uses:` a template becomes
50    // the template's body with its own keys folded in, and
51    // `op_templates:` leaves the document, so every later stage sees
52    // ordinary ops (see `crate::op_templates`). After the `extends:`
53    // check: a library's templates reach a workload only through the
54    // merged document.
55    let instantiated = crate::op_templates::instantiate(
56        doc.as_object_mut()
57            .ok_or("workload must be a YAML mapping")?,
58    )?;
59
60    let obj = doc.as_object().ok_or("workload must be a YAML mapping")?;
61
62    // Stage 3: Extract top-level fields
63    let description = obj
64        .get("description")
65        .and_then(|v| v.as_str())
66        .map(|s| s.to_string());
67
68    let mut scenario_parse_errors: Vec<String> = Vec::new();
69    let mut scenarios = parse_scenarios(obj.get("scenarios"), &mut scenario_parse_errors);
70    // Resolve `scenario: <name>` includes after every scenario
71    // has been parsed so forward references work and cycles are
72    // detected with the full graph available.
73    resolve_scenario_includes(&mut scenarios)?;
74
75    let doc_bindings = extract_bindings(obj.get("bindings"));
76    let doc_params = extract_value_map(obj.get("params"));
77    let doc_tags = extract_string_map(obj.get("tags"));
78
79    // Stage 4: Parse ops from blocks or top-level
80    let mut all_ops = Vec::new();
81
82    // SRD-13f Push D: workload-level `bindings:` live ONLY on
83    // `Workload.bindings` and compile directly to the
84    // workload-root Polydat Kernel. They no longer fold into ops at
85    // parse time — descendant ops resolve workload-level wires
86    // through the Polydat Kernel chain (workload-root → ... → op
87    // kernel) via the SRD-13f cell-on-outputs cascade. So we
88    // pass an empty `BindingsDef` to every op-producing path
89    // here: block-level YAML bindings (parse_blocks) are the
90    // only remaining parser-time "sugar" that expands into ops.
91    if let Some(blocks_val) = obj.get("blocks") {
92        parse_blocks(blocks_val, &doc_params, &doc_tags, &mut all_ops)?;
93    }
94
95    // Top-level ops (no blocks): no block sugar to inline. A
96    // workload declares its ops one way — top-level ops alongside
97    // `blocks:` are an error, never silently dropped.
98    if let Some(ops_val) = op_collection(obj, "workload")? {
99        if obj.contains_key("blocks") {
100            return Err(
101                "workload: top-level `ops:`/`op:` and `blocks:` both given; \
102                 put these ops in a block, or drop `blocks:`"
103                    .to_string(),
104            );
105        }
106        parse_ops_field(
107            &ops_val,
108            "block0",
109            &BindingsDef::default(),
110            &doc_params,
111            &doc_tags,
112            &mut all_ops,
113        )?;
114    }
115
116    // Stage 5: Parse phases
117    let (mut phases, phase_order) = parse_phases(obj.get("phases"), &doc_params, &doc_tags)?;
118
119    // Stage 6: Auto-tag all ops (top-level and phase inline ops)
120    for op in &mut all_ops {
121        if !op.tags.contains_key("name") {
122            op.tags.insert("name".to_string(), op.name.clone());
123        }
124        if !op.tags.contains_key("op") {
125            op.tags.insert("op".to_string(), op.name.clone());
126        }
127    }
128
129    // Stage 6.5 (SRD-108 Part A, completing SRD-20): a phase with
130    // no inline ops and a `tags:` selector resolves its ops HERE,
131    // from the merged document's top-level/block op pool. Parse
132    // time is deliberate: everything downstream — synthesis,
133    // validation, the SRD-107 config digest — sees a phase with
134    // ordinary resolved ops, exactly as if they were inline. This
135    // is the ad-hoc composition seam: an implementation workload
136    // `extends:` a blueprint and contributes tagged block ops
137    // that these selectors pick up.
138    for (phase_name, phase) in phases.iter_mut() {
139        let Some(selector) = phase.tags.clone() else {
140            continue;
141        };
142        if !phase.ops.is_empty() {
143            return Err(format!(
144                "phase '{phase_name}' declares both inline ops and a \
145                 `tags:` selector — a phase has exactly one source of \
146                 ops. Drop the selector or move the ops into a tagged \
147                 block."
148            ));
149        }
150        let mut selected = crate::tags::TagFilter::filter_ops(&all_ops, &selector)
151            .map_err(|e| format!("phase '{phase_name}' `tags:` selector: {e}"))?;
152        if selected.is_empty() {
153            return Err(format!(
154                "phase '{phase_name}' `tags:` selector '{selector}' \
155                 matched no ops ({} in the workload's op pool). A \
156                 selector-only phase must bind at least one op — \
157                 check the tag vocabulary against the blocks this \
158                 workload (or its extends chain) declares.",
159                all_ops.len()
160            ));
161        }
162        // Mirror the inline-op auto-tagging: selected clones gain
163        // the `phase` tag their inline siblings get at parse.
164        for op in &mut selected {
165            op.tags.insert("phase".to_string(), phase_name.clone());
166        }
167        phase.ops = selected;
168    }
169
170    // Stage 7: Resolve workload parameters
171    // Priority: CLI params > workload defaults > env vars
172    let yaml_params = extract_string_map(obj.get("params"));
173
174    // Stage 7.5: ops instantiated from op templates carry the
175    // template's interface as a BOUND interface; every `needs` wire
176    // must be supplied here, and synthesis type-checks them.
177    {
178        let declared: Vec<String> = yaml_params.keys().cloned().collect();
179        crate::op_templates::bind_and_check(
180            &instantiated,
181            &mut phases,
182            &mut all_ops,
183            &declared,
184            &doc_bindings,
185            &scenarios,
186        )?;
187    }
188    let mut resolved_params = HashMap::new();
189    for (key, default_value) in &yaml_params {
190        let resolved = if let Some(cli_value) = params.get(key) {
191            // CLI override — coerce to the declared default's type. The
192            // workload default is the source of truth for type, so a
193            // numeric default makes a suffixed override (`10m`, `4Ki`)
194            // resolve numerically rather than landing as a string; a
195            // non-numeric default leaves the override untouched.
196            crate::magnitude::coerce_param_override(default_value, cli_value)
197        } else if let Some(env_name) = default_value.strip_prefix("env:") {
198            // Environment variable lookup
199            std::env::var(env_name).unwrap_or_else(|_| default_value.clone())
200        } else {
201            default_value.clone()
202        };
203        resolved_params.insert(key.clone(), resolved);
204    }
205    // Also include CLI params that aren't in the workload defaults
206    // (ad-hoc parameters passed on the command line)
207    for (key, value) in params {
208        if !resolved_params.contains_key(key) {
209            resolved_params.insert(key.clone(), value.clone());
210        }
211    }
212
213    let declared_params: Vec<String> = yaml_params.keys().cloned().collect();
214
215    // Legacy `summary:` and `plot:` keys: removed, no shim.
216    // Operators must migrate to the unified `report:` block
217    // (SRD-46). The error message names both new homes.
218    if obj.contains_key("summary") || obj.contains_key("summaries") {
219        return Err("`summary:` / `summaries:` removed; use `report:` with \
220             `table <name> ...` directives instead (SRD-46)"
221            .to_string());
222    }
223    if obj.contains_key("plot") || obj.contains_key("plots") {
224        return Err("`plot:` / `plots:` removed; use `report:` with \
225             `plot <name> ...` directives instead (SRD-46)"
226            .to_string());
227    }
228
229    // ── Construction-model enforcement gate ──
230    // The document must validate against the enumerable
231    // construction grammar (docs/guide/construction_model.md):
232    // unknown elements on closed node kinds, value-form
233    // violations, and missing required elements are load errors,
234    // reported together with their document paths. Runs on the
235    // extends-merged document, after the targeted legacy-key
236    // rejections above (their migration messages are better than
237    // a generic unknown-element finding).
238    {
239        let doc = serde_json::Value::Object(obj.clone());
240        let violations =
241            crate::construction::validate_workload(&doc, crate::construction::Mode::Complete);
242        if !violations.is_empty() {
243            let mut lines: Vec<String> = violations
244                .iter()
245                .map(|v| format!("  {}: {}", v.path, v.message))
246                .collect();
247            lines.sort();
248            return Err(format!(
249                "workload construction: {} violation(s) \
250                 (docs/guide/construction_model.md):\n{}",
251                violations.len(),
252                lines.join("\n")
253            ));
254        }
255    }
256
257    // Unified `report:` block (SRD-46) — plots, tables, defaults,
258    // groups. Parser is in `crate::report::parse_report`. The
259    // returned warnings are stashed on the Workload for
260    // strict-mode promotion downstream (SRD-15).
261    let (report, report_warnings) = if let Some(val) = obj.get("report") {
262        let parsed = crate::report::parse_report(val).map_err(|e| format!("report: {e}"))?;
263        (parsed.report, parsed.warnings)
264    } else {
265        (crate::report::Report::default(), Vec::new())
266    };
267
268    // SRD 21 §"Parameter Resolution": CLI overrides are the
269    // outermost layer. Each op has already absorbed the
270    // doc → block → op closest-wins merge for YAML-declared
271    // params; now overlay the CLI map so `nmbrs run ...
272    // concurrency=200` replaces any inherited block-level
273    // value. Workload-level `resolved_params` was already
274    // CLI-resolved above (line 66–87); this pass extends the
275    // same rule down to per-op params.
276    if !params.is_empty() {
277        for op in &mut all_ops {
278            for (key, value) in params {
279                // Same SRD-32a exclusion as the inherited-params merge: a CLI
280                // `rate=…` / `cycles=…` is a phase/activity override, not an op
281                // field — don't leak it into op params (would trip rate).
282                if ACTIVITY_PARAM_KEYS.contains(&key.as_str()) {
283                    continue;
284                }
285                op.params
286                    .insert(key.clone(), serde_json::Value::String(value.clone()));
287            }
288        }
289    }
290
291    // SRD-44 §"Resume protocol": a phase declared
292    // `checkpoint: idempotent` that lives inside a do_while /
293    // do_until loop is rejected at workload load time. The
294    // do-loop iterates the same phase many times under one
295    // checkpoint identity; checkpointing presumes each phase
296    // execution is a discrete unit, which the loop directly
297    // contradicts. Operators who really want a do-loop'd phase
298    // to skip on resume must wrap the loop with explicit
299    // identity, not lean on the phase's `checkpoint:` flag.
300    for (scenario_name, nodes) in &scenarios {
301        let mut bad: Vec<String> = Vec::new();
302        collect_idempotent_under_do_loop(nodes, false, &phases, &mut bad);
303        if !bad.is_empty() {
304            return Err(format!(
305                "scenario '{scenario_name}': phase{plural} {names} \
306                 declared `checkpoint: idempotent` while nested inside \
307                 a do_while / do_until loop. The loop iterates the \
308                 same phase identity multiple times, which contradicts \
309                 the per-execution unit checkpointing assumes. Either \
310                 remove the `checkpoint:` declaration or restructure \
311                 the loop. (SRD-44 §\"Resume protocol\".)",
312                plural = if bad.len() == 1 { "" } else { "s" },
313                names = bad.join(", "),
314            ));
315        }
316    }
317
318    // Doc-root `status_metrics:` — workload-wide default that
319    // any phase without its own `status_metrics:` inherits.
320    // Same accept-list shapes as the per-phase parser: list of
321    // strings, single string, or comma-separated string.
322    let doc_status_metrics: Vec<String> = match obj.get("status_metrics") {
323        None => Vec::new(),
324        Some(JVal::Array(items)) => items
325            .iter()
326            .filter_map(|v| v.as_str().map(|s| s.trim().to_string()))
327            .filter(|s| !s.is_empty())
328            .collect(),
329        Some(JVal::String(s)) => s
330            .split(',')
331            .map(str::trim)
332            .filter(|s| !s.is_empty())
333            .map(String::from)
334            .collect(),
335        Some(other) => {
336            return Err(format!(
337                "status_metrics: must be a list of names/patterns, a \
338             comma-separated string, or omitted; got {other:?}"
339            ));
340        }
341    };
342    if !doc_status_metrics.is_empty() {
343        for phase in phases.values_mut() {
344            if phase.status_metrics.is_empty() {
345                phase.status_metrics = doc_status_metrics.clone();
346            }
347        }
348    }
349
350    // Doc-root `readouts:` block (SRD-63 §5.0). Three
351    // accepted shapes:
352    //   A. Single scalar string  → bound at on_update.
353    //   B. Mapping of slot → name | body string.
354    //   C. Mapping of slot → list of (name | body) strings.
355    // The slot keys must match the lower-cased
356    // Event::slot_name values (`on_update`, `on_phase_end`, …).
357    // Inline body strings keep their full text — the
358    // body-grammar parser in nmbrs-runtime::readouts::parse
359    // bakes them at activity-init time.
360    let readouts = parse_readouts_block(obj.get("readouts"))?;
361
362    // SRD-83 — top-level `stop_when:` (workload-shell conditions), same
363    // shape as the per-phase block.
364    let stop_when: Vec<crate::model::StopConditionSpec> = match obj.get("stop_when") {
365        Some(v) => serde_json::from_value(v.clone())
366            .map_err(|e| format!("invalid top-level `stop_when` block: {e}"))?,
367        None => Vec::new(),
368    };
369    // SRD-83 Part 5 — the effect verb is a closed vocabulary; an unknown
370    // verb would silently resolve to the shell default at the trip site.
371    for sc in &stop_when {
372        sc.validate()
373            .map_err(|e| format!("top-level `stop_when`: {e}"))?;
374    }
375
376    // SRD-108 Part B — `implements:` names the blueprint this
377    // document provides op bodies for. A non-string value is
378    // rejected rather than ignored.
379    let implements: Option<String> = match obj.get("implements") {
380        Some(v) => Some(
381            v.as_str()
382                .ok_or_else(|| {
383                    format!("`implements:` must be a workload reference string, got {v}")
384                })?
385                .to_string(),
386        ),
387        None => None,
388    };
389
390    // SRD-106 Part 3 — `stick_session:` top-level bool. A non-bool
391    // value is rejected rather than ignored (never-ignore-silently).
392    let stick_session: Option<bool> = match obj.get("stick_session") {
393        Some(v) => Some(
394            v.as_bool()
395                .ok_or_else(|| format!("`stick_session:` must be a boolean, got {v}"))?,
396        ),
397        None => None,
398    };
399
400    Ok(Workload {
401        description,
402        scenarios,
403        ops: all_ops,
404        bindings: doc_bindings,
405        params: resolved_params,
406        phases,
407        phase_order,
408        declared_params,
409        stop_when,
410        report,
411        report_warnings,
412        scenario_parse_errors,
413        resolution_warnings: Vec::new(),
414        status_metrics: doc_status_metrics,
415        readouts,
416        wrappers: None,
417        implements,
418        stick_session,
419    })
420}
421
422/// Path-based entry point: load a workload YAML from disk,
423/// follow its `extends:` chain (SRD-72), and parse the merged
424/// result into a [`Workload`].
425///
426/// `path` MUST be an existing file. Relative paths are resolved
427/// against the cwd before being passed to the loader.
428pub fn parse_workload_from_path(
429    path: &std::path::Path,
430    params: &HashMap<String, String>,
431) -> Result<Workload, String> {
432    let (merged_yaml, resolution_warnings) = crate::extends::load_and_merge(path)?;
433    let mut workload = parse_workload(&merged_yaml, params)?;
434    // Reference-resolution warnings ride the same surfacing
435    // channel as report warnings: stashed here, logged (or
436    // strict-promoted) by the runner.
437    workload.resolution_warnings.extend(resolution_warnings);
438    Ok(workload)
439}
440
441/// Parse the workload's `readouts:` block per SRD-63 §5.0.
442/// Returns the populated bindings struct or a load-time
443/// error.
444fn parse_readouts_block(value: Option<&JVal>) -> Result<crate::model::ReadoutsBindings, String> {
445    use crate::model::ReadoutsBindings;
446    let mut out = ReadoutsBindings::default();
447    let Some(value) = value else {
448        return Ok(out);
449    };
450
451    // Form A — scalar shorthand for `on_update`.
452    if let JVal::String(s) = value {
453        let trimmed = s.trim();
454        if trimmed.is_empty() {
455            return Ok(out);
456        }
457        out.on_update.push(trimmed.to_string());
458        return Ok(out);
459    }
460
461    // Forms B / C — mapping with slot keys.
462    let JVal::Object(map) = value else {
463        return Err(format!(
464            "readouts: must be a scalar (sugar for on_update) or a mapping \
465             of slot name → readout body; got {value:?}"
466        ));
467    };
468    for (key, val) in map {
469        let bodies: Vec<String> = match val {
470            JVal::String(s) => vec![s.trim().to_string()],
471            JVal::Array(items) => items
472                .iter()
473                .map(|item| match item {
474                    JVal::String(s) => Ok(s.trim().to_string()),
475                    other => Err(format!(
476                        "readouts.{key}: list entries must be strings; got {other:?}"
477                    )),
478                })
479                .collect::<Result<Vec<_>, _>>()?,
480            JVal::Null => continue,
481            other => {
482                return Err(format!(
483                    "readouts.{key}: must be a string or list of strings; got {other:?}"
484                ));
485            }
486        };
487        let bodies: Vec<String> = bodies.into_iter().filter(|s| !s.is_empty()).collect();
488        // Wildcard expansion (SRD-63 §4.1.1). The yaml key
489        // can match a family rather than a single slot:
490        //   `each_*`    → on_each_start + on_each_end
491        //   `phase_*`   → on_phase_start + on_phase_end
492        //   `scope_*`   → on_scope_start + on_scope_end
493        //   `session_*` → on_session_start + on_session_end
494        //   `*`         → every slot
495        // Wildcard bindings are duplicated into each
496        // matching slot so the binder's resolution doesn't
497        // need a separate wildcard list. Render order:
498        // explicit bindings first in declaration order
499        // (handled by parser top-down), then any wildcard
500        // expansions appended.
501        let target_slots: Vec<&str> = match key.as_str() {
502            "on_session_start" => vec!["on_session_start"],
503            "on_session_end" => vec!["on_session_end"],
504            "on_phase_start" => vec!["on_phase_start"],
505            "on_phase_end" => vec!["on_phase_end"],
506            "on_each_start" => vec!["on_each_start"],
507            "on_each_end" => vec!["on_each_end"],
508            "on_scope_start" => vec!["on_scope_start"],
509            "on_scope_end" => vec!["on_scope_end"],
510            "on_update" => vec!["on_update"],
511            "session_*" => vec!["on_session_start", "on_session_end"],
512            "phase_*" => vec!["on_phase_start", "on_phase_end"],
513            "each_*" => vec!["on_each_start", "on_each_end"],
514            "scope_*" => vec!["on_scope_start", "on_scope_end"],
515            "*" => vec![
516                "on_session_start",
517                "on_session_end",
518                "on_phase_start",
519                "on_phase_end",
520                "on_each_start",
521                "on_each_end",
522                "on_scope_start",
523                "on_scope_end",
524                "on_update",
525            ],
526            other => {
527                return Err(format!(
528                    "readouts: unknown slot '{other}'. Known: \
529                 on_session_start/end, on_phase_start/end, \
530                 on_each_start/end, on_scope_start/end, on_update; \
531                 wildcards: each_*, phase_*, scope_*, session_*, *"
532                ));
533            }
534        };
535        for slot in target_slots {
536            let target: &mut Vec<String> = match slot {
537                "on_session_start" => &mut out.on_session_start,
538                "on_session_end" => &mut out.on_session_end,
539                "on_phase_start" => &mut out.on_phase_start,
540                "on_phase_end" => &mut out.on_phase_end,
541                "on_each_start" => &mut out.on_each_start,
542                "on_each_end" => &mut out.on_each_end,
543                "on_scope_start" => &mut out.on_scope_start,
544                "on_scope_end" => &mut out.on_scope_end,
545                "on_update" => &mut out.on_update,
546                _ => unreachable!(),
547            };
548            target.extend(bodies.iter().cloned());
549        }
550    }
551    Ok(out)
552}
553
554/// Walk a scenario tree and collect names of phases declared
555/// `checkpoint: idempotent` that live under a `do_while` /
556/// `do_until` ancestor. Used by the workload-load validation
557/// step above (SRD-44).
558fn collect_idempotent_under_do_loop(
559    nodes: &[crate::model::ScenarioNode],
560    in_do_loop: bool,
561    phases: &HashMap<String, crate::model::WorkloadPhase>,
562    out: &mut Vec<String>,
563) {
564    use crate::model::ScenarioNode;
565    for node in nodes {
566        match node {
567            ScenarioNode::Phase(name) => {
568                if in_do_loop {
569                    let idempotent = phases
570                        .get(name)
571                        .and_then(|p| p.checkpoint.as_ref())
572                        .map(|c| c.idempotent)
573                        .unwrap_or(false);
574                    if idempotent {
575                        out.push(format!("'{name}'"));
576                    }
577                }
578            }
579            ScenarioNode::DoWhile { children, .. } | ScenarioNode::DoUntil { children, .. } => {
580                collect_idempotent_under_do_loop(children, true, phases, out);
581            }
582            ScenarioNode::Comprehension { children, .. } => {
583                collect_idempotent_under_do_loop(children, in_do_loop, phases, out);
584            }
585            ScenarioNode::IncludedScenario { children, .. } => {
586                collect_idempotent_under_do_loop(children, in_do_loop, phases, out);
587            }
588            ScenarioNode::Bindings { children, .. } => {
589                collect_idempotent_under_do_loop(children, in_do_loop, phases, out);
590            }
591        }
592    }
593}
594
595/// Parse a YAML source into just the list of normalized ParsedOps.
596/// Normalise an op-level `if:` clause so callers can write
597/// expressions naturally. The downstream pipeline expects
598/// the condition to be either a binding-name reference
599/// (`{name}`) or an inline expression (`{{expr}}`). When
600/// the operator writes a bare expression like
601/// `cql_dialect == 'cass'`, that doesn't match either
602/// form and the conditional dispenser fails at init when
603/// it tries to look up a Polydat binding literally named
604/// `cql_dialect == 'cass'`.
605///
606/// Heuristic: if the trimmed value already starts with `{`
607/// (any braced form), or is a plain identifier
608/// (`[A-Za-z_][A-Za-z0-9_]*`), pass through unchanged.
609/// Otherwise treat as an inline expression and wrap with
610/// `{{...}}` so the existing inline-expression machinery
611/// in `nmbrs-runtime::scope::build_scope` synthesises a
612/// hidden binding (`__expr_N := <expr>`) and rewrites the
613/// condition to reference it.
614pub fn normalize_condition_clause(s: &str) -> String {
615    let trimmed = s.trim();
616    if trimmed.is_empty() {
617        return trimmed.to_string();
618    }
619    // Already in any braced form — pass through. The
620    // downstream extractor handles `{{expr}}`, `{:=expr:=}`,
621    // `{name}`, and `{expr-with-operators}` itself.
622    if trimmed.starts_with('{') {
623        return trimmed.to_string();
624    }
625    // Plain identifier — leave as-is so the legacy "if:
626    // points at a single binding name" form keeps working.
627    let is_plain_ident = trimmed
628        .chars()
629        .next()
630        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
631        && trimmed
632            .chars()
633            .all(|c| c.is_ascii_alphanumeric() || c == '_');
634    if is_plain_ident {
635        return trimmed.to_string();
636    }
637    // Anything else (operators, quotes, parens, …) → wrap
638    // as an inline expression.
639    format!("{{{{{trimmed}}}}}")
640}
641
642pub fn parse_ops(yaml_source: &str) -> Result<Vec<ParsedOp>, String> {
643    let workload = parse_workload(yaml_source, &HashMap::new())?;
644    Ok(workload.ops)
645}
646
647// -----------------------------------------------------------------
648// Scenarios
649// -----------------------------------------------------------------
650
651fn parse_scenarios(
652    val: Option<&JVal>,
653    errors: &mut Vec<String>,
654) -> HashMap<String, Vec<ScenarioNode>> {
655    let mut scenarios = HashMap::new();
656    let Some(val) = val else {
657        return scenarios;
658    };
659    let Some(obj) = val.as_object() else {
660        return scenarios;
661    };
662
663    for (scenario_name, steps_val) in obj {
664        let nodes = parse_scenario_nodes_with_errors(steps_val, scenario_name, errors);
665        scenarios.insert(scenario_name.clone(), nodes);
666    }
667    scenarios
668}
669
670/// Wrapper around the legacy `parse_scenario_nodes` that
671/// accumulates `unknown-key` errors against a per-call sink.
672/// Used by `parse_scenarios` so the top-level builder can
673/// inspect the result and refuse to dispatch a malformed
674/// workload (per "Never Ignore Silently"). The legacy
675/// non-erroring shape is still exposed for the in-file
676/// recursive callers that pre-date the error contract;
677/// those paths quietly drop the unknown-key information,
678/// but the top-level entry now sees it.
679fn parse_scenario_nodes_with_errors(
680    val: &JVal,
681    scenario_name: &str,
682    errors: &mut Vec<String>,
683) -> Vec<ScenarioNode> {
684    match val {
685        JVal::Array(arr) => arr
686            .iter()
687            .flat_map(|item| parse_scenario_nodes_with_errors(item, scenario_name, errors))
688            .collect(),
689        JVal::Object(obj) => {
690            if has_recognised_scenario_key(obj) {
691                return parse_scenario_nodes(val);
692            }
693            // No recognized scenario-node key. Two legitimate
694            // shapes can land here:
695            //
696            // 1. **Legacy command-string form** — `{ name: "run
697            //    ..." }`. Each entry maps a step name to a CLI
698            //    command string; the catch-all in
699            //    `parse_scenario_nodes` produces one
700            //    `ScenarioNode::Phase(<name>)` per key. The
701            //    values are always strings (CLI command lines).
702            //    Accepted.
703            //
704            // 2. **Malformed unknown-key node** — `{ iterate: {
705            //    phases: [...] } }`, `{ for_with_typo: ... }`,
706            //    etc. The value is a map or array, which means
707            //    the author was trying to express structure the
708            //    parser doesn't understand. Reject loudly per
709            //    the project's "Never Ignore Silently" rule —
710            //    silently dropping these used to cause
711            //    confusing downstream errors (`phase 'iterate'
712            //    not found` masking a typoed `for_each` key).
713            let bad: Vec<&String> = obj
714                .iter()
715                .filter(|(_, v)| !matches!(v, JVal::String(_) | JVal::Null))
716                .map(|(k, _)| k)
717                .collect();
718            if !bad.is_empty() {
719                let bad_names: Vec<&str> = bad.iter().map(|s| s.as_str()).collect();
720                errors.push(format!(
721                    "scenario '{scenario_name}': unrecognised scenario-node key(s) \
722                     {bad_names:?} carry non-string values (a map or array). \
723                     Expected one of: `for_each` / `for`, `scenarios`, \
724                     `for_combinations`, `do_while`, `do_until`, `bindings`, \
725                     `set`, `scenario`. (The legacy `name: \"run ...\"` \
726                     command-string form is still accepted when the value is \
727                     a plain string.)"
728                ));
729                return Vec::new();
730            }
731            // All values are strings — legacy command-string
732            // form. Route through the legacy catch-all.
733            parse_scenario_nodes(val)
734        }
735        _ => parse_scenario_nodes(val),
736    }
737}
738
739/// True iff this scenario-node object has at least one of the
740/// recognized keys handled by `parse_scenario_nodes`. Used by
741/// the error-aware wrapper to distinguish "malformed node"
742/// (no recognized key) from "legitimate node" before the
743/// silent-catchall in the legacy path can fire.
744fn has_recognised_scenario_key(obj: &serde_json::Map<String, JVal>) -> bool {
745    crate::vocab::scenario_node_keys()
746        .iter()
747        .any(|k| obj.contains_key(*k))
748}
749
750/// Emit the polydat RHS for a scenario `set:` value. A **bare identifier is a
751/// wire REFERENCE**, consistent with comprehension r-values (SRD-18f): so
752/// `set: { x: mnc }` binds `mnc`'s value, and an unresolved bare name is a
753/// hard error at scope synthesis. A number/bool is that literal; a YAML
754/// sequence is a list (of references / literals). A STRING literal must be
755/// written explicitly as a polydat-quoted scalar — `'"verbose"'` in YAML —
756/// because the pipeline's serde round-trips strip ordinary YAML quotes,
757/// leaving a bare word indistinguishable from a reference.
758fn emit_set_value_literal(value: &JVal) -> String {
759    match value {
760        JVal::Number(n) => n.to_string(),
761        JVal::Bool(b) => b.to_string(),
762        JVal::Null => "\"\"".to_string(),
763        // A YAML sequence is a list literal; its elements are references
764        // (bare) or literals.
765        JVal::Array(elems) => {
766            let parts: Vec<String> = elems.iter().map(emit_set_array_element).collect();
767            format!("[{}]", parts.join(", "))
768        }
769        JVal::String(s) => {
770            let t = s.trim();
771            if is_polydat_quoted_string(t) {
772                // Explicit polydat string literal (`'"verbose"'` in YAML).
773                t.to_string()
774            } else if crate::bindpoints::is_bare_identifier(t) {
775                // Bare identifier ⇒ a wire reference (unquoted; polydat
776                // resolves it against the in-scope chain).
777                t.to_string()
778            } else {
779                // Free text / `{name}` templates ⇒ a string literal.
780                let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
781                format!("\"{escaped}\"")
782            }
783        }
784        other => {
785            let escaped = other.to_string().replace('\\', "\\\\").replace('"', "\\\"");
786            format!("\"{escaped}\"")
787        }
788    }
789}
790
791/// One element of a `set:` sequence value: a bare-identifier element is a
792/// reference (unquoted), a number/bool is its literal, any other string is a
793/// quoted string element.
794fn emit_set_array_element(e: &JVal) -> String {
795    match e {
796        JVal::String(s) if crate::bindpoints::is_bare_identifier(s.trim()) => s.trim().to_string(),
797        JVal::Number(n) => n.to_string(),
798        JVal::Bool(b) => b.to_string(),
799        JVal::String(s) => {
800            let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
801            format!("\"{escaped}\"")
802        }
803        other => other.to_string(),
804    }
805}
806
807/// Recursively parse scenario nodes from YAML.
808///
809/// Handles:
810/// - String: phase name
811/// - Object with `for_each` + `phases`: for_each loop (phases parsed recursively)
812/// - Array: list of nodes
813///
814/// Map a `ScopeLevel` keyword (the `each:` vocabulary) from YAML text.
815fn parse_scope_level(s: &str) -> Option<ScopeLevel> {
816    match s {
817        "self" => Some(ScopeLevel::SelfScope),
818        "op" => Some(ScopeLevel::Op),
819        "phase" => Some(ScopeLevel::Phase),
820        "scenario" => Some(ScopeLevel::Scenario),
821        "workload" => Some(ScopeLevel::Workload),
822        _ => None,
823    }
824}
825
826/// SRD-101 — parse a `continue_if:` value into a [`ContinueIfSpec`]. Accepts
827/// the short string form (`continue_if: "end_of(p) <= max"` → `each: scenario`)
828/// and the long map form (`{ when, each }`, where `each` is a single level or a
829/// list). `each` defaults to `scenario` (the enclosing sweep).
830/// Render a JSON scalar (string or number) as a duration string for the
831/// `tries: {backoff: {min, max}}` map. A string passes through (`"100ms"`);
832/// a bare number becomes its decimal text (`100` → `"100"`, taken as ms by
833/// the runtime's duration parser). Non-scalars yield `None`.
834fn json_scalar_to_dur_string(v: &JVal) -> Option<String> {
835    match v {
836        JVal::String(s) => Some(s.clone()),
837        JVal::Number(n) => Some(n.to_string()),
838        _ => None,
839    }
840}
841
842fn parse_continue_if(val: Option<&JVal>) -> Option<ContinueIfSpec> {
843    match val? {
844        JVal::String(when) => Some(ContinueIfSpec {
845            when: when.clone(),
846            each: vec![ScopeLevel::Scenario],
847        }),
848        JVal::Object(map) => {
849            let when = map.get("when").and_then(|v| v.as_str())?.to_string();
850            let each: Vec<ScopeLevel> = match map.get("each") {
851                Some(JVal::String(s)) => parse_scope_level(s).into_iter().collect(),
852                Some(JVal::Array(arr)) => arr
853                    .iter()
854                    .filter_map(|v| v.as_str().and_then(parse_scope_level))
855                    .collect(),
856                _ => Vec::new(),
857            };
858            let each = if each.is_empty() {
859                vec![ScopeLevel::Scenario]
860            } else {
861                each
862            };
863            Some(ContinueIfSpec { when, each })
864        }
865        _ => None,
866    }
867}
868
869fn parse_scenario_nodes(val: &JVal) -> Vec<ScenarioNode> {
870    match val {
871        JVal::String(s) => vec![ScenarioNode::Phase(s.clone())],
872        JVal::Array(arr) => arr.iter().flat_map(parse_scenario_nodes).collect(),
873        JVal::Object(obj) => {
874            let children = obj
875                .get("phases")
876                .map(parse_scenario_nodes)
877                .unwrap_or_default();
878            let counter = obj
879                .get("counter")
880                .and_then(|v| v.as_str())
881                .map(|s| s.to_string());
882
883            // `for_each` is the canonical key; `for` is accepted as
884            // a shorter synonym ("for k in 10,100" reads more
885            // naturally and matches the Polydat comprehension text
886            // grammar). Both keys are interchangeable; if both
887            // appear, `for_each` wins so misconfigured workloads
888            // don't silently change shape.
889            if let Some(for_each_val) = obj.get("for_each").or_else(|| obj.get("for")) {
890                // for_each supports three YAML shapes (string,
891                // array, object) that collapse into one of three
892                // semantic variants (Cartesian / Union / single-
893                // clause). The detection rule lives in
894                // `ComprehensionSpec::into_legacy` (and ultimately
895                // in `comprehension_from_subspaces` underneath) —
896                // single source of truth.
897                //
898                // YAML-shape → ForSpec mapping:
899                //   "x in 1, y in 2"               → Inline (string)
900                //   "x in 1, x in 2"               → Inline (string,
901                //                                    name repeat ⇒ Union)
902                //   ["x in 1", "y in 2"]           → UnionOfClauseLists
903                //                                    (one entry per
904                //                                    sub-space; name
905                //                                    repeat across
906                //                                    entries ⇒ Union;
907                //                                    no repeat ⇒
908                //                                    Cartesian after
909                //                                    flattening)
910                //   { x: "1", y: "2" }             → Inline (string,
911                //                                    assembled from
912                //                                    key=value pairs)
913                let for_spec: Option<ForSpec> = match for_each_val {
914                    JVal::String(spec) => Some(ForSpec::Inline(spec.clone())),
915                    JVal::Array(arr) => {
916                        // One sub-space per array entry. Each
917                        // entry can hold multiple comma-separated
918                        // clauses (cartesian within); cross-entry
919                        // is unioned. Wrap each entry in a
920                        // singleton inner-list so the
921                        // UnionOfClauseLists shape carries the
922                        // "one entry = one sub-space" semantic.
923                        let groups: Vec<Vec<String>> = arr
924                            .iter()
925                            .filter_map(|item| item.as_str().map(|s| vec![s.to_string()]))
926                            .collect();
927                        if groups.is_empty() {
928                            None
929                        } else {
930                            Some(ForSpec::UnionOfClauseLists(groups))
931                        }
932                    }
933                    JVal::Object(map) => {
934                        // Map form is always a single sub-space
935                        // (keys are unique). Assemble into an
936                        // inline string and route through
937                        // ForSpec::Inline.
938                        if map.is_empty() {
939                            None
940                        } else {
941                            let inline = map
942                                .iter()
943                                .map(|(k, v)| format!("{k} in {}", v.as_str().unwrap_or("")))
944                                .collect::<Vec<_>>()
945                                .join(", ");
946                            Some(ForSpec::Inline(inline))
947                        }
948                    }
949                    _ => None,
950                };
951
952                match for_spec {
953                    None => vec![],
954                    Some(r#for) => {
955                        let spec = ComprehensionSpec {
956                            r#for,
957                            // Optional `where:` key carries a
958                            // filter predicate evaluated per
959                            // emitted tuple.
960                            r#where: obj.get("where").and_then(|v| v.as_str()).map(String::from),
961                            // Optional `order:` key carries a
962                            // traversal order spec (GK text form,
963                            // e.g. "extrema/1").
964                            order: obj.get("order").and_then(|v| v.as_str()).map(String::from),
965                        };
966                        match spec.into_algebra() {
967                            Ok(comprehension) => vec![ScenarioNode::Comprehension {
968                                comprehension,
969                                children,
970                                continue_if: parse_continue_if(obj.get("continue_if")),
971                                anchor: obj
972                                    .get("anchor")
973                                    .and_then(|v| v.as_str())
974                                    .map(String::from),
975                            }],
976                            Err(e) => {
977                                eprintln!("warning: comprehension: {e}");
978                                vec![]
979                            }
980                        }
981                    }
982                }
983            } else if let Some(scenario_val) = obj.get("scenario").and_then(|v| v.as_str()) {
984                // `scenario: <name>` — logical inclusion of
985                // another scenario at this point in the tree.
986                // Children remain empty here; resolution happens
987                // post-parse via `resolve_scenario_includes`,
988                // once every scenario in the workload is known.
989                vec![ScenarioNode::IncludedScenario {
990                    name: scenario_val.to_string(),
991                    children: Vec::new(),
992                }]
993            } else if let Some(scenarios_val) = obj.get("scenarios") {
994                // `scenarios: [name, name, ...]` — plural form
995                // for composing several named scenarios at one
996                // node in the tree. Each list entry expands to
997                // its own `IncludedScenario`; resolution happens
998                // post-parse via `resolve_scenario_includes`.
999                // Reads more naturally than repeating
1000                // `- scenario: foo` for each entry; both forms
1001                // are interchangeable.
1002                //
1003                // Map / object entries (`{ scenario: foo }`) are
1004                // also accepted so a list can mix bare-string
1005                // includes with other scenario-node shapes
1006                // already supported by `parse_scenario_nodes`.
1007                match scenarios_val {
1008                    JVal::Array(arr) => arr
1009                        .iter()
1010                        .flat_map(|item| {
1011                            match item {
1012                                JVal::String(s) => vec![ScenarioNode::IncludedScenario {
1013                                    name: s.clone(),
1014                                    children: Vec::new(),
1015                                }],
1016                                // Anything else (object with
1017                                // `scenario:`, `for_each:`, etc.)
1018                                // routes through the standard parse
1019                                // path so list entries can be
1020                                // heterogeneous.
1021                                _ => parse_scenario_nodes(item),
1022                            }
1023                        })
1024                        .collect(),
1025                    JVal::String(s) => vec![ScenarioNode::IncludedScenario {
1026                        name: s.clone(),
1027                        children: Vec::new(),
1028                    }],
1029                    _ => Vec::new(),
1030                }
1031            } else if let Some(combo_val) = obj.get("for_combinations") {
1032                // Explicit for_combinations keyword (alias for
1033                // multi-clause for_each). Route through
1034                // ComprehensionSpec so the for_combinations branch
1035                // shares the for_each branch's single chokepoint.
1036                // Distinct-var input (the typical case) parses as
1037                // Cartesian via the name-repetition detection rule
1038                // — same semantics as the legacy direct
1039                // `Comprehension::cartesian(...)` path.
1040                let specs = parse_combination_specs(combo_val);
1041                let inline = specs
1042                    .iter()
1043                    .map(|(v, e)| format!("{v} in {e}"))
1044                    .collect::<Vec<_>>()
1045                    .join(", ");
1046                let spec = ComprehensionSpec {
1047                    r#for: ForSpec::Inline(inline),
1048                    r#where: obj.get("where").and_then(|v| v.as_str()).map(String::from),
1049                    order: obj.get("order").and_then(|v| v.as_str()).map(String::from),
1050                };
1051                match spec.into_algebra() {
1052                    Ok(comprehension) => vec![ScenarioNode::Comprehension {
1053                        comprehension,
1054                        children,
1055                        continue_if: parse_continue_if(obj.get("continue_if")),
1056                        anchor: obj.get("anchor").and_then(|v| v.as_str()).map(String::from),
1057                    }],
1058                    Err(e) => {
1059                        eprintln!("warning: for_combinations: {e}");
1060                        vec![]
1061                    }
1062                }
1063            } else if let Some(cond) = obj.get("do_while").and_then(|v| v.as_str()) {
1064                vec![ScenarioNode::DoWhile {
1065                    condition: cond.to_string(),
1066                    counter,
1067                    children,
1068                }]
1069            } else if let Some(cond) = obj.get("do_until").and_then(|v| v.as_str()) {
1070                vec![ScenarioNode::DoUntil {
1071                    condition: cond.to_string(),
1072                    counter,
1073                    children,
1074                }]
1075            } else if let Some(bindings_val) = obj.get("bindings") {
1076                // Scenario-tree-level `bindings:` — arbitrary GK
1077                // matter that installs as a scope-tree layer over
1078                // the parent. The source text is whatever the
1079                // author wrote (interpretation happens at kernel
1080                // build time via the canonical scope synthesizer).
1081                let source = match bindings_val {
1082                    JVal::String(s) => s.clone(),
1083                    JVal::Object(map) => {
1084                        // Map form: each `name: expr` produces
1085                        // one `name := <expr>` line. The GK
1086                        // compiler classifies the modifier from
1087                        // any leading `final`/`init`/`shared`
1088                        // keyword in `name`; the bare-name case
1089                        // becomes a cycle binding.
1090                        let mut out = String::new();
1091                        for (name, value) in map {
1092                            let v_text = match value {
1093                                JVal::String(s) => s.clone(),
1094                                JVal::Bool(b) => b.to_string(),
1095                                JVal::Number(n) => n.to_string(),
1096                                JVal::Null => String::new(),
1097                                other => other.to_string(),
1098                            };
1099                            out.push_str(&format!("{name} := {v_text}\n"));
1100                        }
1101                        out
1102                    }
1103                    _ => String::new(),
1104                };
1105                if source.trim().is_empty() {
1106                    Vec::new()
1107                } else {
1108                    if children.is_empty() {
1109                        eprintln!(
1110                            "warning: scenario-tree `bindings:` block has no \
1111                             `phases:` body — this is a no-op (the scope is \
1112                             entered and immediately exited with no descendants \
1113                             reading any of its declared names). If you meant \
1114                             to publish these bindings to a subtree, add a \
1115                             `phases:` block; if you meant to declare workload-\
1116                             level bindings, move them to the top-level \
1117                             `bindings:` field of the workload."
1118                        );
1119                    }
1120                    vec![ScenarioNode::Bindings { source, children }]
1121                }
1122            } else if let Some(set_val) = obj.get("set") {
1123                // `set: { name: value, ... }` — convenience sugar
1124                // that desugars to a `Bindings` node carrying GK
1125                // matter of the shape `const NAME := <polydat-literal>`.
1126                // The Polydat compiler handles workload-param
1127                // interpolation, string-literal interpolation,
1128                // and full const-expression evaluation at kernel
1129                // build time, so this form composes with every
1130                // other Polydat feature (no separate two-pass
1131                // evaluator). The `Bindings` node carries the
1132                // synthesized source; downstream code never sees
1133                // a SetParam-specific shape.
1134                //
1135                // String shorthand `set: name=value` is also
1136                // accepted for the single-override one-liner case.
1137                //
1138                // Map iteration order is preserved by serde_yaml
1139                // (insertion order); declaration order wins on
1140                // collision via the standard Polydat shadow semantics
1141                // for the same source.
1142                let pairs: Vec<(String, JVal)> = match set_val {
1143                    JVal::Object(map) => map.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
1144                    JVal::String(s) => match s.split_once('=') {
1145                        Some((k, v)) => {
1146                            vec![(k.trim().to_string(), JVal::String(v.trim().to_string()))]
1147                        }
1148                        None => {
1149                            eprintln!(
1150                                "warning: scenario `set:` string form must be \
1151                                     `name=value`, got `{s}` — ignoring"
1152                            );
1153                            Vec::new()
1154                        }
1155                    },
1156                    _ => Vec::new(),
1157                };
1158                if pairs.is_empty() {
1159                    Vec::new()
1160                } else if children.is_empty() {
1161                    // Same no-op condition as the explicit
1162                    // `bindings:` form: a `set:` with no
1163                    // `phases:` body publishes overrides to
1164                    // nothing. Almost certainly an author error.
1165                    let names: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect();
1166                    eprintln!(
1167                        "warning: scenario-tree `set:` block (overriding {:?}) \
1168                         has no `phases:` body — this is a no-op. Add a `phases:` \
1169                         block listing what the override applies to.",
1170                        names
1171                    );
1172                    Vec::new()
1173                } else {
1174                    // Synthesize the Polydat source body. Each pair
1175                    // becomes `const NAME := <polydat-literal>` — the
1176                    // single canonical effectively-const binding
1177                    // shape. The compiler tries const-fold at
1178                    // compile time (pure literals fold; values
1179                    // containing `{name}` interpolation depend on
1180                    // extern slots that aren't populated until
1181                    // materialize-wiring) and falls back to
1182                    // scope-init pull when fold isn't possible.
1183                    // Either way the value is materialized once
1184                    // and then immutable for the scope's
1185                    // lifetime — author doesn't need to think
1186                    // about which path the runtime takes.
1187                    //
1188                    // Each value lowers to `const NAME := <rhs>` via
1189                    // `emit_set_value_literal`. A BARE identifier is a wire
1190                    // reference (consistent with comprehension r-values,
1191                    // SRD-18f) — `set: { x: mnc }` binds mnc's value, and an
1192                    // unresolved bare name is a hard error at scope synthesis.
1193                    // Numbers/bools are literals; a YAML sequence is a list. A
1194                    // string literal is the explicit polydat-quoted form
1195                    // `'"verbose"'` (ordinary YAML quotes don't survive the
1196                    // pipeline's serde round-trips).
1197                    let mut source = String::new();
1198                    for (name, value) in &pairs {
1199                        source.push_str(&format!(
1200                            "const {name} := {}\n",
1201                            emit_set_value_literal(value),
1202                        ));
1203                    }
1204                    vec![ScenarioNode::Bindings { source, children }]
1205                }
1206            } else {
1207                obj.iter()
1208                    .map(|(name, _cmd)| ScenarioNode::Phase(name.clone()))
1209                    .collect()
1210            }
1211        }
1212        _ => Vec::new(),
1213    }
1214}
1215
1216/// Resolve every `IncludedScenario { name, children: [] }` node
1217/// produced by `parse_scenario_nodes` into one whose `children`
1218/// hold a clone of the referenced scenario's resolved nodes.
1219///
1220/// Two failure modes are surfaced as parse errors:
1221///
1222/// 1. **Unknown scenario name** — `scenario: foo` where no
1223///    `scenarios.foo` exists.
1224/// 2. **Cycle** — `A` includes `B` which (transitively) includes
1225///    `A`. The error names the full cycle path so the operator
1226///    can fix the offending edge.
1227///
1228/// Resolution is depth-first with memoization so each scenario
1229/// is resolved at most once regardless of how many places
1230/// reference it. After this pass the workload model carries no
1231/// unresolved `IncludedScenario` nodes; downstream consumers
1232/// (scope tree, executor, runner) can treat the variant as a
1233/// fully-formed wrapper scope.
1234pub fn resolve_scenario_includes(
1235    scenarios: &mut HashMap<String, Vec<ScenarioNode>>,
1236) -> Result<(), String> {
1237    use std::collections::HashSet;
1238
1239    // Snapshot the input so resolution reads from a stable map
1240    // while we mutate the output. Each resolved scenario is
1241    // recorded back into `out`.
1242    let input: HashMap<String, Vec<ScenarioNode>> = scenarios.clone();
1243    let mut out: HashMap<String, Vec<ScenarioNode>> = HashMap::new();
1244
1245    fn resolve_nodes(
1246        nodes: &[ScenarioNode],
1247        input: &HashMap<String, Vec<ScenarioNode>>,
1248        out: &mut HashMap<String, Vec<ScenarioNode>>,
1249        stack: &mut Vec<String>,
1250    ) -> Result<Vec<ScenarioNode>, String> {
1251        let mut resolved = Vec::with_capacity(nodes.len());
1252        for n in nodes {
1253            resolved.push(resolve_one(n, input, out, stack)?);
1254        }
1255        Ok(resolved)
1256    }
1257
1258    fn resolve_one(
1259        node: &ScenarioNode,
1260        input: &HashMap<String, Vec<ScenarioNode>>,
1261        out: &mut HashMap<String, Vec<ScenarioNode>>,
1262        stack: &mut Vec<String>,
1263    ) -> Result<ScenarioNode, String> {
1264        match node {
1265            ScenarioNode::Phase(name) => Ok(ScenarioNode::Phase(name.clone())),
1266            ScenarioNode::IncludedScenario { name, .. } => {
1267                if stack.iter().any(|s| s == name) {
1268                    let mut path = stack.clone();
1269                    path.push(name.clone());
1270                    return Err(format!(
1271                        "scenario include cycle detected: {}",
1272                        path.join(" -> "),
1273                    ));
1274                }
1275                let target = input.get(name).ok_or_else(|| {
1276                    format!(
1277                        "scenario include 'scenario: {name}' references an unknown \
1278                     scenario. Known scenarios: {}",
1279                        {
1280                            let mut names: Vec<&str> = input.keys().map(|s| s.as_str()).collect();
1281                            names.sort();
1282                            names.join(", ")
1283                        },
1284                    )
1285                })?;
1286                stack.push(name.clone());
1287                let children = resolve_nodes(target, input, out, stack)?;
1288                stack.pop();
1289                // Memoize the resolved scenario for any later
1290                // include reference. Idempotent: equivalent
1291                // resolved children produced regardless of
1292                // entry point.
1293                out.entry(name.clone()).or_insert_with(|| children.clone());
1294                Ok(ScenarioNode::IncludedScenario {
1295                    name: name.clone(),
1296                    children,
1297                })
1298            }
1299            ScenarioNode::Comprehension {
1300                comprehension,
1301                children,
1302                continue_if,
1303                anchor,
1304            } => Ok(ScenarioNode::Comprehension {
1305                comprehension: comprehension.clone(),
1306                children: resolve_nodes(children, input, out, stack)?,
1307                continue_if: continue_if.clone(),
1308                anchor: anchor.clone(),
1309            }),
1310            ScenarioNode::DoWhile {
1311                condition,
1312                counter,
1313                children,
1314            } => Ok(ScenarioNode::DoWhile {
1315                condition: condition.clone(),
1316                counter: counter.clone(),
1317                children: resolve_nodes(children, input, out, stack)?,
1318            }),
1319            ScenarioNode::DoUntil {
1320                condition,
1321                counter,
1322                children,
1323            } => Ok(ScenarioNode::DoUntil {
1324                condition: condition.clone(),
1325                counter: counter.clone(),
1326                children: resolve_nodes(children, input, out, stack)?,
1327            }),
1328            ScenarioNode::Bindings { source, children } => Ok(ScenarioNode::Bindings {
1329                source: source.clone(),
1330                children: resolve_nodes(children, input, out, stack)?,
1331            }),
1332        }
1333    }
1334
1335    let mut visited: HashSet<String> = HashSet::new();
1336    let names: Vec<String> = scenarios.keys().cloned().collect();
1337    for name in names {
1338        if visited.contains(&name) {
1339            continue;
1340        }
1341        let mut stack = vec![name.clone()];
1342        let resolved = resolve_nodes(&input[&name], &input, &mut out, &mut stack)?;
1343        out.insert(name.clone(), resolved);
1344        visited.insert(name);
1345    }
1346    *scenarios = out;
1347    Ok(())
1348}
1349
1350/// Parse combination specs from any of three YAML forms:
1351///
1352/// **Map form** (keys = variables, values = expressions):
1353/// ```yaml
1354/// for_combinations:
1355///   profile: "matching_profiles('{dataset}', '{prefix}')"
1356///   k: "{k_values}"
1357/// ```
1358///
1359/// **List form** (reuses for_each "var in expr" syntax):
1360/// ```yaml
1361/// for_combinations:
1362///   - "profile in matching_profiles('{dataset}', '{prefix}')"
1363///   - "k in {k_values}"
1364/// ```
1365///
1366/// **Inline form** (compact comma-separated):
1367/// ```yaml
1368/// for_combinations: "profile in profiles, k in {k_values}"
1369/// ```
1370fn parse_combination_specs(val: &JVal) -> Vec<(String, String)> {
1371    match val {
1372        // Map form: { "profile": "expr", "k": "expr" }
1373        JVal::Object(map) => map
1374            .iter()
1375            .map(|(key, val)| {
1376                let expr = val.as_str().unwrap_or("").to_string();
1377                (key.clone(), expr)
1378            })
1379            .collect(),
1380        // List form: ["profile in expr", "k in expr"]
1381        JVal::Array(arr) => arr
1382            .iter()
1383            .filter_map(|item| {
1384                let s = item.as_str()?;
1385                clause_pairs_of(s)
1386            })
1387            .flatten()
1388            .collect(),
1389        // Inline form: "profile in expr, k in expr"
1390        // Split on commas that are NOT inside parentheses (respects
1391        // function calls like `matching_profiles('{dataset}', '{prefix}')`).
1392        JVal::String(s) => clause_pairs_of(s).unwrap_or_default(),
1393        _ => {
1394            eprintln!("warning: for_combinations value must be a map, list, or string");
1395            Vec::new()
1396        }
1397    }
1398}
1399
1400/// Parse clause text (`"var in expr"`, or a comma-separated list of
1401/// them) through polydat's spec entry and read the `(var, expr)` pairs
1402/// back off the algebra, warning and yielding `None` on a parse error.
1403fn clause_pairs_of(text: &str) -> Option<Vec<(String, String)>> {
1404    match parse_inline(text) {
1405        Ok(comp) => {
1406            let mut pairs = Vec::new();
1407            collect_clause_pairs(&comp, &mut pairs);
1408            Some(pairs)
1409        }
1410        Err(e) => {
1411            eprintln!("warning: for_combinations: {e}");
1412            None
1413        }
1414    }
1415}
1416
1417/// Every leaf clause of `c`, in order, as `(var, source text)`.
1418fn collect_clause_pairs(c: &Comprehension, out: &mut Vec<(String, String)>) {
1419    match c {
1420        Comprehension::Clause { name, source } => match source.to_text() {
1421            Some(text) => out.push((name.clone(), text)),
1422            None => eprintln!("warning: for_combinations: clause '{name}' has no text form"),
1423        },
1424        Comprehension::Cartesian { children }
1425        | Comprehension::Zip { children, .. }
1426        | Comprehension::Union { children } => {
1427            for child in children {
1428                collect_clause_pairs(child, out);
1429            }
1430        }
1431        Comprehension::Filter { child, .. } | Comprehension::Order { child, .. } => {
1432            collect_clause_pairs(child, out);
1433        }
1434    }
1435}
1436
1437// -----------------------------------------------------------------
1438// Phases
1439// -----------------------------------------------------------------
1440
1441/// Parse the `phases:` section of a workload YAML.
1442///
1443/// Each phase is a named map with optional `cycles`, `concurrency`,
1444/// `rate`, `adapter`, `errors`, `tags`, and `ops` fields.
1445/// Returns the phase map and a Vec preserving YAML definition order.
1446fn parse_phases(
1447    val: Option<&JVal>,
1448    doc_params: &HashMap<String, JVal>,
1449    doc_tags: &HashMap<String, String>,
1450) -> Result<(HashMap<String, WorkloadPhase>, Vec<String>), String> {
1451    let mut phases = HashMap::new();
1452    let mut phase_order = Vec::new();
1453    let Some(val) = val else {
1454        return Ok((phases, phase_order));
1455    };
1456    let Some(obj) = val.as_object() else {
1457        return Ok((phases, phase_order));
1458    };
1459
1460    for (phase_name, phase_val) in obj {
1461        let Some(phase_obj) = phase_val.as_object() else {
1462            continue;
1463        };
1464
1465        let cycles = phase_obj.get("cycles").map(|v| match v {
1466            JVal::Number(n) => n.to_string(),
1467            JVal::String(s) => s.clone(),
1468            other => other.to_string(),
1469        });
1470
1471        let concurrency = phase_obj.get("concurrency").map(|v| match v {
1472            JVal::Number(n) => n.to_string(),
1473            JVal::String(s) => s.clone(),
1474            other => other.to_string(),
1475        });
1476
1477        // A number or a `{param}` / iter-var reference (resolved at
1478        // the phase gather, the `timeout:` discipline). Anything
1479        // else is a load error — a malformed rate must never
1480        // silently become "unrated".
1481        let rate = match phase_obj.get("rate") {
1482            None => None,
1483            Some(JVal::Number(n)) => Some(n.to_string()),
1484            Some(JVal::String(s)) => Some(s.clone()),
1485            Some(other) => {
1486                return Err(format!(
1487                    "phase '{phase_name}': `rate` must be a number (ops/sec) \
1488                 or a {{param}} reference; got: {other}"
1489                ));
1490            }
1491        };
1492
1493        // SRD-82 Part 6 — daemon phase (runs concurrently with foreground
1494        // siblings, stopped when they complete). A boolean: `true` / `false`.
1495        let daemon = phase_obj
1496            .get("daemon")
1497            .map_or(Ok(false), |v| crate::boolean::json_bool("daemon", v))
1498            .map_err(|e| format!("phase '{phase_name}': {e}"))?;
1499
1500        let adapter = phase_obj
1501            .get("adapter")
1502            .and_then(|v| v.as_str())
1503            .map(|s| s.to_string());
1504
1505        let errors = phase_obj
1506            .get("errors")
1507            .and_then(|v| v.as_str())
1508            .map(|s| s.to_string());
1509
1510        let error_rate_max = phase_obj.get("error_rate_max").and_then(|v| v.as_f64());
1511
1512        // SRD-83 governance `timeout:` (GAP-12). A duration string, a
1513        // bare number (fractional seconds), or a `{param}` reference.
1514        // Param-bearing values resolve at the phase gather; literal
1515        // values must at least LOOK like a time value (non-empty, and
1516        // either numeric-leading or brace-opening) so a structural typo
1517        // fails at load, not at first dispatch. Full duration parsing
1518        // stays runtime-side (single parser: `timeval::parse_time_ms`).
1519        let timeout = match phase_obj.get("timeout") {
1520            None => None,
1521            Some(v) => {
1522                let s = match v {
1523                    serde_json::Value::String(s) => s.clone(),
1524                    n if n.is_u64() || n.is_f64() => n.to_string(),
1525                    other => {
1526                        return Err(format!(
1527                            "phase '{phase_name}': `timeout` must be a duration \
1528                         string (e.g. \"2.5h\"), a number of seconds, or a \
1529                         {{param}} reference; got: {other}"
1530                        ));
1531                    }
1532                };
1533                let t = s.trim();
1534                if t.is_empty()
1535                    || !(t.starts_with('{') || t.starts_with(|c: char| c.is_ascii_digit()))
1536                {
1537                    return Err(format!(
1538                        "phase '{phase_name}': `timeout: \"{s}\"` is not a \
1539                         duration ('{{param}}', \"2.5h\", \"150ms\", or \
1540                         seconds)"
1541                    ));
1542                }
1543                Some(s)
1544            }
1545        };
1546
1547        // Per-phase total-attempts budget — the phase-level surface of the
1548        // `tries` sigil (SRD-82 Part 3b). Inherits down to the phase's ops;
1549        // absent everywhere → no tries wrapper (single attempt). Two forms:
1550        // the sugared number (`tries: 20`) and the map form carrying retry
1551        // backoff (`tries: {count: 20, backoff: {ratio, min, max}}`).
1552        let (tries, tries_backoff) = match phase_obj.get("tries") {
1553            None => (None, None),
1554            Some(v) if v.is_u64() || v.is_i64() => (v.as_u64().map(|n| n as u32), None),
1555            Some(serde_json::Value::Object(m)) => {
1556                let count = m.get("count").and_then(|c| c.as_u64()).map(|n| n as u32);
1557                let backoff = m.get("backoff").and_then(|b| b.as_object()).map(|bo| {
1558                    crate::model::BackoffSpec {
1559                        ratio: bo.get("ratio").and_then(|r| r.as_f64()),
1560                        min: bo.get("min").and_then(json_scalar_to_dur_string),
1561                        max: bo.get("max").and_then(json_scalar_to_dur_string),
1562                    }
1563                });
1564                (count, backoff)
1565            }
1566            Some(other) => {
1567                return Err(format!(
1568                    "phase '{phase_name}': `tries` must be a number or a map \
1569                 {{count, backoff: {{ratio, min, max}}}}, got {other}"
1570                ));
1571            }
1572        };
1573
1574        // SRD-83 — `stop_when:` is a list of {when, trigger?, effect?}.
1575        // StopConditionSpec derives Deserialize, so deserialize the
1576        // sub-tree directly; surface a malformed block as a parse error.
1577        // SRD-83 §throttle — adaptive backpressure governor: bool
1578        // sugar or the full spec map (serde, deny_unknown_fields).
1579        let throttle: Option<crate::model::ThrottleField> = match phase_obj.get("throttle") {
1580            Some(v) => Some(
1581                serde_json::from_value(v.clone())
1582                    .map_err(|e| format!("phase '{phase_name}' invalid `throttle` block: {e}"))?,
1583            ),
1584            None => None,
1585        };
1586        let stop_when: Vec<StopConditionSpec> = match phase_obj.get("stop_when") {
1587            Some(v) => serde_json::from_value(v.clone())
1588                .map_err(|e| format!("invalid `stop_when` block: {e}"))?,
1589            None => Vec::new(),
1590        };
1591        // SRD-83 Part 5 — reject unknown effect verbs at load (a typo'd
1592        // verb would otherwise silently become the shell default).
1593        for sc in &stop_when {
1594            sc.validate()
1595                .map_err(|e| format!("phase `stop_when`: {e}"))?;
1596        }
1597
1598        let tags = phase_obj
1599            .get("tags")
1600            .and_then(|v| v.as_str())
1601            .map(|s| s.to_string());
1602
1603        // SRD-13f Push D: phase-level AND workload-level
1604        // `bindings:` are captured on their own scope's AST
1605        // only — they do NOT fold into per-op bindings.
1606        // Workload bindings live on `Workload.bindings` and
1607        // compile to the workload-root kernel; phase bindings
1608        // live on `WorkloadPhase.bindings` and compile to the
1609        // phase kernel. Both reach ops through the Polydat Kernel
1610        // chain (cell-on-outputs cascade, SRD-13f Push B.2),
1611        // not parser-time concat.
1612        let phase_bindings_only = extract_bindings(phase_obj.get("bindings"));
1613
1614        // Parse inline ops if present
1615        let mut inline_ops = Vec::new();
1616        if phase_obj.contains_key("op") {
1617            return Err(format!(
1618                "phase '{phase_name}': `op:` is not a phase key; write the phase's \
1619                 op templates under `ops:`"
1620            ));
1621        }
1622        if let Some(ops_val) = op_collection(phase_obj, &format!("phase '{phase_name}'"))? {
1623            let phase_tags = {
1624                let mut t = doc_tags.clone();
1625                t.insert("phase".to_string(), phase_name.clone());
1626                t
1627            };
1628            // Phase inline ops carry zero "outer YAML
1629            // bindings sugar" — they're directly under the
1630            // phase, no block wrapper. Workload + phase
1631            // bindings reach them via the Polydat Kernel chain.
1632            parse_ops_field(
1633                &ops_val,
1634                phase_name,
1635                &BindingsDef::default(),
1636                doc_params,
1637                &phase_tags,
1638                &mut inline_ops,
1639            )?;
1640        }
1641
1642        // Auto-tag inline ops
1643        for op in &mut inline_ops {
1644            if !op.tags.contains_key("name") {
1645                op.tags.insert("name".to_string(), op.name.clone());
1646            }
1647            if !op.tags.contains_key("op") {
1648                op.tags.insert("op".to_string(), op.name.clone());
1649            }
1650        }
1651
1652        let for_each = phase_obj
1653            .get("for_each")
1654            .or_else(|| phase_obj.get("for"))
1655            .and_then(|v| v.as_str())
1656            .map(|s| s.to_string());
1657        // SRD-101 — phase-level `continue_if` gate (bounds a `for_each` sweep).
1658        let continue_if = parse_continue_if(phase_obj.get("continue_if"));
1659
1660        let loop_scope = phase_obj
1661            .get("loop_scope")
1662            .and_then(|v| v.as_str())
1663            .map(|s| s.to_string());
1664        let iter_scope = phase_obj
1665            .get("iter_scope")
1666            .and_then(|v| v.as_str())
1667            .map(|s| s.to_string());
1668        // Phase-level `summary:` is gone (SRD-46 made `report:`
1669        // the canonical surface). Reject explicitly so silent
1670        // drops don't mislead operators migrating workloads.
1671        if phase_obj.contains_key("summary") {
1672            return Err(format!(
1673                "phase '{phase_name}': `summary:` is removed at phase level; \
1674                 use a `report:` block with `table <name> ...` items instead \
1675                 (SRD-46)"
1676            ));
1677        }
1678        // Per-phase `checkpoint:` declaration. Three forms
1679        // (short string, bool/none, full mapping) handled by
1680        // [`Checkpoint`]'s custom deserialize. Absent → None →
1681        // phase always re-runs on resume (per SRD-44 §"No
1682        // workload-level default").
1683        let checkpoint = phase_obj
1684            .get("checkpoint")
1685            .map(|v| serde_json::from_value::<crate::model::Checkpoint>(v.clone()))
1686            .transpose()
1687            .map_err(|e| format!("phase '{phase_name}' checkpoint: {e}"))?;
1688
1689        // Phase-level `poll:` block (SRD-75). When present,
1690        // the phase's cycle execution runs in a wall-clock
1691        // loop until a Polydat predicate over captures returns
1692        // `true` or `timeout_ms` elapses. Distinct from the
1693        // OP-level `poll:` field (which lives on a single op
1694        // and wraps a `PollingDispenser` — SRD-32). The two
1695        // forms coexist; phase-poll is the synchronizer
1696        // pattern (SRD-75 driver use case), per-op poll is
1697        // the await-emptiness pattern.
1698        let phase_poll = match phase_obj.get("poll") {
1699            None => None,
1700            Some(v) => {
1701                let map = v.as_object().ok_or_else(|| {
1702                    format!(
1703                        "phase '{phase_name}': phase-level `poll:` must be a \
1704                     mapping with at least `until: <expr>`. Got a non-object \
1705                     value; if you intended an OP-level `poll:` flag, attach \
1706                     it to a specific op under `ops:` instead. SRD-75."
1707                    )
1708                })?;
1709                let until = map
1710                    .get("until")
1711                    .and_then(|v| v.as_str())
1712                    .ok_or_else(|| {
1713                        format!(
1714                            "phase '{phase_name}': phase-level `poll:` requires \
1715                         `until: <polydat-boolean-expression>`. SRD-75."
1716                        )
1717                    })?
1718                    .to_string();
1719                // Numbers or `{param}` / iter-var references
1720                // (resolved at the phase gather); anything else is
1721                // a load error — a malformed bound must never
1722                // silently fall back to the default.
1723                let numeric_or_ref = |field: &str| -> Result<Option<String>, String> {
1724                    match map.get(field) {
1725                        None => Ok(None),
1726                        Some(JVal::Number(n)) => Ok(Some(n.to_string())),
1727                        Some(JVal::String(s)) => Ok(Some(s.clone())),
1728                        Some(other) => Err(format!(
1729                            "phase '{phase_name}' poll: `{field}` must be a \
1730                             number or a {{param}} reference; got: {other}. \
1731                             SRD-75."
1732                        )),
1733                    }
1734                };
1735                let interval_ms = numeric_or_ref("interval_ms")?;
1736                let timeout_ms = numeric_or_ref("timeout_ms")?;
1737                let max_error_retries = numeric_or_ref("max_error_retries")?;
1738                let metric_name = map
1739                    .get("metric_name")
1740                    .and_then(|v| v.as_str())
1741                    .map(|s| s.to_string());
1742                // SRD-75 §"Open questions" → §"on_timeout" — what
1743                // to do when the deadline fires. Closed vocabulary:
1744                // `error` (default; phase fails, scenario continues
1745                // by default error-routing policy) or `abort`
1746                // (request session stop; the whole run terminates).
1747                let on_timeout = match map.get("on_timeout") {
1748                    None => None,
1749                    Some(v) => {
1750                        let s = v.as_str().ok_or_else(|| {
1751                            format!(
1752                                "phase '{phase_name}' poll: `on_timeout` must be \
1753                             a string (`error` or `abort`). SRD-75."
1754                            )
1755                        })?;
1756                        let normalized = s.trim().to_ascii_lowercase();
1757                        if !matches!(normalized.as_str(), "error" | "abort") {
1758                            return Err(format!(
1759                                "phase '{phase_name}' poll: `on_timeout` must \
1760                                 be `error` or `abort`, got '{s}'. SRD-75."
1761                            ));
1762                        }
1763                        Some(normalized)
1764                    }
1765                };
1766                // SRD-75 (C5) — `require:` strict-gate selectors: a
1767                // single selector string or a list of them; each must
1768                // be a non-empty string.
1769                let require: Vec<String> = match map.get("require") {
1770                    None => Vec::new(),
1771                    Some(serde_json::Value::String(s)) => vec![s.clone()],
1772                    Some(serde_json::Value::Array(items)) => items
1773                        .iter()
1774                        .map(|v| {
1775                            v.as_str().map(str::to_string).ok_or_else(|| {
1776                                format!(
1777                                    "phase '{phase_name}' poll: `require` entries must \
1778                             be metric-selector strings. SRD-75."
1779                                )
1780                            })
1781                        })
1782                        .collect::<Result<Vec<_>, _>>()?,
1783                    Some(_) => {
1784                        return Err(format!(
1785                            "phase '{phase_name}' poll: `require` must be a \
1786                         selector string or a list of them. SRD-75."
1787                        ));
1788                    }
1789                };
1790                if let Some(bad) = require.iter().find(|s| s.trim().is_empty()) {
1791                    let _ = bad;
1792                    return Err(format!(
1793                        "phase '{phase_name}' poll: `require` entries must be \
1794                         non-empty metric selectors. SRD-75."
1795                    ));
1796                }
1797                // Reject keys outside the documented surface — a
1798                // typo like `tinerval_ms:` should fail loudly, not
1799                // silently default. SRD-30 unknown-field hygiene.
1800                let allowed = crate::vocab::phase_poll_fields();
1801                for k in map.keys() {
1802                    if !allowed.contains(&k.as_str()) {
1803                        return Err(format!(
1804                            "phase '{phase_name}' poll: unknown key '{k}'. \
1805                             Allowed: [{}]. SRD-75.",
1806                            allowed.join(", "),
1807                        ));
1808                    }
1809                }
1810                Some(crate::model::PhasePollSpec {
1811                    until,
1812                    interval_ms,
1813                    timeout_ms,
1814                    max_error_retries,
1815                    metric_name,
1816                    on_timeout,
1817                    require,
1818                })
1819            }
1820        };
1821        // SRD-75 §"Concurrency": phase-poll is sequential
1822        // within one phase activation — the predicate's
1823        // evaluation depends on a serial sequence of capture
1824        // writes. `concurrency > 1` against this shape doesn't
1825        // have a meaningful semantic; reject at parse time
1826        // rather than producing surprising runtime behavior.
1827        if phase_poll.is_some() {
1828            if let Some(ref c) = concurrency {
1829                let trimmed = c.trim();
1830                if trimmed != "1" && !trimmed.is_empty() {
1831                    return Err(format!(
1832                        "phase '{phase_name}': `poll:` (SRD-75) is \
1833                         incompatible with `concurrency: {c}` — phase-poll \
1834                         is sequential within one activation (the predicate \
1835                         depends on a serial sequence of capture writes). \
1836                         Drop `concurrency` or set it to 1."
1837                    ));
1838                }
1839            }
1840            if inline_ops.is_empty() {
1841                return Err(format!(
1842                    "phase '{phase_name}': `poll:` requires at least one op \
1843                     under `ops:` — captures are written by op execution; \
1844                     a phase with `poll:` and no ops has nothing to do. \
1845                     SRD-75."
1846                ));
1847            }
1848        }
1849
1850        // `status_metrics:` — names of relevancy aggregates to
1851        // surface on the inline progress line and the per-phase
1852        // ✓ DONE summary. Accepts a YAML list (`[name, name]`),
1853        // a single string, or a comma-separated string. Empty /
1854        // absent → no metrics tail (nothing presumed present).
1855        let status_metrics: Vec<String> = match phase_obj.get("status_metrics") {
1856            None => Vec::new(),
1857            Some(JVal::Array(items)) => items
1858                .iter()
1859                .filter_map(|v| v.as_str().map(|s| s.trim().to_string()))
1860                .filter(|s| !s.is_empty())
1861                .collect(),
1862            Some(JVal::String(s)) => s
1863                .split(',')
1864                .map(str::trim)
1865                .filter(|s| !s.is_empty())
1866                .map(String::from)
1867                .collect(),
1868            Some(other) => {
1869                return Err(format!(
1870                    "phase '{phase_name}' status_metrics: must be a list of metric \
1871                 names, a comma-separated string, or omitted; got {other:?}"
1872                ));
1873            }
1874        };
1875
1876        // Phase-level `metrics:` — same schema as op `metrics:`,
1877        // but evaluated once at phase completion. Raw `value:`
1878        // expressions are preserved (no auto-inject into bindings):
1879        // the phase synthesiser emits `volatile __metric_<name> :=
1880        // <value>` directly, so a nondeterministic value such as
1881        // `phase_elapsed(phase_start)` is volatility-acknowledged
1882        // for strict mode in one place.
1883        let metrics = parse_phase_metrics_field(phase_obj.get("metrics"), phase_name)
1884            .map_err(|e| format!("phase '{phase_name}' metrics: {e}"))?;
1885
1886        // Phase-level `dimensions:` — label names this phase introduces,
1887        // whose VALUES arrive from data through a metric's `cell:`. The
1888        // name is the structural declaration; declaring it here is what
1889        // lets a `cell:` reference be checked against the program before
1890        // any cycle runs, instead of surfacing as an attach-time panic on
1891        // the component tree.
1892        let dimensions = parse_dimensions_field(phase_obj.get("dimensions"), phase_name)?;
1893
1894        // SRD-86 — phase `optimize:` block (workload-local config). A bare
1895        // string is sugar for `{ objective: <string> }` (see
1896        // `OptimizeBlock::from_yaml_value`).
1897        let optimize = match phase_obj.get("optimize") {
1898            Some(v) => Some(
1899                crate::model::OptimizeBlock::from_yaml_value(v)
1900                    .map_err(|e| format!("phase '{phase_name}' invalid `optimize` block: {e}"))?,
1901            ),
1902            None => None,
1903        };
1904        // A `cell:` must name a DECLARED dimension. This is the payoff for
1905        // reifying dimensions: the reference is checked against the program
1906        // at load, so a typo'd or undeclared dimension is a workload error
1907        // here rather than a component-tree surprise at attach time (or, in
1908        // the label-ownership case, a runtime panic).
1909        validate_cell_dimensions(phase_name, &dimensions, &inline_ops, &metrics)?;
1910
1911        // SRD-109 — key-metric designations. Aggregate qualification is
1912        // MANDATORY: an unqualified family is a parse error carrying the
1913        // vocabulary, because there are no implied aggregates anywhere in
1914        // the reporting pipeline.
1915        let key_metrics: Vec<crate::model::KeyMetric> = match phase_obj.get("key_metrics") {
1916            None => Vec::new(),
1917            Some(v) => {
1918                let map = v.as_object().ok_or_else(|| {
1919                    format!(
1920                        "phase '{phase_name}': key_metrics must be a mapping of \
1921                     column: \"agg(family)\""
1922                    )
1923                })?;
1924                let mut out = Vec::new();
1925                for (col, spec) in map {
1926                    let spec = spec.as_str().ok_or_else(|| {
1927                        format!(
1928                            "phase '{phase_name}' key_metrics.{col}: expected a \
1929                         string \"agg(family)\""
1930                        )
1931                    })?;
1932                    let (agg_name, family) = spec
1933                        .trim()
1934                        .strip_suffix(')')
1935                        .and_then(|s| s.split_once('('))
1936                        .ok_or_else(|| {
1937                            format!(
1938                                "phase '{phase_name}' key_metrics.{col}: '{spec}' — \
1939                             aggregate qualification required; write agg(family). \
1940                             Aggregates: {}",
1941                                crate::model::KeyAgg::VOCAB
1942                            )
1943                        })?;
1944                    let agg = crate::model::KeyAgg::parse(agg_name.trim()).ok_or_else(|| {
1945                        format!(
1946                            "phase '{phase_name}' key_metrics.{col}: unknown \
1947                             aggregate '{}'. Aggregates: {}",
1948                            agg_name.trim(),
1949                            crate::model::KeyAgg::VOCAB
1950                        )
1951                    })?;
1952                    let family = family.trim().to_string();
1953                    match agg {
1954                        crate::model::KeyAgg::Span if !family.is_empty() => {
1955                            return Err(format!(
1956                                "phase '{phase_name}' key_metrics.{col}: span() is \
1957                                 family-less — it measures the activation wall clock"
1958                            ));
1959                        }
1960                        crate::model::KeyAgg::Span => {}
1961                        _ if family.is_empty() => {
1962                            return Err(format!(
1963                                "phase '{phase_name}' key_metrics.{col}: {}() needs \
1964                                 a family name",
1965                                agg_name.trim()
1966                            ));
1967                        }
1968                        _ => {}
1969                    }
1970                    out.push(crate::model::KeyMetric {
1971                        column: col.clone(),
1972                        agg,
1973                        family,
1974                    });
1975                }
1976                out
1977            }
1978        };
1979
1980        phases.insert(
1981            phase_name.clone(),
1982            WorkloadPhase {
1983                dimensions,
1984                cycles,
1985                concurrency,
1986                rate,
1987                daemon,
1988                adapter,
1989                errors,
1990                tries,
1991                tries_backoff,
1992                interval: phase_obj
1993                    .get("interval")
1994                    .and_then(|v| v.as_str().map(str::to_string)),
1995                repeat: phase_obj.get("repeat").and_then(|v| v.as_u64()),
1996                error_rate_max,
1997                timeout,
1998                stop_when,
1999                throttle,
2000                tags,
2001                ops: inline_ops,
2002                for_each,
2003                continue_if,
2004                loop_scope,
2005                iter_scope,
2006                checkpoint,
2007                status_metrics,
2008                bindings: phase_bindings_only,
2009                metrics,
2010                poll: phase_poll,
2011                optimize,
2012                key_metrics,
2013            },
2014        );
2015        phase_order.push(phase_name.clone());
2016    }
2017
2018    Ok((phases, phase_order))
2019}
2020
2021// -----------------------------------------------------------------
2022// Blocks
2023// -----------------------------------------------------------------
2024
2025fn parse_blocks(
2026    blocks_val: &JVal,
2027    doc_params: &HashMap<String, JVal>,
2028    doc_tags: &HashMap<String, String>,
2029    all_ops: &mut Vec<ParsedOp>,
2030) -> Result<(), String> {
2031    match blocks_val {
2032        JVal::Object(map) => {
2033            for (block_name, block_val) in map {
2034                parse_single_block(block_name, block_val, doc_params, doc_tags, all_ops)?;
2035            }
2036        }
2037        JVal::Array(arr) => {
2038            for (i, block_val) in arr.iter().enumerate() {
2039                let name = block_val
2040                    .get("name")
2041                    .and_then(|v| v.as_str())
2042                    .map(|s| s.to_string())
2043                    .unwrap_or_else(|| format!("block{}", i + 1));
2044                parse_single_block(&name, block_val, doc_params, doc_tags, all_ops)?;
2045            }
2046        }
2047        _ => {}
2048    }
2049    Ok(())
2050}
2051
2052fn parse_single_block(
2053    block_name: &str,
2054    block_val: &JVal,
2055    doc_params: &HashMap<String, JVal>,
2056    doc_tags: &HashMap<String, String>,
2057    all_ops: &mut Vec<ParsedOp>,
2058) -> Result<(), String> {
2059    let obj = match block_val {
2060        JVal::Object(o) => o,
2061        // A block written as a bare string is one op.
2062        JVal::String(s) => {
2063            let mut op = ParsedOp::simple("stmt1", s);
2064            op.params = exclude_non_op_keys(doc_params);
2065            op.tags = doc_tags.clone();
2066            op.tags.insert("block".to_string(), block_name.to_string());
2067            all_ops.push(op);
2068            return Ok(());
2069        }
2070        other => {
2071            return Err(format!(
2072                "block '{block_name}': must be a mapping or a single op string, got {other}"
2073            ));
2074        }
2075    };
2076
2077    // SRD-13f Push D: workload-level `bindings:` no longer
2078    // merge into block-level. Blocks are YAML organizational
2079    // sugar (not a Polydat scope), so a block's own `bindings:` is
2080    // *syntactic sugar* expanded into each enclosed op's
2081    // `op.bindings` at parse time — it does not cross any
2082    // kernel boundary, and the only "merge" left is this
2083    // block-sugar → op inlining inside `normalize_op_object`.
2084    let block_bindings = extract_bindings(obj.get("bindings"));
2085    let block_params = merge_value_maps(doc_params, &extract_value_map(obj.get("params")));
2086    let mut block_tags = merge_string_maps(doc_tags, &extract_string_map(obj.get("tags")));
2087    block_tags.insert("block".to_string(), block_name.to_string());
2088
2089    if let Some(ops_val) = op_collection(obj, &format!("block '{block_name}'"))? {
2090        parse_ops_field(
2091            &ops_val,
2092            block_name,
2093            &block_bindings,
2094            &block_params,
2095            &block_tags,
2096            all_ops,
2097        )?;
2098    }
2099
2100    Ok(())
2101}
2102
2103/// Collection keys that are not keys: the ops of a workload, phase
2104/// or block go under `ops:` (or one op under `op:`).
2105const RETIRED_COLLECTION_KEYS: &[&str] = &["operations", "statements", "statement"];
2106
2107/// The op templates of a workload, phase or block (`scope` names it
2108/// in errors). `ops:` holds them in any shape (string, list or map);
2109/// `op:` is the one-op shorthand of a workload or block (a phase
2110/// declares none) — a string is its statement and a map is the op
2111/// template itself. A retired spelling is rejected, naming `ops:`.
2112fn op_collection(obj: &serde_json::Map<String, JVal>, scope: &str) -> Result<Option<JVal>, String> {
2113    if let Some(k) = RETIRED_COLLECTION_KEYS
2114        .iter()
2115        .find(|k| obj.contains_key(**k))
2116    {
2117        return Err(format!(
2118            "{scope}: `{k}:` is not a key; write op templates under `ops:` \
2119             (or a single op under `op:`)"
2120        ));
2121    }
2122    match (obj.get("ops"), obj.get("op")) {
2123        (Some(_), Some(_)) => Err(format!(
2124            "{scope}: both `ops:` and `op:` given; `op:` is a single op and \
2125             `ops:` holds any number — write one of them"
2126        )),
2127        (Some(ops), None) => Ok(Some(ops.clone())),
2128        (None, Some(JVal::Array(_))) => Err(format!(
2129            "{scope}: `op:` is a single op; write a list of op templates under `ops:`"
2130        )),
2131        (None, Some(JVal::Object(template))) => {
2132            Ok(Some(JVal::Array(vec![JVal::Object(template.clone())])))
2133        }
2134        (None, Some(statement)) => Ok(Some(statement.clone())),
2135        (None, None) => Ok(None),
2136    }
2137}
2138
2139/// Op-template keys that are not keys, each with the key to write.
2140const RETIRED_OP_KEYS: &[(&str, &str)] = &[
2141    ("ops", "`op:`"),
2142    ("operations", "`op:`"),
2143    ("statement", "`stmt:` (or `op:`)"),
2144    ("statements", "`stmt:` (or `op:`)"),
2145    ("desc", "`description:`"),
2146    ("driver", "`adapter:`"),
2147];
2148
2149// -----------------------------------------------------------------
2150// Ops
2151// -----------------------------------------------------------------
2152
2153fn parse_ops_field(
2154    ops_val: &JVal,
2155    block_name: &str,
2156    bindings: &BindingsDef,
2157    params: &HashMap<String, JVal>,
2158    tags: &HashMap<String, String>,
2159    all_ops: &mut Vec<ParsedOp>,
2160) -> Result<(), String> {
2161    // Activity/phase-scope param keys and the workload's default-adapter
2162    // selectors are never op fields ([`exclude_non_op_keys`]). Strip them from
2163    // the inherited params before they reach any op. A genuine op-level
2164    // `rate:` or `adapter:` is written on the op and is untouched.
2165    let op_scope_params = exclude_non_op_keys(params);
2166    let params = &op_scope_params;
2167    let mut op_counter = 0;
2168
2169    match ops_val {
2170        // Single string: op: "SELECT ..."
2171        JVal::String(s) => {
2172            op_counter += 1;
2173            let name = format!("stmt{op_counter}");
2174            let mut op = ParsedOp::simple(&name, s);
2175            op.bindings = bindings.clone();
2176            op.params = params.clone();
2177            op.tags = tags.clone();
2178            op.tags.insert("block".to_string(), block_name.to_string());
2179            all_ops.push(op);
2180        }
2181
2182        // List of ops
2183        JVal::Array(arr) => {
2184            for item in arr {
2185                op_counter += 1;
2186                let auto_name = format!("stmt{op_counter}");
2187                let op = normalize_op_item(item, &auto_name, block_name, bindings, params, tags)?;
2188                all_ops.push(op);
2189            }
2190        }
2191
2192        // Map of named ops
2193        JVal::Object(map) => {
2194            for (key, val) in map {
2195                let op = normalize_op_entry(key, val, block_name, bindings, params, tags)?;
2196                all_ops.push(op);
2197            }
2198        }
2199
2200        _ => {}
2201    }
2202
2203    Ok(())
2204}
2205
2206/// Normalize a single op from a list item.
2207fn normalize_op_item(
2208    item: &JVal,
2209    auto_name: &str,
2210    block_name: &str,
2211    bindings: &BindingsDef,
2212    params: &HashMap<String, JVal>,
2213    tags: &HashMap<String, String>,
2214) -> Result<ParsedOp, String> {
2215    match item {
2216        JVal::String(s) => {
2217            let mut op = ParsedOp::simple(auto_name, s);
2218            op.bindings = bindings.clone();
2219            op.params = params.clone();
2220            op.tags = tags.clone();
2221            op.tags.insert("block".to_string(), block_name.to_string());
2222            Ok(op)
2223        }
2224        JVal::Object(map) => {
2225            // Check if first entry is name:stmt pattern
2226            if let Some((first_key, first_val)) = map.iter().next()
2227                && map.len() == 1
2228                && first_val.is_string()
2229            {
2230                let mut op = ParsedOp::simple(first_key, first_val.as_str().unwrap());
2231                op.bindings = bindings.clone();
2232                op.params = params.clone();
2233                op.tags = tags.clone();
2234                op.tags.insert("block".to_string(), block_name.to_string());
2235                return Ok(op);
2236            }
2237            // Full op object
2238            normalize_op_object(map, auto_name, block_name, bindings, params, tags)
2239        }
2240        _ => Ok(ParsedOp::simple(auto_name, "")),
2241    }
2242}
2243
2244/// Normalize a named op from a map entry.
2245fn normalize_op_entry(
2246    key: &str,
2247    val: &JVal,
2248    block_name: &str,
2249    bindings: &BindingsDef,
2250    params: &HashMap<String, JVal>,
2251    tags: &HashMap<String, String>,
2252) -> Result<ParsedOp, String> {
2253    match val {
2254        JVal::String(s) => {
2255            let mut op = ParsedOp::simple(key, s);
2256            op.bindings = bindings.clone();
2257            op.params = params.clone();
2258            op.tags = tags.clone();
2259            op.tags.insert("block".to_string(), block_name.to_string());
2260            Ok(op)
2261        }
2262        JVal::Object(map) => normalize_op_object(map, key, block_name, bindings, params, tags),
2263        JVal::Array(arr) => {
2264            // Array at op level → moved to op.stmt
2265            let mut op_fields = HashMap::new();
2266            op_fields.insert("stmt".to_string(), JVal::Array(arr.clone()));
2267            let mut op = ParsedOp {
2268                traverse: None,
2269                name: key.to_string(),
2270                description: None,
2271                op: op_fields,
2272                bindings: bindings.clone(),
2273                params: params.clone(),
2274                tags: tags.clone(),
2275                condition: None,
2276                delay: None,
2277                metrics: HashMap::new(),
2278                cell: std::collections::BTreeMap::new(),
2279                result: None,
2280                wrappers: None,
2281                captures: Vec::new(),
2282                abstract_interface: None,
2283                interface_bound: false,
2284                daemon: crate::model::DaemonSpec::Disabled,
2285                daemon_cancel_grace_ms: None,
2286                while_cond: None,
2287                rate: None,
2288            };
2289            op.tags.insert("block".to_string(), block_name.to_string());
2290            Ok(op)
2291        }
2292        _ => Ok(ParsedOp::simple(key, "")),
2293    }
2294}
2295
2296/// Human-readable name for a JSON value kind, for parse-time
2297/// error messages. ("string", "number", "array", etc.)
2298fn eval_value_kind(v: &JVal) -> &'static str {
2299    match v {
2300        JVal::Null => "null",
2301        JVal::Bool(_) => "bool",
2302        JVal::Number(_) => "number",
2303        JVal::String(_) => "string",
2304        JVal::Array(_) => "array",
2305        JVal::Object(_) => "mapping",
2306    }
2307}
2308
2309/// Sub-keys allowed inside an op-template's `evaluations:`
2310/// block. The block is a reserved closed-vocab wrapper for
2311/// post-execution validation / scoring config — distinct from
2312/// per-adapter op fields. Anything else inside it is rejected at
2313/// parse time so silent-ignore traps (a misspelled `relevency:`,
2314/// a misplaced wrapper) cannot hide a misconfigured op. New
2315/// evaluation kinds are added to the construction registry.
2316fn evaluations_vocab() -> Vec<&'static str> {
2317    crate::vocab::evaluation_kinds()
2318}
2319
2320/// Scan every string under `value` for bind points, failing on the
2321/// first malformed one ([`crate::bindpoints::extract_bind_points`]).
2322fn check_bind_points(value: &JVal) -> Result<(), String> {
2323    match value {
2324        JVal::String(s) => crate::bindpoints::extract_bind_points(s).map(|_| ()),
2325        JVal::Array(items) => items.iter().try_for_each(check_bind_points),
2326        JVal::Object(map) => map.values().try_for_each(check_bind_points),
2327        _ => Ok(()),
2328    }
2329}
2330
2331/// Normalize a full op object (map of fields).
2332fn normalize_op_object(
2333    map: &serde_json::Map<String, JVal>,
2334    default_name: &str,
2335    block_name: &str,
2336    parent_bindings: &BindingsDef,
2337    parent_params: &HashMap<String, JVal>,
2338    parent_tags: &HashMap<String, String>,
2339) -> Result<ParsedOp, String> {
2340    let name = map
2341        .get("name")
2342        .and_then(|v| v.as_str())
2343        .unwrap_or(default_name)
2344        .to_string();
2345
2346    if let Some((k, write)) = RETIRED_OP_KEYS.iter().find(|(k, _)| map.contains_key(*k)) {
2347        return Err(format!(
2348            "op '{name}' (block '{block_name}'): `{k}:` is not an op-template key; write {write}"
2349        ));
2350    }
2351
2352    let description = map
2353        .get("description")
2354        .and_then(|v| v.as_str())
2355        .map(|s| s.to_string());
2356
2357    // SRD-13f Push D: workload-level and phase-level
2358    // `bindings:` no longer touch ops at parse time — they
2359    // compile to their own kernels and reach ops via the GK
2360    // kernel chain. `parent_bindings` here carries ONLY
2361    // block-level YAML sugar (blocks are not a Polydat scope; their
2362    // `bindings:` field is a copy-paste reducer over each
2363    // enclosed op's bindings). The expansion below is the only
2364    // remaining parser-time inlining.
2365    let mut op_bindings =
2366        inline_block_sugar_into_op(parent_bindings, &extract_bindings(map.get("bindings")));
2367    let op_params = merge_value_maps(parent_params, &extract_value_map(map.get("params")));
2368    let mut op_tags = merge_string_maps(parent_tags, &extract_string_map(map.get("tags")));
2369    op_tags.insert("block".to_string(), block_name.to_string());
2370
2371    // Determine op payload
2372    //
2373    // `reserved` lists keys handled by the workload model itself
2374    // (name, bindings, etc.) — they never reach the adapter.
2375    // `evaluations` is in this list because it's a closed-vocab
2376    // wrapper for validation/scoring config (relevancy, verify)
2377    // — its sub-keys are extracted and hoisted into `op_params`
2378    // below so downstream consumers
2379    // (`crate::validation::parse_relevancy` etc.) find them at
2380    // the same address whether the workload writes the
2381    // canonical wrapped form or the legacy top-level shorthand.
2382    // `metrics` and `result` are CORE op-template fields (SRD-40b
2383    // and SRD-66 respectively) extracted into ParsedOp.metrics /
2384    // ParsedOp.result; they must be kept out of `op_fields` so
2385    // adapters with a closed-vocabulary `known_op_fields()` (HTTP,
2386    // testkit) don't reject them as unknown. The CQL adapter
2387    // returns `None` from `known_op_fields()` (open vocabulary)
2388    // which masked this for the existing workloads.
2389    let reserved = crate::vocab::op_model_fields();
2390    let op_field_names = crate::vocab::op_stmt_fields();
2391    // Activity-level params excised from op fields before the
2392    // adapter sees them. `relevancy` / `verify` stay listed here
2393    // for the legacy top-level shorthand
2394    // (`relevancy: { ... }` directly under the op); the canonical
2395    // form puts them inside `evaluations:` and is handled
2396    // separately below.
2397    let activity_params = [
2398        "ratio",
2399        "adapter",
2400        "space",
2401        "instrument",
2402        "start-timers",
2403        "stop-timers",
2404        "verify",
2405        "relevancy",
2406        "admission",
2407        "strict",
2408        "poll",
2409        "poll_interval_ms",
2410        "timeout_ms",
2411        "poll_metric_name",
2412        "emit",
2413        "batch",
2414        "max_batch_size",
2415        "batchtype",
2416        "memo",
2417        "gutter",
2418        // SRD-63 op-level status visibility. `readout: visible` opts the
2419        // op into its own timed status leaf; excised into params so the
2420        // `readout` wrapper's trigger (which reads params) sees it rather
2421        // than the field falling through to the adapter op payload.
2422        "readout",
2423        // SRD-82 op shell — a per-op error-routing override (`errors:
2424        // "<pattern>:<actions>"`), resolved into a child of the phase policy
2425        // and pinned to this op's dispenser, and the op-level `tries:`
2426        // total-attempts sigil for the conditional tries wrapper. Both are
2427        // excised from op fields so they never reach the adapter as
2428        // op-payload keys.
2429        "errors",
2430        "tries",
2431        // Tries-wrapper companion knobs (SRD-82 Part 3b): retry
2432        // pacing and retry-error exemplar sampling (`exec_events`).
2433        // Consumed at wrapper build from op params; excised here so
2434        // the documented op-level standalone form actually lands in
2435        // params instead of leaking to the adapter as payload keys.
2436        "retry_backoff",
2437        "retry_backoff_max",
2438        "retry_backoff_ratio",
2439        "retry_exemplar_rate",
2440        "retry_exemplar_max_hz",
2441        "retry_advisory",
2442    ];
2443
2444    let mut op_fields = if let Some(explicit_op) = op_field_names.iter().find_map(|k| map.get(*k)) {
2445        let mut m: HashMap<String, JVal> = match explicit_op {
2446            JVal::String(s) => {
2447                let mut m = HashMap::new();
2448                m.insert("stmt".to_string(), JVal::String(s.clone()));
2449                m
2450            }
2451            JVal::Object(o) => o.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
2452            other => {
2453                let mut m = HashMap::new();
2454                m.insert("stmt".to_string(), other.clone());
2455                m
2456            }
2457        };
2458        // Preserve sibling op-level fields so adapter-specific
2459        // extras (e.g. testkit's `result-latency`, `result-capacity`)
2460        // aren't silently dropped when the user writes shorthand:
2461        //
2462        //     insert:
2463        //       stmt: "INSERT ..."
2464        //       result-latency: "5ms"
2465        //
2466        // Without this loop the whole object would collapse to just
2467        // `stmt` and the sibling fields would never reach the adapter.
2468        // Keys already present in the explicit op payload win, so an
2469        // `op:` sub-object still has final say over its own shape.
2470        for (k, v) in map.iter() {
2471            if reserved.contains(&k.as_str())
2472                || op_field_names.contains(&k.as_str())
2473                || activity_params.contains(&k.as_str())
2474            {
2475                continue;
2476            }
2477            m.entry(k.clone()).or_insert_with(|| v.clone());
2478        }
2479        m
2480    } else {
2481        // All non-reserved, non-activity-param fields become op fields
2482        map.iter()
2483            .filter(|(k, _)| {
2484                !reserved.contains(&k.as_str())
2485                    && !op_field_names.contains(&k.as_str())
2486                    && !activity_params.contains(&k.as_str())
2487            })
2488            .map(|(k, v)| (k.clone(), v.clone()))
2489            .collect()
2490    };
2491
2492    // Excise activity-level params from op fields into params
2493    let mut op_params = op_params;
2494    for ap in &activity_params {
2495        if let Some(val) = map.get(*ap) {
2496            // Activity params excised from op fields into params map
2497            op_params.insert(ap.to_string(), val.clone());
2498        }
2499    }
2500
2501    // Canonical `evaluations:` wrapper — closed-vocab
2502    // validation/scoring config. Sub-keys are extracted and
2503    // hoisted into `op_params` so downstream consumers (e.g.
2504    // `crate::validation::parse_relevancy`,
2505    // `crate::validation::parse_assertions`) find them at the
2506    // same address whether the workload uses this canonical
2507    // form or the legacy top-level shorthand. Anything inside
2508    // `evaluations:` that isn't in `EVALUATIONS_VOCAB` is
2509    // rejected up front — the whole point of the wrapper is to
2510    // catch misspellings (`relevency:`) and misplaced wrappers
2511    // that the silent-routing path would otherwise drop on the
2512    // floor.
2513    if let Some(eval_val) = map.get("evaluations") {
2514        let eval_obj = eval_val.as_object().ok_or_else(|| {
2515            format!(
2516                "op '{name}' (block '{block_name}'): `evaluations:` must be a \
2517             mapping, got {kind}. Expected shape: \
2518             `evaluations: {{ relevancy: {{...}}, verify: [...] }}`.",
2519                kind = eval_value_kind(eval_val),
2520            )
2521        })?;
2522        for (k, v) in eval_obj.iter() {
2523            if !evaluations_vocab().contains(&k.as_str()) {
2524                return Err(format!(
2525                    "op '{name}' (block '{block_name}'): unknown key \
2526                     '{k}' under `evaluations:`. Allowed keys: [{}]. \
2527                     Each entry under `evaluations:` is a distinct \
2528                     post-execution evaluation kind — typos and \
2529                     misplaced wrappers are rejected here so silent \
2530                     skipped recall / verify can't happen.",
2531                    evaluations_vocab().join(", "),
2532                ));
2533            }
2534            // Top-level shorthand wins on collision so users
2535            // who already have `relevancy: {...}` at the op
2536            // level don't see their config replaced if they
2537            // also added `evaluations: { relevancy: {...} }`.
2538            // Warn so the duplicate is visible.
2539            if op_params.contains_key(k.as_str()) {
2540                eprintln!(
2541                    "warning: op '{name}' has '{k}' both at top level \
2542                     and under `evaluations:` — top-level wins. Pick \
2543                     one form.",
2544                );
2545                continue;
2546            }
2547            op_params.insert(k.clone(), v.clone());
2548        }
2549    }
2550
2551    // SRD-108 Part B (+ SRD-109 Part 3) — `abstract:` declares
2552    // this op as a typed slot: `{ needs: {name: type,…}, yields:
2553    // {name: type,…}, results: {name: type,…} }`. Unknown keys
2554    // are rejected; each type is a polydat type keyword, resolved
2555    // here and verified against the compiled op-template program
2556    // at pre-map synthesis.
2557    let abstract_interface: Option<crate::model::OpInterface> = match map.get("abstract") {
2558        None => None,
2559        Some(v) => {
2560            let obj = v.as_object().ok_or_else(|| format!(
2561                    "op '{name}': `abstract:` must be a mapping with                      `needs:` / `yields:` / `results:` maps of wire-name -> type"))?;
2562            let mut iface = crate::model::OpInterface::default();
2563            for (k, section) in obj {
2564                let target = match k.as_str() {
2565                    "needs" => &mut iface.needs,
2566                    "yields" => &mut iface.yields,
2567                    "results" => &mut iface.results,
2568                    other => {
2569                        return Err(format!(
2570                            "op '{name}': unknown key '{other}' under                              `abstract:` (allowed: needs, yields, results)"
2571                        ));
2572                    }
2573                };
2574                let entries = section.as_object().ok_or_else(|| format!(
2575                        "op '{name}': `abstract.{k}:` must be a mapping                          of wire-name -> type"))?;
2576                for (wire, typ) in entries {
2577                    let type_name = typ.as_str().ok_or_else(|| format!(
2578                            "op '{name}': `abstract.{k}.{wire}:` type                              must be a string, got {typ}"))?;
2579                    let port_type = crate::port_types::resolve_type_keyword(type_name)
2580                        .map_err(|e| format!("op '{name}': `abstract.{k}.{wire}:` {e}"))?;
2581                    target.insert(wire.clone(), port_type);
2582                }
2583            }
2584            Some(iface)
2585        }
2586    };
2587
2588    let condition = map
2589        .get("if")
2590        .and_then(|v| v.as_str())
2591        .map(normalize_condition_clause);
2592
2593    let delay = match map.get("delay") {
2594        None => None,
2595        Some(v) => {
2596            Some(crate::model::parse_delay_spec_value(v).map_err(|e| format!("op '{name}': {e}"))?)
2597        }
2598    };
2599
2600    // Daemon-op declaration. Parses bool / int / "on"/"off" /
2601    // "true"/"false" via `parse_daemon_spec_value`. When set
2602    // to MaxFibers(N), the cycle-pool dispatch spawns the op
2603    // on a daemon fiber instead of awaiting inline; the cap
2604    // is enforced at spawn time.
2605    let daemon = match map.get("daemon") {
2606        Some(v) => crate::model::parse_daemon_spec_value(v)
2607            .map_err(|e| format!("op '{name}' (block '{block_name}'): {e}",))?,
2608        None => crate::model::DaemonSpec::Disabled,
2609    };
2610    let daemon_cancel_grace_ms = map.get("daemon_cancel_grace_ms").and_then(|v| {
2611        v.as_u64()
2612            .or_else(|| v.as_str().and_then(|s| s.parse::<u64>().ok()))
2613    });
2614    let daemon_enabled = !daemon.is_disabled();
2615    if daemon_enabled {
2616        // `cycles:` and `ratio:` on a daemon op are workload-shape
2617        // errors — the daemon's dispatch cadence is governed by
2618        // the cycle-pool walks + per-op `rate:`, not by cycles or
2619        // ratios. Silently accepting them would hide a mis-shaped
2620        // workload; reject at parse so the operator sees the
2621        // contradiction immediately.
2622        if let Some(c) = op_params.get("cycles") {
2623            return Err(format!(
2624                "op '{name}' (block '{block_name}'): `daemon:` and \
2625                 `cycles: {c}` are mutually exclusive. A daemon op's \
2626                 dispatch cadence is governed by the cycle-pool's \
2627                 stanza walk + per-op `rate:`, not by `cycles:`."
2628            ));
2629        }
2630        if let Some(r) = op_params.get("ratio") {
2631            return Err(format!(
2632                "op '{name}' (block '{block_name}'): `daemon:` and \
2633                 `ratio: {r}` are mutually exclusive — a daemon op \
2634                 does not participate in cycle-pool ratio scheduling."
2635            ));
2636        }
2637    }
2638    if !daemon_enabled && daemon_cancel_grace_ms.is_some() {
2639        return Err(format!(
2640            "op '{name}' (block '{block_name}'): \
2641             `daemon_cancel_grace_ms` is only meaningful when \
2642             `daemon:` is enabled (true / N). Either enable `daemon:` \
2643             or drop the grace field."
2644        ));
2645    }
2646
2647    // Loop / rate primitives (apply to both cycle-pool and
2648    // daemon ops, though the typical use case is daemon+while+rate).
2649    let while_cond = map
2650        .get("while")
2651        .and_then(|v| v.as_str())
2652        .map(|s| s.trim().to_string())
2653        .filter(|s| !s.is_empty());
2654    let rate = map.get("rate").and_then(|v| {
2655        v.as_str()
2656            .map(|s| s.to_string())
2657            .or_else(|| v.as_u64().map(|n| n.to_string()))
2658            .or_else(|| v.as_f64().map(|f| f.to_string()))
2659    });
2660    // Rate without while- or per-cycle dispatch is meaningless —
2661    // an op that fires once-per-cycle can't be rate-limited in
2662    // any observable way. Warn at parse rather than silently
2663    // accepting a no-op field.
2664    if rate.is_some() && while_cond.is_none() && daemon.is_disabled() {
2665        // Soft warn via stderr; this is a workload-shape smell
2666        // but not always an error (a workload-author may be
2667        // configuring forward-compatible op templates).
2668        eprintln!(
2669            "warning: op '{name}' (block '{block_name}'): `rate:` is set \
2670             but the op has neither `while:` nor `daemon:`. The rate \
2671             limit will only fire on each cycle-pool dispatch — likely \
2672             not the intended behavior. Add `while:` for a loop or \
2673             `daemon:` to enable fiber-kind dispatch.",
2674        );
2675    }
2676
2677    let metrics = parse_metrics_field(map.get("metrics"), &name, &mut op_bindings)
2678        .map_err(|e| format!("op '{name}' metrics: {e}"))?;
2679    let cell = parse_cell_map(map.get("cell")).map_err(|e| format!("op '{name}' {e}"))?;
2680    let traverse = parse_traverse_field(map.get("traverse"), &name)?;
2681    let result = parse_result_field(map.get("result"), &name)
2682        .map_err(|e| format!("op '{name}' result: {e}"))?;
2683
2684    // Extract capture-point specs from every string-valued entry in
2685    // `op` and replace each value with the bracket-stripped form.
2686    // Adapters consume the cleaned text; `TraversingDispenser` and
2687    // other capture-aware wrappers read the harvested specs from
2688    // `ParsedOp.captures` directly — no re-parse at wrap-time.
2689    //
2690    // De-duplicates by `as_name` across multiple op-fields: the
2691    // same wire name appearing in two fields means the same
2692    // capture, not two separate writes.
2693    let mut captures: Vec<crate::bindpoints::CapturePoint> = Vec::new();
2694    // Declarative `capture:` map block — pulls JSON-Pointer-keyed
2695    // values out of structured response bodies (e.g. Jolokia
2696    // bulk-POST arrays). Each entry is a path string addressed
2697    // by [`serde_json::Value::pointer`]; a trailing `:count`
2698    // collapses the addressed sub-tree to a u64 count instead
2699    // of capturing it as-is. This complements the legacy
2700    // bracket form `[name]` embedded in op text — that form
2701    // still works for adapters whose statements have column
2702    // references; the declarative form is for adapters whose
2703    // responses are JSON and need positional / nested access.
2704    if let Some(cap_val) = map.get("capture") {
2705        let cap_obj = cap_val.as_object().ok_or_else(|| {
2706            format!(
2707                "op '{name}' (block '{block_name}'): `capture:` must be a \
2708             mapping of <wire-name> → <json-pointer-path>. Got {kind}.",
2709                kind = eval_value_kind(cap_val),
2710            )
2711        })?;
2712        for (wire_name, spec_val) in cap_obj.iter() {
2713            let raw = spec_val.as_str().ok_or_else(|| {
2714                format!(
2715                    "op '{name}' (block '{block_name}'): `capture.{wire_name}` \
2716                 must be a string (JSON-Pointer path, optionally with a \
2717                 `:count` suffix). Got {kind}.",
2718                    kind = eval_value_kind(spec_val),
2719                )
2720            })?;
2721            let (path, count, agg, row_filter) = match raw.strip_suffix(":count") {
2722                Some(p) => (p.to_string(), true, None, None),
2723                None => match parse_capture_agg_suffix(raw) {
2724                    Some(suffix) => (
2725                        suffix.path_prefix,
2726                        false,
2727                        Some(suffix.agg),
2728                        suffix.row_filter,
2729                    ),
2730                    None => (raw.to_string(), false, None, None),
2731                },
2732            };
2733            // Two accepted spellings, one meaning — but never a guess in
2734            // between:
2735            //
2736            //   `/value`, `/0/name`  RFC 6901 JSON-Pointer, used verbatim.
2737            //   `value`              a bare top-level member name, which is
2738            //                        exactly `/value` and normalized to it
2739            //                        here, so runtime has one form to resolve.
2740            //   ``                   the root document.
2741            //
2742            // A bare name may contain neither `/` nor `~`, and that is the
2743            // whole anti-ambiguity rule: `a/b` could be a pointer someone
2744            // forgot to lead with '/', or a member literally named "a/b"
2745            // (RFC 6901 spells that `/a~1b`), and `~0`/`~1` are pointer
2746            // escapes. Rather than pick a reading, name both and let the
2747            // author say which. `verify:`'s `field:` is a bare name by
2748            // definition, so an author moving between the two blocks lands
2749            // on the bare form naturally — it now works rather than erroring.
2750            let path = if path.is_empty() || path.starts_with('/') {
2751                path
2752            } else if !path.contains('/') && !path.contains('~') {
2753                format!("/{path}")
2754            } else {
2755                return Err(format!(
2756                    "op '{name}' (block '{block_name}'): \
2757                     `capture.{wire_name}` path '{path}' is ambiguous. Write \
2758                     a JSON-Pointer starting with '/' (e.g. '/{first}/...', \
2759                     escaping '~' as '~0' and '/' as '~1'), or a bare \
2760                     top-level member name containing neither '/' nor '~'. \
2761                     An empty path addresses the root document.",
2762                    first = path.split('/').next().unwrap_or(&path),
2763                ));
2764            };
2765            captures.push(crate::bindpoints::CapturePoint {
2766                row_filter,
2767                source_name: wire_name.clone(),
2768                as_name: wire_name.clone(),
2769                cast_type: None,
2770                slurp: false,
2771                path: Some(path),
2772                count,
2773                agg,
2774            });
2775        }
2776    }
2777    for value in op_fields.values_mut() {
2778        if let serde_json::Value::String(s) = value {
2779            let parsed = crate::bindpoints::parse_capture_points(s);
2780            if parsed.captures.is_empty() {
2781                continue;
2782            }
2783            for cap in parsed.captures {
2784                if !captures
2785                    .iter()
2786                    .any(|existing| existing.as_name == cap.as_name)
2787                {
2788                    captures.push(cap);
2789                }
2790            }
2791            *s = parsed.raw_template;
2792        }
2793    }
2794
2795    // Every op field and param is bind-point text the runtime
2796    // scans again later; refuse a malformed bind point here, where
2797    // the op and field can be named.
2798    for (section, fields) in [("field", &op_fields), ("param", &op_params)] {
2799        for (field, value) in fields.iter() {
2800            check_bind_points(value)
2801                .map_err(|e| format!("op '{name}' {section} '{field}': {e}"))?;
2802        }
2803    }
2804
2805    Ok(ParsedOp {
2806        traverse,
2807        name,
2808        description,
2809        op: op_fields,
2810        bindings: op_bindings,
2811        params: op_params,
2812        tags: op_tags,
2813        condition,
2814        delay,
2815        metrics,
2816        cell,
2817        result,
2818        wrappers: None,
2819        captures,
2820        abstract_interface,
2821        interface_bound: false,
2822        daemon,
2823        daemon_cancel_grace_ms,
2824        while_cond,
2825        rate,
2826    })
2827}
2828
2829/// Split an optional `where <field>='<value>'` predicate off the tail of an
2830/// aggregate's argument, returning `(field_expr, predicate)`.
2831///
2832/// `progress where kind='secondary index build'` →
2833/// `("progress", Some(("kind", "secondary index build")))`.
2834///
2835/// Single or double quotes; the value may contain spaces, which is why it is
2836/// quoted rather than whitespace-delimited.
2837fn split_capture_row_filter(arg: &str) -> (String, Option<(String, String)>) {
2838    let lower = arg.to_ascii_lowercase();
2839    let Some(idx) = lower.find(" where ") else {
2840        return (arg.trim().to_string(), None);
2841    };
2842    let field = arg[..idx].trim().to_string();
2843    let pred = arg[idx + " where ".len()..].trim();
2844    let Some((k, v)) = pred.split_once('=') else {
2845        return (arg.trim().to_string(), None);
2846    };
2847    let k = k.trim();
2848    let v = v.trim();
2849    let unquoted = v
2850        .strip_prefix('\'')
2851        .and_then(|r| r.strip_suffix('\''))
2852        .or_else(|| v.strip_prefix('"').and_then(|r| r.strip_suffix('"')));
2853    match unquoted {
2854        Some(val) if !k.is_empty() => (field, Some((k.to_string(), val.to_string()))),
2855        // An unquoted or malformed predicate is left alone rather than
2856        // silently half-applied — the caller then treats the whole string as a
2857        // field name and the unknown-field error names it.
2858        _ => (arg.trim().to_string(), None),
2859    }
2860}
2861
2862/// A declarative capture path split at its aggregation suffix.
2863struct CaptureAggSuffix {
2864    /// The path before the suffix; empty addresses the whole rows array.
2865    path_prefix: String,
2866    /// The fold the suffix names.
2867    agg: crate::bindpoints::CaptureAgg,
2868    /// The `where <field>='<value>'` row filter, as `(field, value)`.
2869    row_filter: Option<(String, String)>,
2870}
2871
2872/// Parses a `:min(field)` / `:max(field)` / `:sum(field)` suffix on a
2873/// declarative capture path, with an optional `where <field>='<value>'`
2874/// row filter inside the parentheses. Returns `None` when the spec
2875/// carries no recognized aggregation suffix.
2876fn parse_capture_agg_suffix(raw: &str) -> Option<CaptureAggSuffix> {
2877    use crate::bindpoints::CaptureAgg;
2878    if !raw.ends_with(')') {
2879        return None;
2880    }
2881    for (tag, make) in [
2882        (":min(", CaptureAgg::Min as fn(String) -> CaptureAgg),
2883        (":max(", CaptureAgg::Max as fn(String) -> CaptureAgg),
2884        (":sum(", CaptureAgg::Sum as fn(String) -> CaptureAgg),
2885    ] {
2886        if let Some(idx) = raw.rfind(tag) {
2887            let arg = &raw[idx + tag.len()..raw.len() - 1];
2888            let (field, row_filter) = split_capture_row_filter(arg);
2889            if !field.is_empty() && field.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
2890                return Some(CaptureAggSuffix {
2891                    path_prefix: raw[..idx].to_string(),
2892                    agg: make(field),
2893                    row_filter,
2894                });
2895            }
2896        }
2897    }
2898    None
2899}
2900
2901/// SRD-40b §1 + §2: parse the `metrics:` field on an op
2902/// template. Three YAML shapes accepted, dispatched on the
2903/// value's type:
2904///
2905/// - **Scalar** (bare string, §2.1): one metric with the
2906///   string as both family and `value:`.
2907/// - **Sequence** (list, §2.2): each entry is a bare-name
2908///   string OR a `name := <Polydat expression>` wire-expression.
2909///   Wire expressions are auto-injected into the op's
2910///   `bindings:` block; the metric is then a bare-name
2911///   reference to the new wire.
2912/// - **Mapping** (object, §2.3): canonical full-shape form
2913///   keyed by metric name. Each value is either a string
2914///   (treated as `value:`) or a full `MetricSpec` mapping.
2915fn parse_metrics_field(
2916    val: Option<&JVal>,
2917    op_name: &str,
2918    op_bindings: &mut BindingsDef,
2919) -> Result<HashMap<String, MetricSpec>, String> {
2920    use crate::model::MetricSpec;
2921    let Some(v) = val else {
2922        return Ok(HashMap::new());
2923    };
2924    let mut out: HashMap<String, MetricSpec> = HashMap::new();
2925    match v {
2926        JVal::String(s) => {
2927            let name = s.trim().to_string();
2928            if name.is_empty() {
2929                return Err("scalar form requires a metric name".into());
2930            }
2931            out.insert(
2932                name.clone(),
2933                MetricSpec {
2934                    value: name,
2935                    family: None,
2936                    kind: None,
2937                    unit: None,
2938                    format: None,
2939                    cell: Default::default(),
2940                },
2941            );
2942        }
2943        JVal::Array(items) => {
2944            for (idx, item) in items.iter().enumerate() {
2945                let raw = item.as_str().ok_or_else(|| {
2946                    format!(
2947                        "metrics list entry {idx}: must be a string \
2948                     (bare name or `name := <polydat expr>`)"
2949                    )
2950                })?;
2951                let trimmed = raw.trim();
2952                if let Some((name, expr)) = trimmed.split_once(":=") {
2953                    // Wire-expression form: declare the binding +
2954                    // register the metric.
2955                    let name = name.trim();
2956                    let expr = expr.trim();
2957                    if name.is_empty() || expr.is_empty() {
2958                        return Err(format!(
2959                            "metrics list entry {idx} '{raw}': wire \
2960                             expression must be `name := <expression>`"
2961                        ));
2962                    }
2963                    inject_wire_into_bindings(op_bindings, name, expr, op_name)?;
2964                    if out.contains_key(name) {
2965                        return Err(format!("duplicate metric wire '{name}' in metrics list"));
2966                    }
2967                    out.insert(
2968                        name.to_string(),
2969                        MetricSpec {
2970                            value: name.to_string(),
2971                            family: None,
2972                            kind: None,
2973                            unit: None,
2974                            format: None,
2975                            cell: Default::default(),
2976                        },
2977                    );
2978                } else {
2979                    // Bare-name form.
2980                    if trimmed.is_empty() {
2981                        return Err(format!("metrics list entry {idx}: empty name"));
2982                    }
2983                    if out.contains_key(trimmed) {
2984                        return Err(format!("duplicate metric '{trimmed}' in metrics list"));
2985                    }
2986                    out.insert(
2987                        trimmed.to_string(),
2988                        MetricSpec {
2989                            value: trimmed.to_string(),
2990                            family: None,
2991                            kind: None,
2992                            unit: None,
2993                            format: None,
2994                            cell: Default::default(),
2995                        },
2996                    );
2997                }
2998            }
2999        }
3000        JVal::Object(map) => {
3001            for (key, val) in map {
3002                if out.contains_key(key) {
3003                    return Err(format!("duplicate metric key '{key}' in metrics map"));
3004                }
3005                let mut spec = parse_metric_spec_value(val, key)?;
3006                // SRD-13d Phase 9 mapping-form auto-inject: if
3007                // `value:` isn't a bare name, promote it to an
3008                // op-template binding `<key> := <value>` and
3009                // replace the spec's `value:` with the bare key.
3010                // Mirrors the list-form `name := expr` flow.
3011                let value_trimmed = spec.value.trim();
3012                let bare = !value_trimmed.is_empty()
3013                    && value_trimmed
3014                        .chars()
3015                        .all(|c| c.is_alphanumeric() || c == '_');
3016                if !bare {
3017                    if !is_valid_ident(key) {
3018                        return Err(format!(
3019                            "metric '{key}' value '{value}' is a non-bare \
3020                             expression so the metric key must itself be a \
3021                             valid identifier (alphanumerics + underscore, \
3022                             not starting with a digit) so it can be used \
3023                             as a binding name. Rename the metric key, or \
3024                             move the expression into `bindings:` and set \
3025                             `value:` to the bare name.",
3026                            value = spec.value
3027                        ));
3028                    }
3029                    inject_wire_into_bindings(op_bindings, key, value_trimmed, op_name)?;
3030                    spec.value = key.clone();
3031                }
3032                out.insert(key.clone(), spec);
3033            }
3034        }
3035        _ => {
3036            return Err(format!(
3037                "metrics: expected scalar, sequence, or mapping; got {v:?}"
3038            ));
3039        }
3040    }
3041    Ok(out)
3042}
3043
3044/// Parse a phase-level `metrics:` field. Same three YAML shapes as
3045/// the op-level [`parse_metrics_field`] (scalar / sequence / mapping)
3046/// and the same [`MetricSpec`] schema, with one deliberate
3047/// difference: phase metrics do **not** auto-inject non-bare value
3048/// expressions into a `bindings:` block. Op metrics inject so the
3049/// closure-binding-economy walker can allocate magic-extern slots
3050/// (`body`/`count`/`ok`) for the value expression; phase metrics have
3051/// no result body and are pulled directly by the executor from
3052/// `__metric_<name>`, so the phase synthesiser emits
3053/// `volatile __metric_<name> := <value>` straight from the raw
3054/// `value:` expression preserved here.
3055/// Parse a phase-level `dimensions:` block.
3056///
3057/// ```yaml
3058/// dimensions:
3059///   tier: { type: str }
3060///   tier: str            # shorthand
3061/// ```
3062///
3063/// Unknown keys are rejected rather than dropped: a silently-ignored
3064/// dimension declaration would make a metric's `cell:` reference fail its
3065/// existence check for a reason nothing points at.
3066/// Check every `cell:` reference in a phase against its declared dimensions.
3067///
3068/// Both tiers are covered: the phase's own `metrics:` and each inline op's.
3069/// The error names the declared set, because the common failure is a name
3070/// declared one tier away rather than a nonsense name.
3071fn validate_cell_dimensions(
3072    phase_name: &str,
3073    dimensions: &std::collections::BTreeMap<String, crate::model::DimensionSpec>,
3074    ops: &[ParsedOp],
3075    phase_metrics: &HashMap<String, MetricSpec>,
3076) -> Result<(), String> {
3077    let declared = || {
3078        if dimensions.is_empty() {
3079            "none are declared on this phase".to_string()
3080        } else {
3081            format!(
3082                "declared here: {}",
3083                dimensions.keys().cloned().collect::<Vec<_>>().join(", ")
3084            )
3085        }
3086    };
3087    let check =
3088        |site: &str, cell: &std::collections::BTreeMap<String, String>| -> Result<(), String> {
3089            for dim in cell.keys() {
3090                if !dimensions.contains_key(dim) {
3091                    return Err(format!(
3092                        "phase '{phase_name}' {site}: cell \
3093                     dimension '{dim}' is not declared. A dimension is a label \
3094                     name owned by exactly one tier, so declare it on the phase \
3095                     ({dim}: str) before placing a measurement in it — {}",
3096                        declared()
3097                    ));
3098                }
3099            }
3100            Ok(())
3101        };
3102    for (name, spec) in phase_metrics {
3103        check(&format!("phase-level metric '{name}'"), &spec.cell)?;
3104    }
3105    for op in ops {
3106        for (name, spec) in &op.metrics {
3107            check(&format!("op '{}' metric '{name}'", op.name), &spec.cell)?;
3108        }
3109        check(&format!("op '{}'", op.name), &op.cell)?;
3110    }
3111    Ok(())
3112}
3113
3114/// Parse a `cell:` placement: `<dimension>: <polydat expression>`.
3115///
3116/// One grammar for a metric's `cell:` and an op's. Each expression is
3117/// reified by scope synthesis as a typed kernel binding, so a
3118/// coordinate is compiled and checkable rather than a string assembled
3119/// at runtime. The error starts at `cell`; the caller names the site.
3120fn parse_cell_map(
3121    val: Option<&JVal>,
3122) -> Result<std::collections::BTreeMap<String, String>, String> {
3123    let mut cell = std::collections::BTreeMap::new();
3124    match val {
3125        None => {}
3126        Some(JVal::Object(dims)) => {
3127            if dims.is_empty() {
3128                return Err("cell: empty. Omit `cell:` entirely, or name at least one \
3129                     dimension."
3130                    .to_string());
3131            }
3132            for (dim, expr) in dims {
3133                let expr = expr.as_str().ok_or_else(|| {
3134                    format!("cell '{dim}': expected a polydat expression string, got {expr:?}")
3135                })?;
3136                if expr.trim().is_empty() {
3137                    return Err(format!("cell '{dim}': empty expression"));
3138                }
3139                if !is_valid_ident(dim) {
3140                    return Err(format!(
3141                        "cell '{dim}': a dimension name becomes a metric label, so it \
3142                         must be a valid identifier (alphanumerics + underscore, not \
3143                         starting with a digit)"
3144                    ));
3145                }
3146                cell.insert(dim.clone(), expr.trim().to_string());
3147            }
3148        }
3149        Some(other) => {
3150            return Err(format!(
3151                "cell: expected a mapping of <dimension>: <expression>, got {other:?}"
3152            ));
3153        }
3154    }
3155    Ok(cell)
3156}
3157
3158fn parse_dimensions_field(
3159    val: Option<&JVal>,
3160    phase_name: &str,
3161) -> Result<std::collections::BTreeMap<String, crate::model::DimensionSpec>, String> {
3162    use crate::model::{DimensionSpec, DimensionType};
3163    let mut out = std::collections::BTreeMap::new();
3164    let Some(v) = val else { return Ok(out) };
3165    let JVal::Object(map) = v else {
3166        return Err(format!(
3167            "phase '{phase_name}' dimensions: expected a mapping of \
3168             <name>: <declaration>, got {v:?}"
3169        ));
3170    };
3171    for (name, decl) in map {
3172        if !is_valid_ident(name) {
3173            return Err(format!(
3174                "phase '{phase_name}' dimension '{name}': a dimension name \
3175                 becomes a metric label, so it must be a valid identifier \
3176                 (alphanumerics + underscore, not starting with a digit)"
3177            ));
3178        }
3179        let value_type = match decl {
3180            // Shorthand: `tier: str`
3181            JVal::String(s) => parse_dimension_type(s, phase_name, name)?,
3182            JVal::Object(obj) => {
3183                for k in obj.keys() {
3184                    if k != "type" {
3185                        return Err(format!(
3186                            "phase '{phase_name}' dimension '{name}': unknown \
3187                             field `{k}`. Recognised fields: type"
3188                        ));
3189                    }
3190                }
3191                match obj.get("type") {
3192                    None => DimensionType::default(),
3193                    Some(JVal::String(s)) => parse_dimension_type(s, phase_name, name)?,
3194                    Some(other) => {
3195                        return Err(format!(
3196                            "phase '{phase_name}' dimension '{name}' type: \
3197                         expected a string, got {other:?}"
3198                        ));
3199                    }
3200                }
3201            }
3202            other => {
3203                return Err(format!(
3204                    "phase '{phase_name}' dimension '{name}': expected a type \
3205                 name or a mapping, got {other:?}"
3206                ));
3207            }
3208        };
3209        out.insert(name.clone(), DimensionSpec { value_type });
3210    }
3211    Ok(out)
3212}
3213
3214fn parse_dimension_type(
3215    s: &str,
3216    phase_name: &str,
3217    dim: &str,
3218) -> Result<crate::model::DimensionType, String> {
3219    let written = s.trim();
3220    match crate::port_types::resolve_type_keyword(written) {
3221        Ok(crate::port_types::PortType::Str) => Ok(crate::model::DimensionType::Str),
3222        Ok(other) => Err(format!(
3223            "phase '{phase_name}' dimension '{dim}' type '{other}': label \
3224             values are strings; `str` is the only supported type"
3225        )),
3226        Err(e) => Err(format!("phase '{phase_name}' dimension '{dim}': {e}")),
3227    }
3228}
3229
3230fn parse_phase_metrics_field(
3231    val: Option<&JVal>,
3232    phase_name: &str,
3233) -> Result<HashMap<String, MetricSpec>, String> {
3234    use crate::model::MetricSpec;
3235    let Some(v) = val else {
3236        return Ok(HashMap::new());
3237    };
3238    let mut out: HashMap<String, MetricSpec> = HashMap::new();
3239    match v {
3240        JVal::String(s) => {
3241            // Scalar: a bare wire name used as both family and value.
3242            let name = s.trim().to_string();
3243            if name.is_empty() {
3244                return Err("scalar form requires a metric name".into());
3245            }
3246            out.insert(
3247                name.clone(),
3248                MetricSpec {
3249                    value: name,
3250                    family: None,
3251                    kind: None,
3252                    unit: None,
3253                    format: None,
3254                    cell: Default::default(),
3255                },
3256            );
3257        }
3258        JVal::Array(items) => {
3259            // Sequence: bare wire names only (no `name := expr` form —
3260            // phase metrics don't inject bindings).
3261            for (idx, item) in items.iter().enumerate() {
3262                let raw = item
3263                    .as_str()
3264                    .ok_or_else(|| format!("metrics list entry {idx}: must be a bare wire name"))?;
3265                let name = raw.trim();
3266                if name.is_empty() {
3267                    return Err(format!("metrics list entry {idx}: empty name"));
3268                }
3269                if name.contains(":=") {
3270                    return Err(format!(
3271                        "metrics list entry {idx} '{raw}': the `name := expr` \
3272                         form is op-only; for a phase, declare the wire in the \
3273                         phase `bindings:` block and list its bare name here, \
3274                         or use the mapping form `{{ {name}: {{ value: <expr> }} }}`"
3275                    ));
3276                }
3277                if out.contains_key(name) {
3278                    return Err(format!("duplicate metric '{name}' in metrics list"));
3279                }
3280                out.insert(
3281                    name.to_string(),
3282                    MetricSpec {
3283                        value: name.to_string(),
3284                        family: None,
3285                        kind: None,
3286                        unit: None,
3287                        format: None,
3288                        cell: Default::default(),
3289                    },
3290                );
3291            }
3292        }
3293        JVal::Object(map) => {
3294            // Mapping: canonical full-shape form. Raw `value:` kept.
3295            for (key, val) in map {
3296                if out.contains_key(key) {
3297                    return Err(format!("duplicate metric key '{key}' in metrics map"));
3298                }
3299                out.insert(key.clone(), parse_metric_spec_value(val, key)?);
3300            }
3301        }
3302        _ => {
3303            return Err(format!(
3304                "phase '{phase_name}' metrics: expected scalar, sequence, or \
3305             mapping; got {v:?}"
3306            ));
3307        }
3308    }
3309    Ok(out)
3310}
3311
3312/// Parse one entry under the mapping form of `metrics:`.
3313/// Accepts a bare string (treated as `value:`) or a full
3314/// `MetricSpec` object.
3315fn parse_metric_spec_value(v: &JVal, key: &str) -> Result<crate::model::MetricSpec, String> {
3316    use crate::model::MetricSpec;
3317    match v {
3318        JVal::String(s) => Ok(MetricSpec {
3319            value: s.clone(),
3320            family: None,
3321            kind: None,
3322            unit: None,
3323            format: None,
3324            cell: Default::default(),
3325        }),
3326        JVal::Object(map) => {
3327            // SRD-30 unknown-field hygiene: reject any key outside the
3328            // MetricSpec surface rather than silently dropping it (a
3329            // dropped `kind:` would let a counter/histogram silently
3330            // default to gauge). The instrument-type discriminator is
3331            // `kind`, not `type` — `type` is the word OpenMetrics /
3332            // Prometheus use, so it's the predictable mistake; give it
3333            // a targeted hint.
3334            const KNOWN: &[&str] = &["value", "family", "kind", "unit", "format", "cell"];
3335            for k in map.keys() {
3336                if KNOWN.contains(&k.as_str()) {
3337                    continue;
3338                }
3339                let hint = if k == "type" {
3340                    " — the instrument-type discriminator is `kind` \
3341                     (gauge | histogram | counter)"
3342                } else {
3343                    ""
3344                };
3345                return Err(format!(
3346                    "metric '{key}': unknown field `{k}`{hint}. Recognised \
3347                     fields: value, family, kind, unit, format, cell"
3348                ));
3349            }
3350            let value = map
3351                .get("value")
3352                .and_then(|v| v.as_str())
3353                .ok_or_else(|| {
3354                    format!(
3355                        "metric '{key}': required field `value:` missing or \
3356                     not a string"
3357                    )
3358                })?
3359                .to_string();
3360            let family = map.get("family").and_then(|v| v.as_str()).map(String::from);
3361            let unit = map.get("unit").and_then(|v| v.as_str()).map(String::from);
3362            let format = map.get("format").and_then(|v| v.as_str()).map(String::from);
3363            // Validate format syntax at parse time so the user
3364            // hears about a bad `#.##` pattern at workload
3365            // load, not first-cycle. SRD-40b §1.
3366            if let Some(f) = format.as_deref() {
3367                crate::metric_format::parse_format_spec(f)
3368                    .map_err(|e| format!("metric '{key}' format '{f}': {e}"))?;
3369            }
3370            let kind = match map.get("kind") {
3371                None => None,
3372                Some(JVal::String(s)) => Some(parse_metric_kind(s, key)?),
3373                Some(other) => {
3374                    return Err(format!(
3375                        "metric '{key}' kind: expected string, got {other:?}"
3376                    ));
3377                }
3378            };
3379            let cell =
3380                parse_cell_map(map.get("cell")).map_err(|e| format!("metric '{key}' {e}"))?;
3381            Ok(MetricSpec {
3382                value,
3383                family,
3384                kind,
3385                unit,
3386                format,
3387                cell,
3388            })
3389        }
3390        _ => Err(format!(
3391            "metric '{key}': expected string or mapping, got {v:?}"
3392        )),
3393    }
3394}
3395
3396fn parse_metric_kind(s: &str, key: &str) -> Result<crate::model::MetricKind, String> {
3397    use crate::model::MetricKind;
3398    match s.to_ascii_lowercase().as_str() {
3399        "gauge" => Ok(MetricKind::Gauge),
3400        "histogram" => Ok(MetricKind::Histogram),
3401        "counter" => Ok(MetricKind::Counter),
3402        other => Err(format!(
3403            "metric '{key}' kind '{other}': expected one of \
3404             gauge / histogram / counter"
3405        )),
3406    }
3407}
3408
3409/// Auto-inject `name := expr` into the op template's
3410/// `bindings:` block (per SRD-40b §2.2). Conflicts with an
3411/// existing declaration of the same name are a strict
3412/// workload parse error per §2.2.
3413fn inject_wire_into_bindings(
3414    bindings: &mut BindingsDef,
3415    name: &str,
3416    expr: &str,
3417    op_name: &str,
3418) -> Result<(), String> {
3419    // Look for an existing same-name declaration to refuse
3420    // shadowing. The check is textual: a line beginning with
3421    // `<name>` followed by whitespace + `:=`. Prefix matching
3422    // would surface false positives for `foo` vs `foobar`,
3423    // hence the boundary check.
3424    let line_to_inject = format!("{name} := {expr}\n");
3425    // BindingsDef has no `Empty` variant — `Map(empty)` is the
3426    // default. Detect emptiness via the existing helper, then
3427    // promote to PolydatSource for injection (we're adding a real
3428    // Polydat statement, not a name→expr pair the legacy Map form
3429    // can't carry alone).
3430    if bindings.is_empty() {
3431        *bindings = BindingsDef::PolydatSource(line_to_inject);
3432        return Ok(());
3433    }
3434    match bindings {
3435        BindingsDef::PolydatSource(src) => {
3436            if has_binding_named(src, name) {
3437                return Err(format!(
3438                    "metric wire '{name}' (op '{op_name}') collides \
3439                     with existing `bindings:` declaration of the \
3440                     same name"
3441                ));
3442            }
3443            if !src.ends_with('\n') {
3444                src.push('\n');
3445            }
3446            src.push_str(&line_to_inject);
3447        }
3448        BindingsDef::Map(map) => {
3449            if map.contains_key(name) {
3450                return Err(format!(
3451                    "metric wire '{name}' (op '{op_name}') collides \
3452                     with existing `bindings:` declaration of the \
3453                     same name"
3454                ));
3455            }
3456            map.insert(name.to_string(), expr.to_string());
3457        }
3458    }
3459    Ok(())
3460}
3461
3462/// True when `s` is a valid Polydat identifier: non-empty, first
3463/// char is a letter or underscore, remaining chars are
3464/// alphanumerics or underscore. Used by the mapping-form
3465/// metric auto-inject to confirm the metric key can stand in
3466/// as a binding name.
3467fn is_valid_ident(s: &str) -> bool {
3468    let mut chars = s.chars();
3469    match chars.next() {
3470        Some(c) if c.is_alphabetic() || c == '_' => {}
3471        _ => return false,
3472    }
3473    chars.all(|c| c.is_alphanumeric() || c == '_')
3474}
3475
3476/// True when the Polydat source contains a binding line
3477/// `<name> := …` at the start of any (whitespace-trimmed)
3478/// line. Used by the wire-expression injection to detect
3479/// shadowing without parsing the Polydat grammar.
3480fn has_binding_named(src: &str, name: &str) -> bool {
3481    for raw in src.lines() {
3482        let line = raw.trim_start();
3483        if let Some(rest) = line.strip_prefix(name) {
3484            // Boundary: next char must be whitespace or `:=`.
3485            let rest = rest.trim_start();
3486            if rest.starts_with(":=") {
3487                return true;
3488            }
3489        }
3490    }
3491    false
3492}
3493
3494/// Parse an op's `traverse:` block.
3495///
3496/// Customises the always-installed traversal layer; it does not select it, so
3497/// absence means "defaults", not "no traversal". Unknown keys are rejected
3498/// rather than dropped — a silently ignored `on_missing:` would leave the
3499/// author believing absent captures are being policed when they are not.
3500fn parse_traverse_field(
3501    val: Option<&JVal>,
3502    op_name: &str,
3503) -> Result<Option<crate::model::TraverseSpec>, String> {
3504    use crate::model::{OnMissing, TraverseSpec};
3505    let Some(v) = val else { return Ok(None) };
3506    let JVal::Object(map) = v else {
3507        return Err(format!(
3508            "op '{op_name}' traverse: expected a mapping, got {v:?}"
3509        ));
3510    };
3511    const KNOWN: &[&str] = &["path", "on_missing"];
3512    for k in map.keys() {
3513        if !KNOWN.contains(&k.as_str()) {
3514            return Err(format!(
3515                "op '{op_name}' traverse: unknown field `{k}`. Recognised \
3516                 fields: path, on_missing"
3517            ));
3518        }
3519    }
3520    let path = match map.get("path") {
3521        None => None,
3522        Some(JVal::String(p)) => {
3523            let p = p.trim();
3524            if !p.is_empty() && !p.starts_with('/') {
3525                return Err(format!(
3526                    "op '{op_name}' traverse: path '{p}' must start with '/' \
3527                     (RFC 6901 JSON-Pointer); an empty path addresses the root"
3528                ));
3529            }
3530            Some(p.to_string())
3531        }
3532        Some(other) => {
3533            return Err(format!(
3534                "op '{op_name}' traverse: path expected a string, got {other:?}"
3535            ));
3536        }
3537    };
3538    let on_missing = match map.get("on_missing") {
3539        None => OnMissing::default(),
3540        Some(JVal::String(s)) => match s.trim().to_ascii_lowercase().as_str() {
3541            "ignore" => OnMissing::Ignore,
3542            "warn" => OnMissing::Warn,
3543            "error" | "fail" => OnMissing::Error,
3544            other => {
3545                return Err(format!(
3546                    "op '{op_name}' traverse: on_missing '{other}': expected one of \
3547                 ignore / warn / error"
3548                ));
3549            }
3550        },
3551        Some(other) => {
3552            return Err(format!(
3553                "op '{op_name}' traverse: on_missing expected a string, got {other:?}"
3554            ));
3555        }
3556    };
3557    Ok(Some(TraverseSpec { path, on_missing }))
3558}
3559
3560/// SRD-66 §"Surface 1 §Schema": parse the vari-structured
3561/// `result:` field on an op template. Three shapes:
3562///
3563/// - **String** scalar — Polydat source block (multi-line or
3564///   single-line). Each `<name> := <expr>` declares one
3565///   wire.
3566/// - **List** sequence — each element is itself a
3567///   `ResultSpec` (recursively); fragments concatenate.
3568/// - **Mapping** — named-key short-forms; each value is a
3569///   string parsed as `count` / `ok` / path-expr / Polydat expr.
3570fn parse_result_field(
3571    val: Option<&JVal>,
3572    op_name: &str,
3573) -> Result<Option<crate::model::ResultSpec>, String> {
3574    let Some(v) = val else {
3575        return Ok(None);
3576    };
3577    let spec = parse_result_spec(v, op_name)?;
3578    if spec.is_empty() {
3579        Ok(None)
3580    } else {
3581        Ok(Some(spec))
3582    }
3583}
3584
3585fn parse_result_spec(v: &JVal, op_name: &str) -> Result<crate::model::ResultSpec, String> {
3586    use crate::model::ResultSpec;
3587    match v {
3588        JVal::Null => Ok(ResultSpec::String(String::new())),
3589        JVal::String(s) => Ok(ResultSpec::String(s.clone())),
3590        JVal::Array(items) => {
3591            let mut out: Vec<ResultSpec> = Vec::with_capacity(items.len());
3592            for item in items {
3593                out.push(parse_result_spec(item, op_name)?);
3594            }
3595            Ok(ResultSpec::List(out))
3596        }
3597        JVal::Object(map) => {
3598            let mut out: std::collections::BTreeMap<String, String> =
3599                std::collections::BTreeMap::new();
3600            for (key, val) in map {
3601                let source = match val {
3602                    JVal::String(s) => s.clone(),
3603                    JVal::Null => String::new(),
3604                    other => {
3605                        return Err(format!(
3606                            "op '{op_name}' result.{key}: expected string \
3607                         (short-form keyword `count`/`ok`, path \
3608                         expression, or Polydat expression); got {other}"
3609                        ));
3610                    }
3611                };
3612                if out.insert(key.clone(), source).is_some() {
3613                    return Err(format!("op '{op_name}' result: duplicate key '{key}'"));
3614                }
3615            }
3616            Ok(ResultSpec::Map(out))
3617        }
3618        _ => Err(format!(
3619            "op '{op_name}' result: expected string (GK source), \
3620             list (sequence of fragments), or mapping (named \
3621             short-forms); got {v}"
3622        )),
3623    }
3624}
3625
3626// -----------------------------------------------------------------
3627// Helpers
3628// -----------------------------------------------------------------
3629
3630/// Extract bindings from a YAML value.
3631///
3632/// If the value is a string, it's native Polydat grammar source.
3633/// If it's a mapping, it's legacy name→expression pairs.
3634fn extract_bindings(val: Option<&JVal>) -> BindingsDef {
3635    match val {
3636        Some(JVal::String(s)) => BindingsDef::PolydatSource(s.clone()),
3637        Some(JVal::Object(obj)) => {
3638            let mut map = HashMap::new();
3639            for (k, v) in obj {
3640                if let Some(s) = v.as_str() {
3641                    map.insert(k.clone(), s.to_string());
3642                } else {
3643                    map.insert(k.clone(), v.to_string());
3644                }
3645            }
3646            BindingsDef::Map(map)
3647        }
3648        _ => BindingsDef::default(),
3649    }
3650}
3651
3652/// SRD-13f Push D: inline a block's YAML-level `bindings:`
3653/// sugar into one of its enclosed ops.
3654///
3655/// Blocks are not a Polydat scope — they're YAML authoring sugar
3656/// (named groups for tag-filtering + shared defaults). A
3657/// block-level `bindings:` field is *syntactic sugar* meaning
3658/// "every op underneath has these bindings as part of its own
3659/// op-level bindings." This helper does that expansion at
3660/// parse time.
3661///
3662/// Semantics (preserves prior `merge_bindings` shape for the
3663/// only call site that still uses it):
3664/// - The op's own PolydatSource fully shadows the block's sugar
3665///   (the op declares its full binding set explicitly).
3666/// - Op Map merges with block Map (op keys override block).
3667/// - Empty op inherits the block sugar verbatim.
3668///
3669/// No cross-scope semantics: workload-level and phase-level
3670/// `bindings:` no longer flow through this helper. They reach
3671/// ops via the Polydat Kernel chain.
3672fn inline_block_sugar_into_op(block_sugar: &BindingsDef, op_own: &BindingsDef) -> BindingsDef {
3673    match (block_sugar, op_own) {
3674        (_, BindingsDef::PolydatSource(s)) if !s.trim().is_empty() => {
3675            BindingsDef::PolydatSource(s.clone())
3676        }
3677        (BindingsDef::Map(p), BindingsDef::Map(c)) => {
3678            let mut merged = p.clone();
3679            for (k, v) in c {
3680                merged.insert(k.clone(), v.clone());
3681            }
3682            BindingsDef::Map(merged)
3683        }
3684        (_, BindingsDef::Map(c)) if c.is_empty() => block_sugar.clone(),
3685        (_, child) => child.clone(),
3686    }
3687}
3688
3689/// Render a YAML/JSON param value as the text form
3690/// `add_param_binding` expects.
3691///
3692/// Scalar shapes pass through RAW (no extra quoting): a YAML
3693/// `iter_count: "3"` and a YAML `iter_count: 3` BOTH come out as
3694/// the string `"3"` here — the downstream classifier sees
3695/// numeric-shape and emits a bare U64 binding either way. YAML's
3696/// quotes are presentation, not semantic, for scalars.
3697///
3698/// Array shape gets the polydat array literal form
3699/// (`[v1, v2, v3]`) — that's the new convention the workload
3700/// surface needs to support. Array ELEMENTS are formatted with
3701/// polydat literal grammar (strings explicitly quoted) since
3702/// polydat's parser requires quotes inside array literals;
3703/// `format_jval_in_array_context` handles the recursion.
3704///
3705/// Object shape (rare for params) falls back to JSON
3706/// serialization — there's no polydat literal form for objects,
3707/// so the value passes through whatever-it-is for callers
3708/// downstream to handle.
3709pub(crate) fn format_jval_as_polydat_literal(v: &JVal) -> String {
3710    match v {
3711        JVal::Null => String::new(),
3712        JVal::Bool(b) => b.to_string(),
3713        JVal::Number(n) => n.to_string(),
3714        // Scalar strings pass through unquoted to preserve the
3715        // legacy "YAML quotes are presentation" behavior. The
3716        // downstream classifier (`add_param_binding`) figures
3717        // out the actual type from the content — numeric-shape
3718        // becomes U64/F64, identifier-shape becomes a reference,
3719        // string-shape becomes a polydat-quoted Str.
3720        JVal::String(s) => s.clone(),
3721        JVal::Array(items) => {
3722            let elts: Vec<String> = items.iter().map(format_jval_in_array_context).collect();
3723            format!("[{}]", elts.join(", "))
3724        }
3725        JVal::Object(_) => v.to_string(),
3726    }
3727}
3728
3729/// Element-context formatter: polydat array literals require
3730/// explicit quotes around string elements (`["a", "b"]`), unlike
3731/// the scalar-context formatter which leaves strings unquoted.
3732fn format_jval_in_array_context(v: &JVal) -> String {
3733    match v {
3734        JVal::String(s) => {
3735            let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
3736            format!("\"{escaped}\"")
3737        }
3738        JVal::Array(items) => {
3739            let elts: Vec<String> = items.iter().map(format_jval_in_array_context).collect();
3740            format!("[{}]", elts.join(", "))
3741        }
3742        _ => format_jval_as_polydat_literal(v),
3743    }
3744}
3745
3746fn extract_string_map(val: Option<&JVal>) -> HashMap<String, String> {
3747    let mut map = HashMap::new();
3748    if let Some(JVal::Object(obj)) = val {
3749        for (k, v) in obj {
3750            // Format every YAML value as polydat-native source.
3751            // Strings come out quote-wrapped, arrays as
3752            // `[a, b, c]`, numbers / bools bare. The downstream
3753            // `add_param_binding` classifier reads this and emits
3754            // the const binding without re-quoting.
3755            map.insert(k.clone(), format_jval_as_polydat_literal(v));
3756        }
3757    }
3758    map
3759}
3760
3761// Shared classifier helpers — the `set:` block parser routes
3762// every value through the same shape detection so the numeric /
3763// array-literal / quoted-string surface is consistent.
3764
3765fn is_polydat_quoted_string(s: &str) -> bool {
3766    if s.len() < 2 {
3767        return false;
3768    }
3769    if !s.starts_with('"') || !s.ends_with('"') {
3770        return false;
3771    }
3772    let bytes = s.as_bytes();
3773    let mut i = 1;
3774    let last = bytes.len() - 1;
3775    while i < last {
3776        if bytes[i] == b'\\' {
3777            i += 2;
3778            continue;
3779        }
3780        if bytes[i] == b'"' {
3781            return false;
3782        }
3783        i += 1;
3784    }
3785    true
3786}
3787
3788fn extract_value_map(val: Option<&JVal>) -> HashMap<String, JVal> {
3789    let mut map = HashMap::new();
3790    if let Some(JVal::Object(obj)) = val {
3791        for (k, v) in obj {
3792            map.insert(k.clone(), v.clone());
3793        }
3794    }
3795    map
3796}
3797
3798fn merge_string_maps(
3799    parent: &HashMap<String, String>,
3800    child: &HashMap<String, String>,
3801) -> HashMap<String, String> {
3802    let mut merged = parent.clone();
3803    for (k, v) in child {
3804        merged.insert(k.clone(), v.clone());
3805    }
3806    merged
3807}
3808
3809/// Activity/phase-scope param keys that must never be blast-merged onto ops.
3810/// They are consumed at phase/activity scope; leaking them into op `params`
3811/// makes an inherited `rate` collide with the `rate` wrapper's
3812/// field-ownership guard (SRD-32a). The op-level `rate:` field reaches ops via
3813/// the typed [`ParsedOp::rate`] path, not params, so this exclusion is safe.
3814const ACTIVITY_PARAM_KEYS: &[&str] = &["cycles", "concurrency", "rate", "errors", "error_rate_max"];
3815
3816/// The workload `params:` keys that select its DEFAULT adapter. An op never
3817/// inherits them: an op's `params.adapter` is an op-level override, which
3818/// outranks the phase's `adapter:`, so an inherited copy would outrank it
3819/// too and a phase could never override the workload default. An op's own
3820/// `adapter:` is written on the op and is untouched; a CLI `adapter=` still
3821/// overlays every op (SRD 21, the outermost layer).
3822const ADAPTER_SELECTOR_KEYS: &[&str] = &["adapter", "driver"];
3823
3824/// Clone `params` minus the keys an op never inherits from an enclosing
3825/// `params:` block ([`ACTIVITY_PARAM_KEYS`], [`ADAPTER_SELECTOR_KEYS`]).
3826fn exclude_non_op_keys(params: &HashMap<String, JVal>) -> HashMap<String, JVal> {
3827    params
3828        .iter()
3829        .filter(|(k, _)| {
3830            !ACTIVITY_PARAM_KEYS.contains(&k.as_str())
3831                && !ADAPTER_SELECTOR_KEYS.contains(&k.as_str())
3832        })
3833        .map(|(k, v)| (k.clone(), v.clone()))
3834        .collect()
3835}
3836
3837fn merge_value_maps(
3838    parent: &HashMap<String, JVal>,
3839    child: &HashMap<String, JVal>,
3840) -> HashMap<String, JVal> {
3841    let mut merged = parent.clone();
3842    for (k, v) in child {
3843        merged.insert(k.clone(), v.clone());
3844    }
3845    merged
3846}
3847
3848#[cfg(test)]
3849mod tests {
3850    use super::*;
3851
3852    /// A malformed bind point is refused when the workload is
3853    /// parsed, naming the op and the field or param that holds it.
3854    #[test]
3855    fn a_malformed_bind_point_is_refused_naming_its_op_and_field() {
3856        let yaml = |op_body: &str| {
3857            format!(
3858                "phases:\n  load:\n    ops:\n      write: {op_body}\nscenarios: {{ default: [load] }}\n"
3859            )
3860        };
3861        let err = parse_workload(
3862            &yaml(r#"{ stmt: "INSERT INTO t (id) VALUES ({id:String})" }"#),
3863            &HashMap::new(),
3864        )
3865        .expect_err("a retired type spelling on a bind point must be refused");
3866        assert_eq!(
3867            err.matches("op 'write' field 'stmt': bind point `{id:String}`: `String` is no longer a type keyword; write `str`").count(),
3868            1,
3869            "{err}"
3870        );
3871        let err = parse_workload(
3872            &yaml(r#"{ stmt: "op", params: { label: "{h:handle}" } }"#),
3873            &HashMap::new(),
3874        )
3875        .expect_err("an internal type on a bind point must be refused");
3876        assert!(
3877            err.contains(
3878                "op 'write' param 'label': bind point `{h:handle}`: `handle` is an internal type"
3879            ),
3880            "{err}"
3881        );
3882        parse_workload(
3883            &yaml(r#"{ stmt: "INSERT INTO t (id) VALUES ({id:str})" }"#),
3884            &HashMap::new(),
3885        )
3886        .expect("a type keyword on a bind point parses");
3887    }
3888
3889    #[test]
3890    fn phase_metrics_mapping_form_preserves_raw_value() {
3891        // Phase-level `metrics:` keeps the raw `value:` expression
3892        // (no bare-key injection into bindings — the phase synthesiser
3893        // emits `volatile __metric_<name> := <value>` directly).
3894        let yaml = r#"
3895phases:
3896  build_index:
3897    metrics:
3898      time_to_index: { value: "current_epoch_millis() - phase_start", kind: gauge }
3899    ops:
3900      work: { stmt: "op" }
3901scenarios:
3902  default: [build_index]
3903"#;
3904        let wl = parse_workload(yaml, &HashMap::new()).expect("parse");
3905        let phase = wl.phases.get("build_index").expect("phase build_index");
3906        let m = phase
3907            .metrics
3908            .get("time_to_index")
3909            .expect("time_to_index metric");
3910        assert_eq!(
3911            m.value, "current_epoch_millis() - phase_start",
3912            "raw value must be preserved verbatim"
3913        );
3914        assert_eq!(m.kind, Some(crate::model::MetricKind::Gauge));
3915        assert!(
3916            phase.bindings.is_empty(),
3917            "phase metrics must NOT auto-inject into bindings: {:?}",
3918            phase.bindings
3919        );
3920    }
3921
3922    #[test]
3923    fn tries_accepts_sugared_number_and_map_form() {
3924        // Sugared: a bare number sets the count, no backoff overrides.
3925        let sugar = r#"
3926phases:
3927  load:
3928    tries: 20
3929    ops: { work: { stmt: "op" } }
3930scenarios: { default: [load] }
3931"#;
3932        let wl = parse_workload(sugar, &HashMap::new()).expect("parse sugar");
3933        let p = wl.phases.get("load").unwrap();
3934        assert_eq!(p.tries, Some(20));
3935        assert_eq!(p.tries_backoff, None);
3936
3937        // Map form: `count` + nested `backoff` (durations kept as strings).
3938        let map = r#"
3939phases:
3940  load:
3941    tries:
3942      count: 20
3943      backoff:
3944        ratio: 2.0
3945        min: 100ms
3946        max: 10s
3947    ops: { work: { stmt: "op" } }
3948scenarios: { default: [load] }
3949"#;
3950        let wl = parse_workload(map, &HashMap::new()).expect("parse map");
3951        let p = wl.phases.get("load").unwrap();
3952        assert_eq!(p.tries, Some(20));
3953        let bo = p.tries_backoff.as_ref().expect("backoff parsed");
3954        assert_eq!(bo.ratio, Some(2.0));
3955        assert_eq!(bo.min.as_deref(), Some("100ms"));
3956        assert_eq!(bo.max.as_deref(), Some("10s"));
3957
3958        // A bad shape (string) is a loud parse error, not a silent drop.
3959        let bad = r#"
3960phases: { load: { tries: "lots", ops: { w: { stmt: "op" } } } }
3961scenarios: { default: [load] }
3962"#;
3963        assert!(
3964            parse_workload(bad, &HashMap::new()).is_err(),
3965            "non-number, non-map tries must fail to parse"
3966        );
3967    }
3968
3969    #[test]
3970    fn metric_spec_rejects_unknown_field_type_with_hint() {
3971        // `type:` is the OpenMetrics word; ours is `kind`. Reject it
3972        // loudly with a hint rather than silently dropping it (which
3973        // would default the metric to gauge).
3974        let yaml = r#"
3975phases:
3976  p:
3977    metrics:
3978      m: { type: counter, value: "x" }
3979    ops:
3980      work: { stmt: "op" }
3981scenarios:
3982  default: [p]
3983"#;
3984        let err = parse_workload(yaml, &HashMap::new())
3985            .expect_err("unknown metric field `type` must be rejected");
3986        assert!(
3987            err.contains("unknown field `type`"),
3988            "must name the offending field; got: {err}"
3989        );
3990        assert!(
3991            err.contains("kind"),
3992            "must hint at the canonical `kind` field; got: {err}"
3993        );
3994    }
3995
3996    #[test]
3997    fn metric_spec_rejects_arbitrary_unknown_field() {
3998        let yaml = r#"
3999phases:
4000  p:
4001    metrics:
4002      m: { value: "x", flavour: gauge }
4003    ops:
4004      work: { stmt: "op" }
4005scenarios:
4006  default: [p]
4007"#;
4008        let err = parse_workload(yaml, &HashMap::new())
4009            .expect_err("arbitrary unknown metric field must be rejected");
4010        assert!(
4011            err.contains("unknown field `flavour`"),
4012            "must name the offending field; got: {err}"
4013        );
4014    }
4015
4016    #[test]
4017    fn metric_spec_accepts_all_known_fields() {
4018        // Regression guard: the unknown-field check must not reject any
4019        // legitimate field.
4020        let yaml = r#"
4021phases:
4022  p:
4023    metrics:
4024      m: { value: "x", family: fam, kind: counter, unit: bytes, format: "0.00" }
4025    ops:
4026      work: { stmt: "op" }
4027scenarios:
4028  default: [p]
4029"#;
4030        let wl = parse_workload(yaml, &HashMap::new()).expect("all known fields accepted");
4031        let m = wl.phases.get("p").unwrap().metrics.get("m").unwrap();
4032        assert_eq!(m.kind, Some(crate::model::MetricKind::Counter));
4033        assert_eq!(m.unit.as_deref(), Some("bytes"));
4034        assert_eq!(m.family.as_deref(), Some("fam"));
4035    }
4036
4037    #[test]
4038    fn phase_metrics_list_form_rejects_wire_expression() {
4039        // The `name := expr` list form is op-only; for a phase the
4040        // author must use the phase `bindings:` block + a bare name,
4041        // or the mapping form. Reject loudly rather than silently.
4042        let yaml = r#"
4043phases:
4044  p:
4045    metrics:
4046      - "te := current_epoch_millis() - phase_start"
4047    ops:
4048      work: { stmt: "op" }
4049scenarios:
4050  default: [p]
4051"#;
4052        let err = parse_workload(yaml, &HashMap::new())
4053            .expect_err("list `name := expr` form must be rejected for phases");
4054        assert!(
4055            err.contains("op-only") || err.contains("mapping form"),
4056            "diagnostic should point at the op-only form; got: {err}"
4057        );
4058    }
4059
4060    #[test]
4061    fn readouts_block_form_a_scalar_binds_on_update() {
4062        let workload: serde_yaml::Value =
4063            serde_yaml::from_str(r#"readouts: phase_status"#).unwrap();
4064        let json = serde_json::to_value(&workload).unwrap();
4065        let r = parse_readouts_block(json.get("readouts")).unwrap();
4066        assert_eq!(r.on_update, vec!["phase_status".to_string()]);
4067        assert!(r.on_phase_end.is_empty());
4068    }
4069
4070    #[test]
4071    fn readouts_block_form_b_mapping_binds_explicit_slots() {
4072        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
4073            r#"
4074readouts:
4075  on_phase_end: phase_outcome
4076  on_update: "phase_status lod=compact"
4077"#,
4078        )
4079        .unwrap();
4080        let json = serde_json::to_value(&yaml).unwrap();
4081        let r = parse_readouts_block(json.get("readouts")).unwrap();
4082        assert_eq!(r.on_phase_end, vec!["phase_outcome".to_string()]);
4083        assert_eq!(r.on_update, vec!["phase_status lod=compact".to_string()]);
4084    }
4085
4086    #[test]
4087    fn readouts_block_form_c_list_composes() {
4088        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
4089            r#"
4090readouts:
4091  on_phase_end:
4092    - phase_outcome
4093    - phase_failure_hint
4094"#,
4095        )
4096        .unwrap();
4097        let json = serde_json::to_value(&yaml).unwrap();
4098        let r = parse_readouts_block(json.get("readouts")).unwrap();
4099        assert_eq!(
4100            r.on_phase_end,
4101            vec![
4102                "phase_outcome".to_string(),
4103                "phase_failure_hint".to_string(),
4104            ]
4105        );
4106    }
4107
4108    #[test]
4109    fn readouts_block_each_wildcard_expands() {
4110        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
4111            r#"
4112readouts:
4113  each_*: scope_bracket
4114"#,
4115        )
4116        .unwrap();
4117        let json = serde_json::to_value(&yaml).unwrap();
4118        let r = parse_readouts_block(json.get("readouts")).unwrap();
4119        assert_eq!(r.on_each_start, vec!["scope_bracket".to_string()]);
4120        assert_eq!(r.on_each_end, vec!["scope_bracket".to_string()]);
4121        // Other slots untouched.
4122        assert!(r.on_phase_end.is_empty());
4123        assert!(r.on_update.is_empty());
4124    }
4125
4126    #[test]
4127    fn readouts_block_phase_wildcard_expands() {
4128        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
4129            r#"
4130readouts:
4131  phase_*: trace
4132"#,
4133        )
4134        .unwrap();
4135        let json = serde_json::to_value(&yaml).unwrap();
4136        let r = parse_readouts_block(json.get("readouts")).unwrap();
4137        assert_eq!(r.on_phase_start, vec!["trace".to_string()]);
4138        assert_eq!(r.on_phase_end, vec!["trace".to_string()]);
4139        assert!(r.on_each_start.is_empty());
4140    }
4141
4142    #[test]
4143    fn readouts_block_universal_wildcard_expands_to_all() {
4144        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
4145            r#"
4146readouts:
4147  "*": trace
4148"#,
4149        )
4150        .unwrap();
4151        let json = serde_json::to_value(&yaml).unwrap();
4152        let r = parse_readouts_block(json.get("readouts")).unwrap();
4153        for slot in [
4154            &r.on_session_start,
4155            &r.on_session_end,
4156            &r.on_phase_start,
4157            &r.on_phase_end,
4158            &r.on_each_start,
4159            &r.on_each_end,
4160            &r.on_scope_start,
4161            &r.on_scope_end,
4162            &r.on_update,
4163        ] {
4164            assert_eq!(slot, &vec!["trace".to_string()]);
4165        }
4166    }
4167
4168    #[test]
4169    fn readouts_block_unknown_slot_is_error() {
4170        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
4171            r#"
4172readouts:
4173  on_unknown: phase_outcome
4174"#,
4175        )
4176        .unwrap();
4177        let json = serde_json::to_value(&yaml).unwrap();
4178        let err = parse_readouts_block(json.get("readouts")).unwrap_err();
4179        assert!(
4180            err.contains("unknown slot 'on_unknown'"),
4181            "wrong message: {err}"
4182        );
4183    }
4184
4185    #[test]
4186    fn parse_single_string_op() {
4187        let ops = parse_ops("op: select * from bar.table;").unwrap();
4188        assert_eq!(ops.len(), 1);
4189        assert_eq!(ops[0].name, "stmt1");
4190        assert_eq!(ops[0].op["stmt"], "select * from bar.table;");
4191    }
4192
4193    #[test]
4194    fn parse_ops_list_of_strings() {
4195        let yaml = r#"
4196ops:
4197  - select * from t1;
4198  - select * from t2;
4199"#;
4200        let ops = parse_ops(yaml).unwrap();
4201        assert_eq!(ops.len(), 2);
4202        assert_eq!(ops[0].op["stmt"], "select * from t1;");
4203        assert_eq!(ops[1].op["stmt"], "select * from t2;");
4204    }
4205
4206    #[test]
4207    fn parse_ops_map_of_strings() {
4208        let yaml = r#"
4209ops:
4210  read: select * from t1;
4211  write: insert into t1 values (1);
4212"#;
4213        let ops = parse_ops(yaml).unwrap();
4214        assert_eq!(ops.len(), 2);
4215        let read = ops.iter().find(|o| o.name == "read").unwrap();
4216        assert_eq!(read.op["stmt"], "select * from t1;");
4217    }
4218
4219    #[test]
4220    fn parse_named_blocks() {
4221        let yaml = r#"
4222blocks:
4223  schema:
4224    ops:
4225      create: "CREATE TABLE t (id int PRIMARY KEY);"
4226  main:
4227    ops:
4228      read: "SELECT * FROM t WHERE id={id};"
4229"#;
4230        let ops = parse_ops(yaml).unwrap();
4231        assert_eq!(ops.len(), 2);
4232        let create = ops.iter().find(|o| o.name == "create").unwrap();
4233        assert_eq!(create.tags["block"], "schema");
4234        let read = ops.iter().find(|o| o.name == "read").unwrap();
4235        assert_eq!(read.tags["block"], "main");
4236    }
4237
4238    #[test]
4239    fn parse_property_inheritance() {
4240        let yaml = r#"
4241bindings:
4242  id: Identity()
4243params:
4244  prepared: true
4245tags:
4246  workload: test
4247blocks:
4248  main:
4249    bindings:
4250      id: Hash()
4251    ops:
4252      op1: "SELECT * FROM t;"
4253"#;
4254        let ops = parse_ops(yaml).unwrap();
4255        assert_eq!(ops.len(), 1);
4256        // Block-level binding overrides doc-level
4257        assert_eq!(ops[0].bindings.as_map()["id"], "Hash()");
4258        // Doc-level param inherited
4259        assert_eq!(ops[0].params["prepared"], true);
4260        // Doc-level tag inherited
4261        assert_eq!(ops[0].tags["workload"], "test");
4262        // Auto-tag
4263        assert_eq!(ops[0].tags["block"], "main");
4264    }
4265
4266    /// The workload's default adapter is not an op-level override: an op
4267    /// inherits no `adapter` from `params:`, so a phase's `adapter:` can
4268    /// replace the default. An op's own `adapter:` stays on the op.
4269    #[test]
4270    fn an_op_does_not_inherit_the_workload_default_adapter() {
4271        let yaml = r#"
4272params:
4273  adapter: cql
4274  prepared: true
4275blocks:
4276  main:
4277    ops:
4278      plain: "SELECT * FROM t;"
4279      routed:
4280        adapter: stdout
4281        stmt: "hello"
4282"#;
4283        let ops = parse_ops(yaml).unwrap();
4284        let plain = ops.iter().find(|o| o.name == "plain").unwrap();
4285        let routed = ops.iter().find(|o| o.name == "routed").unwrap();
4286        assert!(!plain.params.contains_key("adapter"));
4287        assert_eq!(plain.params["prepared"], true);
4288        assert_eq!(routed.params["adapter"], "stdout");
4289    }
4290
4291    #[test]
4292    fn parse_auto_naming() {
4293        let yaml = r#"
4294ops:
4295  - "first op"
4296  - "second op"
4297"#;
4298        let ops = parse_ops(yaml).unwrap();
4299        assert_eq!(ops[0].name, "stmt1");
4300        assert_eq!(ops[1].name, "stmt2");
4301    }
4302
4303    #[test]
4304    fn parse_auto_tagging() {
4305        let yaml = r#"
4306ops:
4307  myop: "SELECT 1;"
4308"#;
4309        let ops = parse_ops(yaml).unwrap();
4310        assert_eq!(ops[0].tags["name"], "myop");
4311        assert_eq!(ops[0].tags["op"], "myop");
4312        assert_eq!(ops[0].tags["block"], "block0");
4313    }
4314
4315    #[test]
4316    fn condition_clause_passthrough_for_identifier() {
4317        // Bare identifier — legacy "name a binding" form.
4318        assert_eq!(normalize_condition_clause("my_flag"), "my_flag");
4319        assert_eq!(normalize_condition_clause(" my_flag "), "my_flag");
4320    }
4321
4322    #[test]
4323    fn condition_clause_passthrough_for_braced_forms() {
4324        assert_eq!(normalize_condition_clause("{my_flag}"), "{my_flag}");
4325        assert_eq!(normalize_condition_clause("{{x == 1}}"), "{{x == 1}}");
4326        assert_eq!(normalize_condition_clause("{:=x == 1:=}"), "{:=x == 1:=}");
4327    }
4328
4329    #[test]
4330    fn condition_clause_wraps_bare_expressions() {
4331        assert_eq!(
4332            normalize_condition_clause("cql_dialect == 'cass'"),
4333            "{{cql_dialect == 'cass'}}",
4334        );
4335        assert_eq!(
4336            normalize_condition_clause("a > 0 && b < 10"),
4337            "{{a > 0 && b < 10}}",
4338        );
4339        assert_eq!(normalize_condition_clause("foo(bar)"), "{{foo(bar)}}",);
4340    }
4341
4342    #[test]
4343    fn condition_clause_empty_passthrough() {
4344        assert_eq!(normalize_condition_clause(""), "");
4345        assert_eq!(normalize_condition_clause("   "), "");
4346    }
4347
4348    #[test]
4349    fn parse_op_with_fields() {
4350        let yaml = r#"
4351ops:
4352  op1:
4353    field1: value1
4354    field2: value2
4355"#;
4356        let ops = parse_ops(yaml).unwrap();
4357        assert_eq!(ops[0].op["field1"], "value1");
4358        assert_eq!(ops[0].op["field2"], "value2");
4359    }
4360
4361    #[test]
4362    fn parse_explicit_op_field() {
4363        let yaml = r#"
4364ops:
4365  op1:
4366    op:
4367      stmt: "SELECT * FROM t;"
4368      type: query
4369"#;
4370        let ops = parse_ops(yaml).unwrap();
4371        assert_eq!(ops[0].op["stmt"], "SELECT * FROM t;");
4372        assert_eq!(ops[0].op["type"], "query");
4373    }
4374
4375    #[test]
4376    fn parse_scenarios() {
4377        let yaml = r#"
4378scenarios:
4379  default:
4380    schema: run adapter=cql tags==block:schema threads==1
4381    main: run adapter=cql tags==block:main cycles=1M
4382ops:
4383  op1: "test"
4384"#;
4385        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4386        let default = &workload.scenarios["default"];
4387        assert_eq!(default.len(), 2);
4388        // Legacy command-string format: names are preserved as Phase nodes
4389        assert!(matches!(&default[0], ScenarioNode::Phase(n) if n == "schema"));
4390        assert!(matches!(&default[1], ScenarioNode::Phase(n) if n == "main"));
4391    }
4392
4393    #[test]
4394    fn parse_template_expansion() {
4395        let yaml = r#"
4396ops:
4397  op1: "SELECT * FROM t LIMIT TEMPLATE(limit, 100);"
4398"#;
4399        let ops = parse_ops(yaml).unwrap();
4400        assert_eq!(ops[0].op["stmt"], "SELECT * FROM t LIMIT 100;");
4401    }
4402
4403    #[test]
4404    fn parse_description() {
4405        let yaml = r#"
4406description: |
4407  This is a test workload.
4408ops:
4409  op1: "test"
4410"#;
4411        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4412        assert!(workload.description.unwrap().contains("test workload"));
4413    }
4414
4415    // ── Scenario malformed-node rejection (Never Ignore
4416    // Silently). The parser used to silently drop an
4417    // unrecognised scenario-node key like `iterate:` →
4418    // `{phases: [...]}`, leaving the scenario empty and
4419    // surfacing as a confusing downstream "phase not found"
4420    // error. These tests pin the loud-rejection behavior so a
4421    // refactor can't regress the silent-drop. ──
4422
4423    #[test]
4424    fn scenario_node_with_unknown_map_key_collects_parse_error() {
4425        let yaml = r#"
4426scenarios:
4427  bogus:
4428    - iterate:
4429        phases:
4430          - phase_x
4431phases:
4432  phase_x:
4433    ops:
4434      noop: "x"
4435"#;
4436        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4437        assert!(
4438            !workload.scenario_parse_errors.is_empty(),
4439            "malformed `iterate:` node MUST surface a scenario_parse_error \
4440             — silent drop is the safety bug being prevented"
4441        );
4442        let msg = workload.scenario_parse_errors[0].as_str();
4443        assert!(
4444            msg.contains("bogus"),
4445            "error must name the offending scenario: {msg}"
4446        );
4447        assert!(
4448            msg.contains("iterate"),
4449            "error must name the bad key: {msg}"
4450        );
4451        // Bogus scenario must NOT have absorbed phase_x as a Phase
4452        // node via the legacy catch-all.
4453        assert_eq!(
4454            workload.scenarios.get("bogus").map(|v| v.len()),
4455            Some(0),
4456            "malformed node must NOT silently produce ScenarioNode::Phase"
4457        );
4458    }
4459
4460    #[test]
4461    fn scenario_node_with_legacy_command_string_form_still_works() {
4462        // Pre-existing nosqlbench-style scenario shape: each
4463        // map key is a step name, value is a `run ...` CLI
4464        // string. The malformed-rejection refactor MUST NOT
4465        // break this — the discriminator is "map value is
4466        // a string" → legacy, "map value is a map/array" →
4467        // malformed.
4468        let yaml = r#"
4469scenarios:
4470  default:
4471    schema: run tags==block:schema
4472    main: run tags==block:main
4473ops:
4474  op1: "test"
4475"#;
4476        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4477        assert!(
4478            workload.scenario_parse_errors.is_empty(),
4479            "legacy command-string form must NOT be flagged as malformed: {:?}",
4480            workload.scenario_parse_errors
4481        );
4482        let default = &workload.scenarios["default"];
4483        assert_eq!(default.len(), 2);
4484        assert!(matches!(&default[0], ScenarioNode::Phase(n) if n == "schema"));
4485        assert!(matches!(&default[1], ScenarioNode::Phase(n) if n == "main"));
4486    }
4487
4488    #[test]
4489    fn scenario_node_malformed_error_lists_recognised_keys() {
4490        // The error message must point the operator at the
4491        // recognised key vocabulary so they can self-correct
4492        // without grepping the source.
4493        let yaml = r#"
4494scenarios:
4495  s1:
4496    - typoed_for_each:
4497        phases:
4498          - phase_x
4499phases:
4500  phase_x:
4501    ops:
4502      noop: "x"
4503"#;
4504        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4505        assert_eq!(workload.scenario_parse_errors.len(), 1);
4506        let msg = &workload.scenario_parse_errors[0];
4507        // Must mention at least the load-bearing alternatives.
4508        for expected in ["for_each", "scenarios", "do_while", "bindings"] {
4509            assert!(
4510                msg.contains(expected),
4511                "error message must mention `{expected}` as a valid \
4512                 alternative; got: {msg}"
4513            );
4514        }
4515    }
4516
4517    #[test]
4518    fn parse_polydat_source_bindings() {
4519        // SRD-13f Push D: workload-level `bindings:` live on
4520        // `Workload.bindings` and reach ops via the Polydat Kernel
4521        // chain at runtime — they are NOT folded into per-op
4522        // bindings at parse time.
4523        let yaml = r#"
4524bindings: |
4525  // Explicit wiring — every intermediate is named
4526  input cycle: u64
4527  h := hash(cycle)
4528  user_id := mod(h, 1000000)
4529  code_hash := hash(user_id)
4530  code := combinations(code_hash, '0-9A-Z')
4531
4532  // Equivalent concise form (nested composition):
4533  // user_id := mod(hash(cycle), 1000000)
4534  // code := combinations(hash(user_id), '0-9A-Z')
4535ops:
4536  insert: "INSERT INTO users (id, code) VALUES ({user_id}, '{code}');"
4537"#;
4538        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4539        match &workload.bindings {
4540            BindingsDef::PolydatSource(src) => {
4541                assert!(src.contains("input cycle: u64"));
4542                assert!(src.contains("user_id := mod(h, 1000000)"));
4543            }
4544            BindingsDef::Map(_) => panic!("expected PolydatSource at workload level, got Map"),
4545        }
4546        assert_eq!(workload.ops.len(), 1);
4547        // Op carries no workload bindings — they reach it via
4548        // the Polydat Kernel chain, not via parse-time merge.
4549        assert!(workload.ops[0].bindings.is_empty());
4550    }
4551
4552    #[test]
4553    fn parse_map_bindings_still_works() {
4554        // SRD-13f Push D: Map-form workload bindings live on
4555        // `Workload.bindings`, not on per-op bindings.
4556        let yaml = r#"
4557bindings:
4558  id: "Hash(); Mod(100)"
4559ops:
4560  op1: "SELECT * FROM t WHERE id={id};"
4561"#;
4562        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4563        assert_eq!(workload.bindings.as_map()["id"], "Hash(); Mod(100)");
4564        // The op itself carries no merged-in workload bindings.
4565        assert!(workload.ops[0].bindings.is_empty());
4566    }
4567
4568    #[test]
4569    fn parse_phased_workload() {
4570        let yaml = r#"
4571scenarios:
4572  default:
4573    - schema
4574    - main
4575
4576phases:
4577  schema:
4578    cycles: 1
4579    concurrency: 1
4580    ops:
4581      create_table:
4582        stmt: "CREATE TABLE t (id int PRIMARY KEY);"
4583  main:
4584    cycles: 1000
4585    concurrency: 10
4586    rate: 500.0
4587    ops:
4588      read:
4589        stmt: "SELECT * FROM t WHERE id={id};"
4590      write:
4591        stmt: "INSERT INTO t (id) VALUES ({id});"
4592"#;
4593        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4594
4595        // Phases parsed
4596        assert_eq!(workload.phases.len(), 2);
4597        assert!(workload.phases.contains_key("schema"));
4598        assert!(workload.phases.contains_key("main"));
4599
4600        // Phase order preserved
4601        assert_eq!(workload.phase_order, vec!["schema", "main"]);
4602
4603        // Schema phase config
4604        let schema = &workload.phases["schema"];
4605        assert_eq!(schema.cycles.as_deref(), Some("1"));
4606        assert_eq!(schema.concurrency.as_deref(), Some("1"));
4607        assert_eq!(schema.rate, None);
4608        assert_eq!(schema.ops.len(), 1);
4609        assert_eq!(schema.ops[0].name, "create_table");
4610
4611        // Main phase config
4612        let main = &workload.phases["main"];
4613        assert_eq!(main.cycles.as_deref(), Some("1000"));
4614        assert_eq!(main.concurrency.as_deref(), Some("10"));
4615        assert_eq!(main.rate.as_deref(), Some("500.0"));
4616        assert_eq!(main.ops.len(), 2);
4617
4618        // Scenario parsed as phase name list
4619        let default = &workload.scenarios["default"];
4620        assert_eq!(default.len(), 2);
4621        assert!(matches!(&default[0], ScenarioNode::Phase(n) if n == "schema"));
4622        assert!(matches!(&default[1], ScenarioNode::Phase(n) if n == "main"));
4623    }
4624
4625    #[test]
4626    fn parse_phased_workload_with_tags() {
4627        let yaml = r#"
4628blocks:
4629  schema:
4630    ops:
4631      create: "CREATE TABLE t (id int PRIMARY KEY);"
4632  main:
4633    ops:
4634      read: "SELECT * FROM t;"
4635
4636phases:
4637  setup:
4638    tags: "block:schema"
4639    cycles: 1
4640  run:
4641    tags: "block:main"
4642    cycles: 1000
4643"#;
4644        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4645        assert_eq!(workload.phases.len(), 2);
4646
4647        // SRD-108 Part A: the selector resolves at parse time —
4648        // the phase carries the selected block ops as if inline.
4649        let setup = &workload.phases["setup"];
4650        assert_eq!(setup.tags.as_deref(), Some("block:schema"));
4651        assert_eq!(setup.ops.len(), 1);
4652        assert_eq!(setup.ops[0].name, "create");
4653        assert_eq!(
4654            setup.ops[0].tags.get("phase").map(String::as_str),
4655            Some("setup")
4656        );
4657
4658        let run = &workload.phases["run"];
4659        assert_eq!(run.tags.as_deref(), Some("block:main"));
4660        assert_eq!(run.ops.len(), 1);
4661        assert_eq!(run.ops[0].name, "read");
4662    }
4663
4664    /// SRD-108 Part A — a selector matching nothing is a load
4665    /// error naming the phase, never a dispatch-time panic.
4666    #[test]
4667    fn phase_tag_selector_matching_nothing_is_a_load_error() {
4668        let yaml = r#"
4669blocks:
4670  schema:
4671    ops:
4672      create: "CREATE TABLE t (id int PRIMARY KEY);"
4673phases:
4674  setup:
4675    tags: "block:nonexistent"
4676    cycles: 1
4677"#;
4678        let err = parse_workload(yaml, &HashMap::new()).unwrap_err();
4679        assert!(
4680            err.contains("setup") && err.contains("matched no ops"),
4681            "error must name the phase and the failure: {err}"
4682        );
4683    }
4684
4685    /// SRD-108 Part A — inline ops and a selector together are
4686    /// rejected: one source of ops per phase.
4687    #[test]
4688    fn phase_with_inline_ops_and_selector_is_rejected() {
4689        let yaml = r#"
4690blocks:
4691  schema:
4692    ops:
4693      create: "CREATE TABLE t (id int PRIMARY KEY);"
4694phases:
4695  setup:
4696    tags: "block:schema"
4697    cycles: 1
4698    ops:
4699      also: "SELECT 1;"
4700"#;
4701        let err = parse_workload(yaml, &HashMap::new()).unwrap_err();
4702        assert!(
4703            err.contains("both inline ops and a"),
4704            "error must explain the conflict: {err}"
4705        );
4706    }
4707
4708    #[test]
4709    fn parse_phased_workload_polydat_cycles() {
4710        let yaml = r#"
4711phases:
4712  rampup:
4713    cycles: "{train_count}"
4714    concurrency: 100
4715    ops:
4716      insert:
4717        stmt: "INSERT INTO t (id) VALUES ({id});"
4718"#;
4719        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4720        let rampup = &workload.phases["rampup"];
4721        assert_eq!(rampup.cycles.as_deref(), Some("{train_count}"));
4722    }
4723
4724    // ── SRD-40b §1 + §2: `metrics:` discriminant on op template ──
4725
4726    #[test]
4727    fn parse_metrics_full_mapping_form() {
4728        let yaml = r##"
4729phases:
4730  predict:
4731    bindings: |
4732      example_factor := 1.0 + 2.5
4733    ops:
4734      synth:
4735        stmt: "noop"
4736        metrics:
4737          example_factor:
4738            value: example_factor
4739            kind: gauge
4740            unit: ratio
4741            format: "#.##"
4742"##;
4743        let wl = parse_workload(yaml, &HashMap::new()).unwrap();
4744        let op = &wl.phases["predict"].ops[0];
4745        assert_eq!(op.name, "synth");
4746        let m = &op.metrics["example_factor"];
4747        assert_eq!(m.value, "example_factor");
4748        assert_eq!(m.kind, Some(crate::model::MetricKind::Gauge));
4749        assert_eq!(m.unit.as_deref(), Some("ratio"));
4750        assert_eq!(m.format.as_deref(), Some("#.##"));
4751    }
4752
4753    #[test]
4754    fn parse_metrics_bare_string_sugar() {
4755        let yaml = r#"
4756phases:
4757  p:
4758    bindings: |
4759      overscan := 1.0
4760    ops:
4761      o:
4762        stmt: "noop"
4763        metrics: overscan
4764"#;
4765        let wl = parse_workload(yaml, &HashMap::new()).unwrap();
4766        let op = &wl.phases["p"].ops[0];
4767        let m = &op.metrics["overscan"];
4768        // Bare-string form: family + value both = "overscan"
4769        // (defaults), kind unset (defaults to gauge at runtime).
4770        assert_eq!(m.value, "overscan");
4771        assert_eq!(m.family, None);
4772        assert_eq!(m.kind, None);
4773    }
4774
4775    #[test]
4776    fn parse_metrics_list_with_wire_expression() {
4777        let yaml = r#"
4778phases:
4779  p:
4780    ops:
4781      o:
4782        stmt: "noop"
4783        metrics:
4784          - latency_pred := 0.5 + 1.5 * pow(limit, -0.4)
4785          - already_bound
4786"#;
4787        let wl = parse_workload(yaml, &HashMap::new()).unwrap();
4788        let op = &wl.phases["p"].ops[0];
4789        // Both metric entries registered.
4790        assert!(op.metrics.contains_key("latency_pred"));
4791        assert!(op.metrics.contains_key("already_bound"));
4792        // Wire expression auto-injected into op bindings.
4793        match &op.bindings {
4794            BindingsDef::PolydatSource(src) => {
4795                assert!(
4796                    src.contains("latency_pred := 0.5 + 1.5 * pow(limit, -0.4)"),
4797                    "wire not injected; bindings: {src:?}"
4798                );
4799            }
4800            other => panic!("expected PolydatSource bindings, got {other:?}"),
4801        }
4802    }
4803
4804    #[test]
4805    fn parse_metrics_mapping_form_with_wire_expression() {
4806        let yaml = r#"
4807phases:
4808  p:
4809    bindings: |
4810      base := 10
4811    ops:
4812      o:
4813        stmt: "noop"
4814        metrics:
4815          scaled:
4816            value: base * 2
4817            kind: gauge
4818"#;
4819        let wl = parse_workload(yaml, &HashMap::new()).unwrap();
4820        let op = &wl.phases["p"].ops[0];
4821        let m = &op.metrics["scaled"];
4822        // After auto-inject the spec's `value:` is the bare key.
4823        assert_eq!(m.value, "scaled");
4824        // The non-bare expression landed in op-template bindings.
4825        match &op.bindings {
4826            BindingsDef::PolydatSource(src) => {
4827                assert!(
4828                    src.contains("scaled := base * 2"),
4829                    "expression not injected; bindings: {src:?}"
4830                );
4831            }
4832            other => panic!("expected PolydatSource bindings, got {other:?}"),
4833        }
4834    }
4835
4836    #[test]
4837    fn parse_metrics_mapping_form_invalid_key_for_non_bare_value() {
4838        // Non-bare value + key that can't be a binding name → reject.
4839        let yaml = r#"
4840phases:
4841  p:
4842    ops:
4843      o:
4844        stmt: "noop"
4845        metrics:
4846          "1bad":
4847            value: foo + 1
4848            kind: gauge
4849"#;
4850        let err = parse_workload(yaml, &HashMap::new()).unwrap_err();
4851        assert!(
4852            err.contains("must itself be a valid identifier"),
4853            "expected identifier diagnostic, got: {err}"
4854        );
4855    }
4856
4857    #[test]
4858    fn parse_metrics_format_validation_runs_at_load() {
4859        let yaml = r##"
4860phases:
4861  p:
4862    ops:
4863      o:
4864        stmt: "noop"
4865        metrics:
4866          x:
4867            value: x
4868            format: "%3.2f"
4869"##;
4870        let err = parse_workload(yaml, &HashMap::new()).unwrap_err();
4871        assert!(
4872            err.contains("printf-style"),
4873            "format error not surfaced at parse time: {err}"
4874        );
4875    }
4876
4877    #[test]
4878    fn parse_metrics_wire_expression_collision_errors() {
4879        let yaml = r#"
4880phases:
4881  p:
4882    ops:
4883      o:
4884        stmt: "noop"
4885        bindings: |
4886          foo := 1.0
4887        metrics:
4888          - foo := 2.0
4889"#;
4890        let err = parse_workload(yaml, &HashMap::new()).unwrap_err();
4891        assert!(err.contains("collides"), "collision not detected: {err}");
4892    }
4893
4894    #[test]
4895    fn parse_phase_bindings_round_trip() {
4896        // SRD-13d Phase 1: phase-level `bindings:` block must
4897        // land on WorkloadPhase.bindings (not just merged into
4898        // ops) so HasGkMatter can classify it.
4899        let yaml = r#"
4900phases:
4901  p:
4902    bindings: |
4903      phase_factor := 7
4904    ops:
4905      o:
4906        stmt: "noop"
4907"#;
4908        let wl = parse_workload(yaml, &HashMap::new()).unwrap();
4909        match &wl.phases["p"].bindings {
4910            BindingsDef::PolydatSource(s) => assert!(s.contains("phase_factor := 7")),
4911            other => panic!("expected PolydatSource, got {other:?}"),
4912        }
4913    }
4914
4915    #[test]
4916    fn parse_phased_workload_default_scenario_from_order() {
4917        // No scenarios section — phases should run in definition order
4918        let yaml = r#"
4919phases:
4920  alpha:
4921    cycles: 1
4922    ops:
4923      op1:
4924        stmt: "a"
4925  beta:
4926    cycles: 2
4927    ops:
4928      op2:
4929        stmt: "b"
4930  gamma:
4931    cycles: 3
4932    ops:
4933      op3:
4934        stmt: "c"
4935"#;
4936        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4937        assert_eq!(workload.phase_order, vec!["alpha", "beta", "gamma"]);
4938        assert!(workload.scenarios.is_empty());
4939    }
4940
4941    #[test]
4942    fn parse_backward_compat_no_phases() {
4943        // Workload without phases should work exactly as before
4944        let yaml = r#"
4945ops:
4946  op1: "SELECT 1;"
4947  op2: "SELECT 2;"
4948"#;
4949        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4950        assert!(workload.phases.is_empty());
4951        assert!(workload.phase_order.is_empty());
4952        assert_eq!(workload.ops.len(), 2);
4953    }
4954
4955    #[test]
4956    fn block_level_params_override_workload_default() {
4957        // SRD 21 §"Parameter Resolution": closest-wins. The DDL block declares
4958        // `consistency=1`, overriding the workload-level default `100` for ops
4959        // in that block. Uses an op-scope param (`consistency`); activity-scope
4960        // keys (`concurrency`/`rate`/`cycles`/`errors`) are deliberately NOT
4961        // merged onto ops (SRD-32a — see `ACTIVITY_PARAM_KEYS`), so this tests
4962        // op-param precedence with a key that actually reaches ops.
4963        let yaml = r#"
4964params:
4965  consistency: "100"
4966blocks:
4967  ddl:
4968    params:
4969      consistency: "1"
4970    ops:
4971      schema_create: "CREATE TABLE foo (id int PRIMARY KEY);"
4972  bulk:
4973    ops:
4974      insert: "INSERT INTO foo (id) VALUES (?);"
4975"#;
4976        let ops = parse_ops(yaml).unwrap();
4977        let ddl = ops.iter().find(|o| o.name == "schema_create").unwrap();
4978        let bulk = ops.iter().find(|o| o.name == "insert").unwrap();
4979        assert_eq!(
4980            ddl.params.get("consistency").and_then(|v| v.as_str()),
4981            Some("1"),
4982            "block-level override should win for ddl op",
4983        );
4984        assert_eq!(
4985            bulk.params.get("consistency").and_then(|v| v.as_str()),
4986            Some("100"),
4987            "non-overriding block inherits workload-level default",
4988        );
4989    }
4990
4991    #[test]
4992    fn cli_overrides_block_level_params() {
4993        // CLI is the outermost layer per SRD 21 — it wins even over block-level
4994        // explicit overrides. Uses an op-scope param (`consistency`); see
4995        // `block_level_params_override_workload_default` for why not an
4996        // activity-scope key like `concurrency`.
4997        let yaml = r#"
4998params:
4999  consistency: "100"
5000blocks:
5001  ddl:
5002    params:
5003      consistency: "1"
5004    ops:
5005      schema_create: "CREATE TABLE foo (id int PRIMARY KEY);"
5006"#;
5007        let mut cli = HashMap::new();
5008        cli.insert("consistency".to_string(), "200".to_string());
5009        let workload = parse_workload(yaml, &cli).unwrap();
5010        let ddl = workload
5011            .ops
5012            .iter()
5013            .find(|o| o.name == "schema_create")
5014            .unwrap();
5015        assert_eq!(
5016            ddl.params.get("consistency").and_then(|v| v.as_str()),
5017            Some("200"),
5018            "CLI override should beat block-level",
5019        );
5020        // Workload-level params likewise reflect CLI.
5021        assert_eq!(
5022            workload.params.get("consistency").map(|s| s.as_str()),
5023            Some("200"),
5024        );
5025    }
5026
5027    #[test]
5028    fn parse_polydat_source_overrides_parent_map() {
5029        // Block-level Polydat source completely replaces doc-level map bindings
5030        let yaml = r#"
5031bindings:
5032  id: "Hash()"
5033blocks:
5034  main:
5035    bindings: |
5036      input cycle: u64
5037      h := hash(cycle)
5038      id := mod(h, 1000)
5039      // Concise equivalent:
5040      // id := mod(hash(cycle), 1000)
5041    ops:
5042      op1: "SELECT * FROM t WHERE id={id};"
5043"#;
5044        let ops = parse_ops(yaml).unwrap();
5045        match &ops[0].bindings {
5046            BindingsDef::PolydatSource(src) => {
5047                assert!(src.contains("input cycle: u64"));
5048                assert!(src.contains("id := mod(h, 1000)"));
5049            }
5050            BindingsDef::Map(_) => panic!("expected PolydatSource, got Map"),
5051        }
5052    }
5053
5054    #[test]
5055    fn parse_scenarios_plural_list_form() {
5056        // The plural `scenarios: [a, b, c]` form composes
5057        // several named scenarios at one node. Each list
5058        // entry expands to an `IncludedScenario` and resolves
5059        // post-parse. Equivalent to `[- scenario: a, -
5060        // scenario: b, ...]` but reads more naturally for the
5061        // "just compose these" case.
5062        let yaml = r#"
5063scenarios:
5064  rampup:
5065    - prep
5066  query:
5067    - run
5068
5069  composed:
5070    - scenarios:
5071        - rampup
5072        - query
5073
5074phases:
5075  prep:
5076    ops:
5077      create:
5078        raw: "select 1"
5079  run:
5080    ops:
5081      sel:
5082        raw: "select {cycle}"
5083"#;
5084        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
5085        let composed = workload
5086            .scenarios
5087            .get("composed")
5088            .expect("composed scenario must parse");
5089        // After resolution the IncludedScenario wrappers carry
5090        // their resolved children. The scenario tree shape is:
5091        //   composed
5092        //     └── IncludedScenario("rampup") [Phase("prep")]
5093        //     └── IncludedScenario("query")  [Phase("run")]
5094        // Walk one level deep into each include to assert.
5095        assert_eq!(
5096            composed.len(),
5097            2,
5098            "scenarios: [a, b] should produce two top-level nodes"
5099        );
5100        let names: Vec<&str> = composed
5101            .iter()
5102            .filter_map(|n| match n {
5103                ScenarioNode::IncludedScenario { name, .. } => Some(name.as_str()),
5104                _ => None,
5105            })
5106            .collect();
5107        assert_eq!(names, vec!["rampup", "query"]);
5108        // First include resolves to its sole `Phase("prep")`.
5109        let first_children = match &composed[0] {
5110            ScenarioNode::IncludedScenario { children, .. } => children,
5111            _ => panic!("expected IncludedScenario at index 0"),
5112        };
5113        let first_phase = first_children.iter().find_map(|n| match n {
5114            ScenarioNode::Phase(p) => Some(p.as_str()),
5115            _ => None,
5116        });
5117        assert_eq!(first_phase, Some("prep"));
5118    }
5119
5120    #[test]
5121    fn parse_scenarios_plural_mixes_with_other_node_shapes() {
5122        // List entries can be a mix of bare strings and other
5123        // scenario-node shapes (objects with `scenario:`,
5124        // `for_each:`, etc.). This matches the heterogeneous
5125        // shape `parse_scenario_nodes` already accepts at the
5126        // top level, so the plural form composes naturally
5127        // with everything else.
5128        let yaml = r#"
5129scenarios:
5130  rampup:
5131    - prep
5132  composed:
5133    - scenarios:
5134        - rampup
5135        - { scenario: rampup }
5136
5137phases:
5138  prep:
5139    ops:
5140      create:
5141        raw: "select 1"
5142"#;
5143        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
5144        let composed = workload.scenarios.get("composed").unwrap();
5145        // Both list entries should resolve to an IncludedScenario
5146        // wrapping the same `prep` phase.
5147        assert_eq!(composed.len(), 2);
5148        for node in composed {
5149            match node {
5150                ScenarioNode::IncludedScenario { name, children } => {
5151                    assert_eq!(name, "rampup");
5152                    assert!(
5153                        children
5154                            .iter()
5155                            .any(|c| matches!(c, ScenarioNode::Phase(p) if p == "prep"))
5156                    );
5157                }
5158                other => panic!("expected IncludedScenario, got {other:?}"),
5159            }
5160        }
5161    }
5162
5163    // -----------------------------------------------------------------
5164    // Checkpoint declaration parsing — SRD-44 §"Forms"
5165    // -----------------------------------------------------------------
5166
5167    fn parse_checkpoint_field(yaml: &str) -> Option<crate::model::Checkpoint> {
5168        let yaml = format!(
5169            "phases:\n  p:\n{}\n    ops:\n      - select 1;\n",
5170            yaml.lines()
5171                .map(|l| format!("    {l}"))
5172                .collect::<Vec<_>>()
5173                .join("\n")
5174        );
5175        let v: serde_yaml::Value = serde_yaml::from_str(&yaml).expect("yaml parse");
5176        let json: serde_json::Value = serde_json::to_value(&v).expect("json convert");
5177        let phases_obj = json
5178            .get("phases")
5179            .and_then(|p| p.as_object())
5180            .expect("phases");
5181        let phase = phases_obj
5182            .get("p")
5183            .and_then(|p| p.as_object())
5184            .expect("phase p");
5185        phase.get("checkpoint").map(|v| {
5186            serde_json::from_value::<crate::model::Checkpoint>(v.clone()).expect("checkpoint parse")
5187        })
5188    }
5189
5190    #[test]
5191    fn checkpoint_short_form_idempotent() {
5192        let cp = parse_checkpoint_field("checkpoint: idempotent").expect("present");
5193        assert!(cp.idempotent);
5194        assert!(cp.hashed);
5195        assert!(cp.verify.is_none());
5196    }
5197
5198    #[test]
5199    fn checkpoint_short_form_none_disables_skip() {
5200        let cp = parse_checkpoint_field("checkpoint: none").expect("present");
5201        assert!(!cp.idempotent);
5202        // hashed default-true is preserved even when disabled —
5203        // the disabled state is about skip eligibility, not
5204        // about the hash field.
5205        assert!(cp.hashed);
5206        assert!(cp.verify.is_none());
5207    }
5208
5209    #[test]
5210    fn checkpoint_bool_and_empty_forms_name_the_short_form() {
5211        // One spelling per meaning: `idempotent` / `none` (or a
5212        // mapping). A bool, its string spelling, or a bare null is
5213        // an error naming the short form to write.
5214        for (form, want) in [
5215            ("true", "checkpoint: idempotent"),
5216            ("false", "checkpoint: none"),
5217            ("\"true\"", "checkpoint: idempotent"),
5218            ("\"false\"", "checkpoint: none"),
5219            ("", "checkpoint: idempotent"),
5220        ] {
5221            let v: serde_json::Value = if form.is_empty() {
5222                serde_json::Value::Null
5223            } else {
5224                serde_json::to_value(serde_yaml::from_str::<serde_yaml::Value>(form).unwrap())
5225                    .unwrap()
5226            };
5227            let err = serde_json::from_value::<crate::model::Checkpoint>(v)
5228                .expect_err(form)
5229                .to_string();
5230            assert!(err.contains(want), "{form:?}: {err}");
5231        }
5232    }
5233
5234    #[test]
5235    fn checkpoint_short_forms_load_through_the_full_parser() {
5236        // The construction table and the deserializer must agree on
5237        // the short-form vocabulary (they once disagreed:
5238        // `disabled` vs `none`, so `checkpoint: none` failed to load).
5239        for (form, idempotent) in [("idempotent", true), ("none", false)] {
5240            let yaml = format!(
5241                "phases:\n  p:\n    cycles: 1\n    checkpoint: {form}\n    ops:\n      - select 1;\n"
5242            );
5243            let wl = parse_workload(&yaml, &HashMap::new())
5244                .unwrap_or_else(|e| panic!("checkpoint: {form} must load: {e}"));
5245            let cp = wl.phases["p"].checkpoint.as_ref().expect("declared");
5246            assert_eq!(cp.idempotent, idempotent, "{form}");
5247        }
5248    }
5249
5250    #[test]
5251    fn checkpoint_full_form_all_explicit() {
5252        let cp = parse_checkpoint_field("checkpoint:\n  idempotent: true\n  hashed: false")
5253            .expect("present");
5254        assert!(cp.idempotent);
5255        assert!(!cp.hashed);
5256        assert!(cp.verify.is_none());
5257    }
5258
5259    #[test]
5260    fn checkpoint_full_form_with_verify() {
5261        let cp = parse_checkpoint_field(
5262            "checkpoint:\n  idempotent: true\n  verify:\n    raw: 'SELECT 1'\n    poll: assert_one",
5263        )
5264        .expect("present");
5265        assert!(cp.idempotent);
5266        assert!(cp.hashed); // default
5267        let v = cp.verify.expect("verify body");
5268        assert_eq!(v.get("raw").and_then(|x| x.as_str()), Some("SELECT 1"));
5269        assert_eq!(v.get("poll").and_then(|x| x.as_str()), Some("assert_one"));
5270    }
5271
5272    #[test]
5273    fn checkpoint_full_form_idempotent_false_equivalent_to_none() {
5274        let cp = parse_checkpoint_field("checkpoint:\n  idempotent: false\n  hashed: true")
5275            .expect("present");
5276        assert!(!cp.idempotent);
5277        assert!(cp.hashed);
5278    }
5279
5280    #[test]
5281    fn checkpoint_unknown_short_form_errors() {
5282        // Should fail to parse — an unknown short string is a
5283        // workload bug, not silently treated as `none`.
5284        let yaml = "phases:\n  p:\n    checkpoint: maybe\n    ops:\n      - select 1;\n";
5285        let v: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
5286        let json: serde_json::Value = serde_json::to_value(&v).unwrap();
5287        let phases_obj = json.get("phases").and_then(|p| p.as_object()).unwrap();
5288        let phase = phases_obj.get("p").and_then(|p| p.as_object()).unwrap();
5289        let cp_val = phase.get("checkpoint").unwrap().clone();
5290        let err = serde_json::from_value::<crate::model::Checkpoint>(cp_val).unwrap_err();
5291        let msg = err.to_string();
5292        assert!(
5293            msg.contains("unknown short form"),
5294            "expected unknown-short-form error, got: {msg}"
5295        );
5296        assert!(
5297            msg.contains("'maybe'"),
5298            "expected the bad token in error, got: {msg}"
5299        );
5300    }
5301
5302    #[test]
5303    fn checkpoint_unknown_key_errors() {
5304        let yaml = "phases:\n  p:\n    checkpoint:\n      idempotent: true\n      bogus: yes\n    ops:\n      - select 1;\n";
5305        let v: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
5306        let json: serde_json::Value = serde_json::to_value(&v).unwrap();
5307        let cp_val = json.pointer("/phases/p/checkpoint").unwrap().clone();
5308        let err = serde_json::from_value::<crate::model::Checkpoint>(cp_val).unwrap_err();
5309        let msg = err.to_string();
5310        assert!(
5311            msg.contains("unknown key 'bogus'"),
5312            "expected unknown-key error, got: {msg}"
5313        );
5314    }
5315
5316    #[test]
5317    fn checkpoint_field_absent_yields_none() {
5318        let cp = parse_checkpoint_field("# no checkpoint declared\n");
5319        assert!(
5320            cp.is_none(),
5321            "absent declaration should yield None, not Default"
5322        );
5323    }
5324
5325    /// SRD-44 validation: a phase declared `checkpoint:
5326    /// idempotent` inside a do_while loop must be rejected at
5327    /// workload-load time. The do-loop iterates the same phase
5328    /// identity multiple times, contradicting the per-execution
5329    /// unit checkpointing assumes.
5330    #[test]
5331    fn rejects_idempotent_phase_inside_do_while() {
5332        let yaml = r#"
5333scenarios:
5334  default:
5335    - do_while: "true"
5336      phases:
5337        - probe
5338phases:
5339  probe:
5340    checkpoint: idempotent
5341    cycles: 1
5342    ops:
5343      step:
5344        stmt: "probe"
5345"#;
5346        let err = super::parse_workload(yaml, &HashMap::new())
5347            .expect_err("expected validation rejection");
5348        assert!(
5349            err.contains("checkpoint: idempotent"),
5350            "error should explain the rejection: {err}"
5351        );
5352        assert!(
5353            err.contains("'probe'"),
5354            "error should name the offending phase: {err}"
5355        );
5356        assert!(
5357            err.contains("do_while") || err.contains("do_until"),
5358            "error should mention the do-loop ancestor: {err}"
5359        );
5360    }
5361
5362    /// `do_until` triggers the same rejection.
5363    #[test]
5364    fn rejects_idempotent_phase_inside_do_until() {
5365        let yaml = r#"
5366scenarios:
5367  default:
5368    - do_until: "false"
5369      phases:
5370        - probe
5371phases:
5372  probe:
5373    checkpoint: idempotent
5374    cycles: 1
5375    ops:
5376      step:
5377        stmt: "probe"
5378"#;
5379        let err = super::parse_workload(yaml, &HashMap::new())
5380            .expect_err("expected validation rejection");
5381        assert!(err.contains("'probe'"));
5382    }
5383
5384    /// A do_while'd phase WITHOUT checkpoint declaration is
5385    /// fine — only the combination with `checkpoint:
5386    /// idempotent` is rejected.
5387    #[test]
5388    fn allows_do_while_phase_without_checkpoint_declaration() {
5389        let yaml = r#"
5390scenarios:
5391  default:
5392    - do_while: "true"
5393      phases:
5394        - probe
5395phases:
5396  probe:
5397    cycles: 1
5398    ops:
5399      step:
5400        stmt: "probe"
5401"#;
5402        super::parse_workload(yaml, &HashMap::new()).expect("plain do_while phase should parse");
5403    }
5404
5405    /// Idempotent phases NOT inside a do-loop are fine.
5406    #[test]
5407    fn allows_idempotent_phase_outside_do_loop() {
5408        let yaml = r#"
5409scenarios:
5410  default:
5411    - probe
5412phases:
5413  probe:
5414    checkpoint: idempotent
5415    cycles: 1
5416    ops:
5417      step:
5418        stmt: "probe"
5419"#;
5420        super::parse_workload(yaml, &HashMap::new())
5421            .expect("idempotent phase outside loop should parse");
5422    }
5423
5424    /// Declarative `capture:` map block on an op produces
5425    /// CapturePoint entries with [`CapturePoint::path`] set.
5426    /// JSON-Pointer paths are not validated against the
5427    /// response shape (it's a runtime read), so the parser's
5428    /// only job is to forbid obviously-malformed inputs
5429    /// (non-string values, paths missing the leading `/`).
5430    #[test]
5431    fn parses_declarative_capture_block_with_json_pointer_paths() {
5432        let yaml = r#"
5433scenarios:
5434  default:
5435    - probe
5436phases:
5437  probe:
5438    cycles: 1
5439    ops:
5440      read_state:
5441        adapter: http
5442        method: POST
5443        uri: "http://h:8778/jolokia/"
5444        body: "[]"
5445        capture:
5446          sstables: "/0/value"
5447          active_count: "/1/value:count"
5448          pending_for_cf: "/2/value"
5449"#;
5450        let wl = super::parse_workload(yaml, &HashMap::new())
5451            .expect("workload with declarative captures should parse");
5452        let phase = wl.phases.get("probe").expect("probe phase");
5453        let op = phase
5454            .ops
5455            .iter()
5456            .find(|o| o.name == "read_state")
5457            .expect("read_state op");
5458        assert_eq!(
5459            op.captures.len(),
5460            3,
5461            "expected 3 declarative captures, got {:?}",
5462            op.captures
5463        );
5464        let by_name = |n: &str| {
5465            op.captures
5466                .iter()
5467                .find(|c| c.as_name == n)
5468                .unwrap_or_else(|| panic!("capture {n} missing"))
5469        };
5470        let sstables = by_name("sstables");
5471        assert_eq!(sstables.path.as_deref(), Some("/0/value"));
5472        assert!(!sstables.count);
5473        let active = by_name("active_count");
5474        assert_eq!(
5475            active.path.as_deref(),
5476            Some("/1/value"),
5477            ":count suffix should be stripped from stored path"
5478        );
5479        assert!(active.count, ":count suffix should set CapturePoint.count");
5480        let pending = by_name("pending_for_cf");
5481        assert_eq!(pending.path.as_deref(), Some("/2/value"));
5482        assert!(!pending.count);
5483    }
5484
5485    /// SRD-75: phase-level `poll:` block parses into
5486    /// `WorkloadPhase.poll`. Distinct from the op-level
5487    /// `poll:` field which lives on a single op and routes
5488    /// through the `PollingDispenser` wrapper.
5489    #[test]
5490    fn parses_phase_level_poll_block() {
5491        let yaml = r#"
5492scenarios:
5493  default:
5494    - ensure
5495phases:
5496  ensure:
5497    cycles: 1
5498    poll:
5499      until: "sstables == 1 && active_for_cf == 0"
5500      interval_ms: 5000
5501      timeout_ms: 14400000
5502      max_error_retries: 3
5503      metric_name: ensure_wait_s
5504    ops:
5505      read_state:
5506        stmt: "noop"
5507"#;
5508        let wl =
5509            super::parse_workload(yaml, &HashMap::new()).expect("phase-poll block should parse");
5510        let phase = wl.phases.get("ensure").expect("ensure phase");
5511        let poll = phase.poll.as_ref().expect("phase.poll Some");
5512        assert_eq!(poll.until, "sstables == 1 && active_for_cf == 0");
5513        assert_eq!(poll.interval_ms.as_deref(), Some("5000"));
5514        assert_eq!(poll.timeout_ms.as_deref(), Some("14400000"));
5515        assert_eq!(poll.max_error_retries.as_deref(), Some("3"));
5516        assert_eq!(poll.metric_name.as_deref(), Some("ensure_wait_s"));
5517    }
5518
5519    #[test]
5520    fn optimize_string_is_sugar_for_objective_block() {
5521        // SRD-86 — `optimize: <string>` is shorthand for
5522        // `optimize: { objective: <string> }` with every other field defaulted.
5523        let yaml = r#"
5524scenarios:
5525  default:
5526    - search
5527phases:
5528  search:
5529    cycles: 1
5530    for_each: "ef in 1.0 .. 5.0"
5531    optimize: |
5532      0 - (ef - 4) * (ef - 4)
5533    ops:
5534      probe:
5535        stmt: "probe ef={ef}"
5536"#;
5537        let wl = super::parse_workload(yaml, &HashMap::new())
5538            .expect("string-form optimize should parse");
5539        let opt = wl
5540            .phases
5541            .get("search")
5542            .and_then(|p| p.optimize.as_ref())
5543            .expect("optimize block present");
5544        // The whole string became the objective; the rest defaulted.
5545        assert_eq!(opt.objective.trim(), "0 - (ef - 4) * (ef - 4)");
5546        assert_eq!(opt.method, "sweep");
5547        assert!(opt.servo.is_empty());
5548
5549        // ...and it is equivalent to the explicit map form.
5550        let map_yaml = yaml.replace(
5551            "    optimize: |\n      0 - (ef - 4) * (ef - 4)\n",
5552            "    optimize: { objective: \"0 - (ef - 4) * (ef - 4)\" }\n",
5553        );
5554        let wl2 = super::parse_workload(&map_yaml, &HashMap::new())
5555            .expect("map-form optimize should parse");
5556        let opt2 = wl2
5557            .phases
5558            .get("search")
5559            .and_then(|p| p.optimize.as_ref())
5560            .unwrap();
5561        assert_eq!(opt.objective.trim(), opt2.objective.trim());
5562        assert_eq!(opt.method, opt2.method);
5563    }
5564
5565    /// SRD-75 §"Workload-load validation": phase-poll +
5566    /// concurrency > 1 is rejected at parse time. The
5567    /// predicate's evaluation depends on a serial sequence
5568    /// of capture writes; concurrent cycle execution has no
5569    /// well-defined semantic here.
5570    #[test]
5571    fn rejects_phase_poll_with_concurrency_gt_one() {
5572        let yaml = r#"
5573scenarios:
5574  default:
5575    - ensure
5576phases:
5577  ensure:
5578    cycles: 1
5579    concurrency: 4
5580    poll:
5581      until: "done == 1"
5582    ops:
5583      op1:
5584        stmt: "noop"
5585"#;
5586        let err = super::parse_workload(yaml, &HashMap::new())
5587            .expect_err("poll: + concurrency > 1 must error");
5588        assert!(
5589            err.contains("poll:") && err.contains("concurrency"),
5590            "expected error to name both poll: and concurrency; got: {err}"
5591        );
5592    }
5593
5594    /// SRD-75 §"Workload-load validation": phase-poll with
5595    /// no ops is rejected — captures are produced by op
5596    /// execution; a poll-phase with no ops has nothing to
5597    /// drive the predicate.
5598    #[test]
5599    fn rejects_phase_poll_with_no_ops() {
5600        let yaml = r#"
5601scenarios:
5602  default:
5603    - ensure
5604phases:
5605  ensure:
5606    cycles: 1
5607    poll:
5608      until: "done == 1"
5609"#;
5610        let err =
5611            super::parse_workload(yaml, &HashMap::new()).expect_err("poll: without ops must error");
5612        assert!(
5613            err.contains("poll:") && err.contains("ops"),
5614            "expected error to name poll: and ops:; got: {err}"
5615        );
5616    }
5617
5618    /// Unknown keys under `poll:` are typos waiting to
5619    /// silently default. Surface them at parse time.
5620    #[test]
5621    fn rejects_unknown_keys_under_phase_poll() {
5622        let yaml = r#"
5623scenarios:
5624  default:
5625    - ensure
5626phases:
5627  ensure:
5628    cycles: 1
5629    poll:
5630      until: "done == 1"
5631      tinerval_ms: 5000
5632    ops:
5633      op1:
5634        stmt: "noop"
5635"#;
5636        let err =
5637            super::parse_workload(yaml, &HashMap::new()).expect_err("typo under poll: must error");
5638        assert!(
5639            err.contains("tinerval_ms"),
5640            "expected error to name the offending key; got: {err}"
5641        );
5642    }
5643
5644    /// SRD-75 §"on_timeout" — accepts the documented
5645    /// closed-vocabulary values and persists them on the
5646    /// parsed phase model. Both `error` and `abort` parse
5647    /// cleanly; case is normalised at parse time.
5648    #[test]
5649    fn parses_phase_poll_on_timeout_accepts_error_and_abort() {
5650        for (input, expected) in [
5651            ("error", "error"),
5652            ("abort", "abort"),
5653            ("ABORT", "abort"),
5654            ("Error", "error"),
5655        ] {
5656            let yaml = format!(
5657                r#"
5658scenarios:
5659  default:
5660    - ensure
5661phases:
5662  ensure:
5663    cycles: 1
5664    poll:
5665      until: "done == 1"
5666      on_timeout: {input}
5667    ops:
5668      op1:
5669        stmt: "noop"
5670"#
5671            );
5672            let wl = super::parse_workload(&yaml, &HashMap::new())
5673                .expect("on_timeout value should parse");
5674            let phase = wl.phases.get("ensure").expect("ensure phase");
5675            let poll = phase.poll.as_ref().expect("phase.poll Some");
5676            assert_eq!(
5677                poll.on_timeout.as_deref(),
5678                Some(expected),
5679                "on_timeout '{input}' should normalise to '{expected}'"
5680            );
5681        }
5682    }
5683
5684    /// SRD-75 §"on_timeout" — anything outside the
5685    /// closed vocabulary is rejected at parse time.
5686    /// Typos like `aborts:` or `fail:` should fail loudly,
5687    /// not silently default to `error` and obscure the
5688    /// workload-author's actual intent.
5689    #[test]
5690    fn rejects_phase_poll_unknown_on_timeout_value() {
5691        let yaml = r#"
5692scenarios:
5693  default:
5694    - ensure
5695phases:
5696  ensure:
5697    cycles: 1
5698    poll:
5699      until: "done == 1"
5700      on_timeout: fail
5701    ops:
5702      op1:
5703        stmt: "noop"
5704"#;
5705        let err = super::parse_workload(yaml, &HashMap::new())
5706            .expect_err("unknown on_timeout value must error");
5707        assert!(
5708            err.contains("on_timeout") && err.contains("'fail'"),
5709            "expected error to name the offending value; got: {err}"
5710        );
5711    }
5712
5713    /// `poll:` requires `until:` — the predicate is the
5714    /// loop's whole purpose.
5715    #[test]
5716    fn rejects_phase_poll_without_until() {
5717        let yaml = r#"
5718scenarios:
5719  default:
5720    - ensure
5721phases:
5722  ensure:
5723    cycles: 1
5724    poll:
5725      interval_ms: 5000
5726    ops:
5727      op1:
5728        stmt: "noop"
5729"#;
5730        let err = super::parse_workload(yaml, &HashMap::new())
5731            .expect_err("poll: without until: must error");
5732        assert!(
5733            err.contains("until"),
5734            "expected error to require until:; got: {err}"
5735        );
5736    }
5737
5738    /// SRD-83 Part 5 — the `effect:`/`action:` verb vocabulary is
5739    /// closed. An unknown verb used to fall silently to the shell
5740    /// default at the trip site; it is a load error now.
5741    #[test]
5742    fn rejects_unknown_stop_condition_effect() {
5743        let yaml = r#"
5744scenarios:
5745  default:
5746    - work
5747phases:
5748  work:
5749    cycles: 10
5750    stop_when:
5751      - when: "cycles_total > 5"
5752        effect: sotp
5753    ops:
5754      op1:
5755        stmt: "noop"
5756"#;
5757        let err = super::parse_workload(yaml, &HashMap::new())
5758            .expect_err("unknown effect verb must be a load error");
5759        assert!(
5760            err.contains("sotp") && err.contains("stop|fail|abort"),
5761            "expected error to name the verb and the vocabulary; got: {err}"
5762        );
5763    }
5764
5765    /// The three declared verbs — and the `action:` alias — all load.
5766    #[test]
5767    fn accepts_declared_stop_condition_effects() {
5768        let yaml = |key: &str, verb: &str| {
5769            format!(
5770                r#"
5771scenarios:
5772  default:
5773    - work
5774phases:
5775  work:
5776    cycles: 10
5777    stop_when:
5778      - when: "cycles_total > 5"
5779        {key}: {verb}
5780    ops:
5781      op1:
5782        stmt: "noop"
5783"#
5784            )
5785        };
5786        for verb in ["stop", "fail", "abort"] {
5787            super::parse_workload(&yaml("effect", verb), &HashMap::new())
5788                .unwrap_or_else(|e| panic!("effect: {verb} must load: {e}"));
5789        }
5790        // `effect:` has one spelling; `action:` is an unknown key, not an alias.
5791        assert!(
5792            super::parse_workload(&yaml("action", "abort"), &HashMap::new()).is_err(),
5793            "`action:` must be rejected"
5794        );
5795    }
5796
5797    /// The op sugars all load: `op:` as a workload's one op (string or
5798    /// template map), a block written as one string, and inside an op
5799    /// `op:` as a statement string or as the payload map.
5800    #[test]
5801    fn op_sugar_forms_load() {
5802        let stmt_of = |yaml: &str| -> String {
5803            let w = super::parse_workload(yaml, &HashMap::new())
5804                .unwrap_or_else(|e| panic!("must load:\n{yaml}\n{e}"));
5805            assert_eq!(w.ops.len(), 1, "one op from:\n{yaml}");
5806            w.ops[0]
5807                .op
5808                .get("stmt")
5809                .and_then(|v| v.as_str())
5810                .unwrap()
5811                .to_string()
5812        };
5813        assert_eq!(stmt_of("op: select 1\n"), "select 1");
5814        assert_eq!(stmt_of("op:\n  stmt: select 2\n  ratio: 3\n"), "select 2");
5815        assert_eq!(stmt_of("blocks:\n  b1: select 3\n"), "select 3");
5816        assert_eq!(stmt_of("ops:\n  o1:\n    op: select 4\n"), "select 4");
5817        assert_eq!(
5818            stmt_of("ops:\n  o1:\n    op:\n      stmt: select 5\n"),
5819            "select 5"
5820        );
5821        assert_eq!(stmt_of("ops:\n  o1:\n    stmt: select 6\n"), "select 6");
5822    }
5823
5824    /// Every retired key spelling is an error naming the key to write,
5825    /// never a silent op field or an ignored key.
5826    #[test]
5827    fn retired_op_key_spellings_name_the_canonical_key() {
5828        let cases = [
5829            ("operations: select 1\n", "under `ops:`"),
5830            ("statements: select 1\n", "under `ops:`"),
5831            ("statement: select 1\n", "under `ops:`"),
5832            ("blocks:\n  b1:\n    statements: select 1\n", "under `ops:`"),
5833            ("op:\n  - select 1\n", "under `ops:`"),
5834            ("ops: select 1\nop: select 2\n", "both `ops:` and `op:`"),
5835            (
5836                "ops: select 1\nblocks:\n  b1: select 2\n",
5837                "and `blocks:` both given",
5838            ),
5839            (
5840                "op: select 1\nblocks:\n  b1: select 2\n",
5841                "and `blocks:` both given",
5842            ),
5843            ("phases:\n  p:\n    op: select 1\n", "under `ops:`"),
5844            ("phases:\n  p:\n    statements: select 1\n", "under `ops:`"),
5845            ("ops:\n  o1:\n    statement: select 1\n", "write `stmt:`"),
5846            ("ops:\n  o1:\n    statements: select 1\n", "write `stmt:`"),
5847            ("ops:\n  o1:\n    ops: select 1\n", "write `op:`"),
5848            ("ops:\n  o1:\n    operations: select 1\n", "write `op:`"),
5849            (
5850                "ops:\n  o1:\n    stmt: select 1\n    desc: d\n",
5851                "write `description:`",
5852            ),
5853            (
5854                "ops:\n  o1:\n    stmt: select 1\n    driver: stdout\n",
5855                "write `adapter:`",
5856            ),
5857        ];
5858        for (yaml, expect) in cases {
5859            let err = match super::parse_workload(yaml, &HashMap::new()) {
5860                Ok(_) => panic!("must be rejected:\n{yaml}"),
5861                Err(e) => e,
5862            };
5863            assert!(
5864                err.contains(expect),
5865                "{yaml}\n→ {err}\nmust contain {expect:?}"
5866            );
5867        }
5868    }
5869
5870    /// A path that contains `/` but doesn't begin with one is the
5871    /// ambiguous case: `0/value` is either a JSON-Pointer missing its
5872    /// leading slash (the classic transcription bug) or a member
5873    /// literally named "0/value" (which RFC 6901 spells `/0~1value`).
5874    /// Both readings are defensible, so the parser refuses rather than
5875    /// picking one — surfaced at parse time, not as silent
5876    /// capture-misses at runtime. Bare names WITHOUT a `/` are
5877    /// unambiguous and accepted; see the tests below.
5878    #[test]
5879    fn rejects_capture_path_without_leading_slash() {
5880        let yaml = r#"
5881scenarios:
5882  default:
5883    - probe
5884phases:
5885  probe:
5886    cycles: 1
5887    ops:
5888      read_state:
5889        adapter: http
5890        method: POST
5891        uri: "http://h:8778/"
5892        body: "[]"
5893        capture:
5894          bad: "0/value"
5895"#;
5896        let err = super::parse_workload(yaml, &HashMap::new())
5897            .expect_err("path without leading / must error");
5898        assert!(
5899            err.contains("`capture.bad`") && err.contains("'/'"),
5900            "expected parse error to name the offending capture and require '/'; got: {err}"
5901        );
5902    }
5903
5904    /// A bare top-level member name means exactly `/name`, and is
5905    /// normalized to it at parse time so runtime resolves one form. This
5906    /// is the spelling `verify:`'s `field:` uses, so an author moving
5907    /// between the two blocks on one op writes the same thing twice.
5908    #[test]
5909    fn accepts_bare_member_name_as_capture_path() {
5910        let yaml = r#"
5911scenarios:
5912  default:
5913    - probe
5914phases:
5915  probe:
5916    cycles: 1
5917    ops:
5918      read_state:
5919        adapter: http
5920        method: GET
5921        uri: "http://h:8778/"
5922        capture:
5923          bare: "value"
5924          pointer: "/value"
5925          rooted: ""
5926"#;
5927        let wl = super::parse_workload(yaml, &HashMap::new()).expect("both spellings must parse");
5928        let op = wl
5929            .phases
5930            .get("probe")
5931            .expect("phase")
5932            .ops
5933            .iter()
5934            .find(|o| o.name == "read_state")
5935            .expect("op");
5936        let path_of = |wire: &str| {
5937            op.captures
5938                .iter()
5939                .find(|c| c.as_name == wire)
5940                .unwrap_or_else(|| panic!("capture {wire} missing"))
5941                .path
5942                .clone()
5943                .expect("declarative capture carries a path")
5944        };
5945        assert_eq!(
5946            path_of("bare"),
5947            "/value",
5948            "a bare name normalizes to the equivalent pointer"
5949        );
5950        assert_eq!(
5951            path_of("pointer"),
5952            "/value",
5953            "and is indistinguishable from the pointer spelling downstream"
5954        );
5955        assert_eq!(
5956            path_of("rooted"),
5957            "",
5958            "empty still addresses the root document"
5959        );
5960    }
5961
5962    /// `~` is a JSON-Pointer escape introducer (`~0` = `~`, `~1` = `/`), so
5963    /// a bare name containing one is ambiguous for the same reason `/` is.
5964    #[test]
5965    fn rejects_bare_name_containing_pointer_escape_char() {
5966        let yaml = r#"
5967scenarios:
5968  default:
5969    - probe
5970phases:
5971  probe:
5972    cycles: 1
5973    ops:
5974      read_state:
5975        adapter: http
5976        method: GET
5977        uri: "http://h:8778/"
5978        capture:
5979          bad: "a~1b"
5980"#;
5981        let err = super::parse_workload(yaml, &HashMap::new())
5982            .expect_err("a bare name with '~' must error");
5983        assert!(
5984            err.contains("`capture.bad`") && err.contains("ambiguous"),
5985            "expected an ambiguity error naming the capture; got: {err}"
5986        );
5987    }
5988
5989    #[test]
5990    fn set_value_bare_is_reference() {
5991        // A bare `set:` value is a wire REFERENCE (consistent with
5992        // comprehension r-values); a string literal is the explicit
5993        // polydat-quoted form; a number/bool is a literal; a sequence is a list.
5994        fn set_source(pair: &str) -> String {
5995            let yaml = format!(
5996                "scenarios:\n  s:\n    - set: {{ {pair} }}\n      \
5997                 phases:\n        - p\nops:\n  p: \"test\"\n"
5998            );
5999            let wl = super::parse_workload(&yaml, &HashMap::new()).expect("parse");
6000            for n in &wl.scenarios["s"] {
6001                if let ScenarioNode::Bindings { source, .. } = n {
6002                    return source.trim().to_string();
6003                }
6004            }
6005            panic!("no Bindings node for `set: {{ {pair} }}`");
6006        }
6007        // bare identifier → wire reference (unquoted)
6008        assert_eq!(set_source("x: mnc"), "const x := mnc");
6009        assert_eq!(set_source("x: verbose"), "const x := verbose");
6010        // explicit polydat-quoted form → a string literal
6011        assert_eq!(set_source(r#"x: '"verbose"'"#), r#"const x := "verbose""#);
6012        // a YAML sequence → a list literal (of references)
6013        assert_eq!(set_source("x: [a, b]"), "const x := [a, b]");
6014        // numbers/bools are literals (serde distinguishes 8 from "8")
6015        assert_eq!(set_source("x: 8"), "const x := 8");
6016        assert_eq!(set_source(r#"x: "8""#), r#"const x := "8""#);
6017        assert_eq!(set_source("x: true"), "const x := true");
6018    }
6019}