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