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, matchers, samples) =
1966                        crate::model::KeyMetric::parse_measure(family)
1967                            .map_err(|e| format!("phase '{phase_name}' key_metrics.{col}: {e}"))?;
1968                    if samples.is_some() && !crate::model::KeyMetric::is_session_family(&family) {
1969                        return Err(format!(
1970                            "phase '{phase_name}' key_metrics.{col}: a sample mode is for a \
1971                             family the session records (`sysmon_…`), which is read over \
1972                             the phase by its samples' times; '{family}' is recorded by the \
1973                             phase itself and needs none"
1974                        ));
1975                    }
1976                    if agg == crate::model::KeyAgg::Rate
1977                        && crate::model::KeyMetric::is_host_family(&family)
1978                    {
1979                        return Err(format!(
1980                            "phase '{phase_name}' key_metrics.{col}: rate() is not for a \
1981                             host measure; '{family}' is a level or is already a rate, so \
1982                             write avg(), max() or another aggregate"
1983                        ));
1984                    }
1985                    match agg {
1986                        crate::model::KeyAgg::Span if !family.is_empty() => {
1987                            return Err(format!(
1988                                "phase '{phase_name}' key_metrics.{col}: span() is \
1989                                 family-less — it measures the activation wall clock"
1990                            ));
1991                        }
1992                        crate::model::KeyAgg::Span => {}
1993                        _ if family.is_empty() => {
1994                            return Err(format!(
1995                                "phase '{phase_name}' key_metrics.{col}: {}() needs \
1996                                 a family name",
1997                                agg_name.trim()
1998                            ));
1999                        }
2000                        _ => {}
2001                    }
2002                    out.push(crate::model::KeyMetric {
2003                        column: col.clone(),
2004                        agg,
2005                        family,
2006                        matchers,
2007                        samples,
2008                    });
2009                }
2010                out
2011            }
2012        };
2013
2014        phases.insert(
2015            phase_name.clone(),
2016            WorkloadPhase {
2017                dimensions,
2018                cycles,
2019                concurrency,
2020                rate,
2021                daemon,
2022                adapter,
2023                errors,
2024                tries,
2025                tries_backoff,
2026                interval: phase_obj
2027                    .get("interval")
2028                    .and_then(|v| v.as_str().map(str::to_string)),
2029                repeat: phase_obj.get("repeat").and_then(|v| v.as_u64()),
2030                error_rate_max,
2031                timeout,
2032                stop_when,
2033                throttle,
2034                tags,
2035                ops: inline_ops,
2036                for_each,
2037                continue_if,
2038                loop_scope,
2039                iter_scope,
2040                checkpoint,
2041                status_metrics,
2042                bindings: phase_bindings_only,
2043                metrics,
2044                poll: phase_poll,
2045                optimize,
2046                key_metrics,
2047            },
2048        );
2049        phase_order.push(phase_name.clone());
2050    }
2051
2052    Ok((phases, phase_order))
2053}
2054
2055// -----------------------------------------------------------------
2056// Blocks
2057// -----------------------------------------------------------------
2058
2059fn parse_blocks(
2060    blocks_val: &JVal,
2061    doc_params: &HashMap<String, JVal>,
2062    doc_tags: &HashMap<String, String>,
2063    all_ops: &mut Vec<ParsedOp>,
2064) -> Result<(), String> {
2065    match blocks_val {
2066        JVal::Object(map) => {
2067            for (block_name, block_val) in map {
2068                parse_single_block(block_name, block_val, doc_params, doc_tags, all_ops)?;
2069            }
2070        }
2071        JVal::Array(arr) => {
2072            for (i, block_val) in arr.iter().enumerate() {
2073                let name = block_val
2074                    .get("name")
2075                    .and_then(|v| v.as_str())
2076                    .map(|s| s.to_string())
2077                    .unwrap_or_else(|| format!("block{}", i + 1));
2078                parse_single_block(&name, block_val, doc_params, doc_tags, all_ops)?;
2079            }
2080        }
2081        _ => {}
2082    }
2083    Ok(())
2084}
2085
2086fn parse_single_block(
2087    block_name: &str,
2088    block_val: &JVal,
2089    doc_params: &HashMap<String, JVal>,
2090    doc_tags: &HashMap<String, String>,
2091    all_ops: &mut Vec<ParsedOp>,
2092) -> Result<(), String> {
2093    let obj = match block_val {
2094        JVal::Object(o) => o,
2095        // A block written as a bare string is one op.
2096        JVal::String(s) => {
2097            let mut op = ParsedOp::simple("stmt1", s);
2098            op.params = exclude_non_op_keys(doc_params);
2099            op.tags = doc_tags.clone();
2100            op.tags.insert("block".to_string(), block_name.to_string());
2101            all_ops.push(op);
2102            return Ok(());
2103        }
2104        other => {
2105            return Err(format!(
2106                "block '{block_name}': must be a mapping or a single op string, got {other}"
2107            ));
2108        }
2109    };
2110
2111    // SRD-13f Push D: workload-level `bindings:` no longer
2112    // merge into block-level. Blocks are YAML organizational
2113    // sugar (not a Polydat scope), so a block's own `bindings:` is
2114    // *syntactic sugar* expanded into each enclosed op's
2115    // `op.bindings` at parse time — it does not cross any
2116    // kernel boundary, and the only "merge" left is this
2117    // block-sugar → op inlining inside `normalize_op_object`.
2118    let block_bindings = extract_bindings(obj.get("bindings"));
2119    let block_params = merge_value_maps(doc_params, &extract_value_map(obj.get("params")));
2120    let mut block_tags = merge_string_maps(doc_tags, &extract_string_map(obj.get("tags")));
2121    block_tags.insert("block".to_string(), block_name.to_string());
2122
2123    if let Some(ops_val) = op_collection(obj, &format!("block '{block_name}'"))? {
2124        parse_ops_field(
2125            &ops_val,
2126            block_name,
2127            &block_bindings,
2128            &block_params,
2129            &block_tags,
2130            all_ops,
2131        )?;
2132    }
2133
2134    Ok(())
2135}
2136
2137/// Collection keys that are not keys: the ops of a workload, phase
2138/// or block go under `ops:` (or one op under `op:`).
2139const RETIRED_COLLECTION_KEYS: &[&str] = &["operations", "statements", "statement"];
2140
2141/// The op templates of a workload, phase or block (`scope` names it
2142/// in errors). `ops:` holds them in any shape (string, list or map);
2143/// `op:` is the one-op shorthand of a workload or block (a phase
2144/// declares none) — a string is its statement and a map is the op
2145/// template itself. A retired spelling is rejected, naming `ops:`.
2146fn op_collection(obj: &serde_json::Map<String, JVal>, scope: &str) -> Result<Option<JVal>, String> {
2147    if let Some(k) = RETIRED_COLLECTION_KEYS
2148        .iter()
2149        .find(|k| obj.contains_key(**k))
2150    {
2151        return Err(format!(
2152            "{scope}: `{k}:` is not a key; write op templates under `ops:` \
2153             (or a single op under `op:`)"
2154        ));
2155    }
2156    match (obj.get("ops"), obj.get("op")) {
2157        (Some(_), Some(_)) => Err(format!(
2158            "{scope}: both `ops:` and `op:` given; `op:` is a single op and \
2159             `ops:` holds any number — write one of them"
2160        )),
2161        (Some(ops), None) => Ok(Some(ops.clone())),
2162        (None, Some(JVal::Array(_))) => Err(format!(
2163            "{scope}: `op:` is a single op; write a list of op templates under `ops:`"
2164        )),
2165        (None, Some(JVal::Object(template))) => {
2166            Ok(Some(JVal::Array(vec![JVal::Object(template.clone())])))
2167        }
2168        (None, Some(statement)) => Ok(Some(statement.clone())),
2169        (None, None) => Ok(None),
2170    }
2171}
2172
2173/// Op-template keys that are not keys, each with the key to write.
2174const RETIRED_OP_KEYS: &[(&str, &str)] = &[
2175    ("ops", "`op:`"),
2176    ("operations", "`op:`"),
2177    ("statement", "`stmt:` (or `op:`)"),
2178    ("statements", "`stmt:` (or `op:`)"),
2179    ("desc", "`description:`"),
2180    ("driver", "`adapter:`"),
2181];
2182
2183// -----------------------------------------------------------------
2184// Ops
2185// -----------------------------------------------------------------
2186
2187fn parse_ops_field(
2188    ops_val: &JVal,
2189    block_name: &str,
2190    bindings: &BindingsDef,
2191    params: &HashMap<String, JVal>,
2192    tags: &HashMap<String, String>,
2193    all_ops: &mut Vec<ParsedOp>,
2194) -> Result<(), String> {
2195    // Activity/phase-scope param keys and the workload's default-adapter
2196    // selectors are never op fields ([`exclude_non_op_keys`]). Strip them from
2197    // the inherited params before they reach any op. A genuine op-level
2198    // `rate:` or `adapter:` is written on the op and is untouched.
2199    let op_scope_params = exclude_non_op_keys(params);
2200    let params = &op_scope_params;
2201    let mut op_counter = 0;
2202
2203    match ops_val {
2204        // Single string: op: "SELECT ..."
2205        JVal::String(s) => {
2206            op_counter += 1;
2207            let name = format!("stmt{op_counter}");
2208            let mut op = ParsedOp::simple(&name, s);
2209            op.bindings = bindings.clone();
2210            op.params = params.clone();
2211            op.tags = tags.clone();
2212            op.tags.insert("block".to_string(), block_name.to_string());
2213            all_ops.push(op);
2214        }
2215
2216        // List of ops
2217        JVal::Array(arr) => {
2218            for item in arr {
2219                op_counter += 1;
2220                let auto_name = format!("stmt{op_counter}");
2221                let op = normalize_op_item(item, &auto_name, block_name, bindings, params, tags)?;
2222                all_ops.push(op);
2223            }
2224        }
2225
2226        // Map of named ops
2227        JVal::Object(map) => {
2228            for (key, val) in map {
2229                let op = normalize_op_entry(key, val, block_name, bindings, params, tags)?;
2230                all_ops.push(op);
2231            }
2232        }
2233
2234        _ => {}
2235    }
2236
2237    Ok(())
2238}
2239
2240/// Normalize a single op from a list item.
2241fn normalize_op_item(
2242    item: &JVal,
2243    auto_name: &str,
2244    block_name: &str,
2245    bindings: &BindingsDef,
2246    params: &HashMap<String, JVal>,
2247    tags: &HashMap<String, String>,
2248) -> Result<ParsedOp, String> {
2249    match item {
2250        JVal::String(s) => {
2251            let mut op = ParsedOp::simple(auto_name, s);
2252            op.bindings = bindings.clone();
2253            op.params = params.clone();
2254            op.tags = tags.clone();
2255            op.tags.insert("block".to_string(), block_name.to_string());
2256            Ok(op)
2257        }
2258        JVal::Object(map) => {
2259            // Check if first entry is name:stmt pattern
2260            if let Some((first_key, first_val)) = map.iter().next()
2261                && map.len() == 1
2262                && first_val.is_string()
2263            {
2264                let mut op = ParsedOp::simple(first_key, first_val.as_str().unwrap());
2265                op.bindings = bindings.clone();
2266                op.params = params.clone();
2267                op.tags = tags.clone();
2268                op.tags.insert("block".to_string(), block_name.to_string());
2269                return Ok(op);
2270            }
2271            // Full op object
2272            normalize_op_object(map, auto_name, block_name, bindings, params, tags)
2273        }
2274        _ => Ok(ParsedOp::simple(auto_name, "")),
2275    }
2276}
2277
2278/// Normalize a named op from a map entry.
2279fn normalize_op_entry(
2280    key: &str,
2281    val: &JVal,
2282    block_name: &str,
2283    bindings: &BindingsDef,
2284    params: &HashMap<String, JVal>,
2285    tags: &HashMap<String, String>,
2286) -> Result<ParsedOp, String> {
2287    match val {
2288        JVal::String(s) => {
2289            let mut op = ParsedOp::simple(key, s);
2290            op.bindings = bindings.clone();
2291            op.params = params.clone();
2292            op.tags = tags.clone();
2293            op.tags.insert("block".to_string(), block_name.to_string());
2294            Ok(op)
2295        }
2296        JVal::Object(map) => normalize_op_object(map, key, block_name, bindings, params, tags),
2297        JVal::Array(arr) => {
2298            // Array at op level → moved to op.stmt
2299            let mut op_fields = HashMap::new();
2300            op_fields.insert("stmt".to_string(), JVal::Array(arr.clone()));
2301            let mut op = ParsedOp {
2302                traverse: None,
2303                name: key.to_string(),
2304                description: None,
2305                op: op_fields,
2306                bindings: bindings.clone(),
2307                params: params.clone(),
2308                tags: tags.clone(),
2309                condition: None,
2310                delay: None,
2311                metrics: HashMap::new(),
2312                cell: std::collections::BTreeMap::new(),
2313                result: None,
2314                wrappers: None,
2315                captures: Vec::new(),
2316                abstract_interface: None,
2317                interface_bound: false,
2318                daemon: crate::model::DaemonSpec::Disabled,
2319                daemon_cancel_grace_ms: None,
2320                while_cond: None,
2321                rate: None,
2322            };
2323            op.tags.insert("block".to_string(), block_name.to_string());
2324            Ok(op)
2325        }
2326        _ => Ok(ParsedOp::simple(key, "")),
2327    }
2328}
2329
2330/// Human-readable name for a JSON value kind, for parse-time
2331/// error messages. ("string", "number", "array", etc.)
2332fn eval_value_kind(v: &JVal) -> &'static str {
2333    match v {
2334        JVal::Null => "null",
2335        JVal::Bool(_) => "bool",
2336        JVal::Number(_) => "number",
2337        JVal::String(_) => "string",
2338        JVal::Array(_) => "array",
2339        JVal::Object(_) => "mapping",
2340    }
2341}
2342
2343/// Sub-keys allowed inside an op-template's `evaluations:`
2344/// block. The block is a reserved closed-vocab wrapper for
2345/// post-execution validation / scoring config — distinct from
2346/// per-adapter op fields. Anything else inside it is rejected at
2347/// parse time so silent-ignore traps (a misspelled `relevency:`,
2348/// a misplaced wrapper) cannot hide a misconfigured op. New
2349/// evaluation kinds are added to the construction registry.
2350fn evaluations_vocab() -> Vec<&'static str> {
2351    crate::vocab::evaluation_kinds()
2352}
2353
2354/// Scan every string under `value` for bind points, failing on the
2355/// first malformed one ([`crate::bindpoints::extract_bind_points`]).
2356fn check_bind_points(value: &JVal) -> Result<(), String> {
2357    match value {
2358        JVal::String(s) => crate::bindpoints::extract_bind_points(s).map(|_| ()),
2359        JVal::Array(items) => items.iter().try_for_each(check_bind_points),
2360        JVal::Object(map) => map.values().try_for_each(check_bind_points),
2361        _ => Ok(()),
2362    }
2363}
2364
2365/// Normalize a full op object (map of fields).
2366fn normalize_op_object(
2367    map: &serde_json::Map<String, JVal>,
2368    default_name: &str,
2369    block_name: &str,
2370    parent_bindings: &BindingsDef,
2371    parent_params: &HashMap<String, JVal>,
2372    parent_tags: &HashMap<String, String>,
2373) -> Result<ParsedOp, String> {
2374    let name = map
2375        .get("name")
2376        .and_then(|v| v.as_str())
2377        .unwrap_or(default_name)
2378        .to_string();
2379
2380    if let Some((k, write)) = RETIRED_OP_KEYS.iter().find(|(k, _)| map.contains_key(*k)) {
2381        return Err(format!(
2382            "op '{name}' (block '{block_name}'): `{k}:` is not an op-template key; write {write}"
2383        ));
2384    }
2385
2386    let description = map
2387        .get("description")
2388        .and_then(|v| v.as_str())
2389        .map(|s| s.to_string());
2390
2391    // SRD-13f Push D: workload-level and phase-level
2392    // `bindings:` no longer touch ops at parse time — they
2393    // compile to their own kernels and reach ops via the GK
2394    // kernel chain. `parent_bindings` here carries ONLY
2395    // block-level YAML sugar (blocks are not a Polydat scope; their
2396    // `bindings:` field is a copy-paste reducer over each
2397    // enclosed op's bindings). The expansion below is the only
2398    // remaining parser-time inlining.
2399    let mut op_bindings =
2400        inline_block_sugar_into_op(parent_bindings, &extract_bindings(map.get("bindings")));
2401    let op_params = merge_value_maps(parent_params, &extract_value_map(map.get("params")));
2402    let mut op_tags = merge_string_maps(parent_tags, &extract_string_map(map.get("tags")));
2403    op_tags.insert("block".to_string(), block_name.to_string());
2404
2405    // Determine op payload
2406    //
2407    // `reserved` lists keys handled by the workload model itself
2408    // (name, bindings, etc.) — they never reach the adapter.
2409    // `evaluations` is in this list because it's a closed-vocab
2410    // wrapper for validation/scoring config (relevancy, verify)
2411    // — its sub-keys are extracted and hoisted into `op_params`
2412    // below so downstream consumers
2413    // (`crate::validation::parse_relevancy` etc.) find them at
2414    // the same address whether the workload writes the
2415    // canonical wrapped form or the legacy top-level shorthand.
2416    // `metrics` and `result` are CORE op-template fields (SRD-40b
2417    // and SRD-66 respectively) extracted into ParsedOp.metrics /
2418    // ParsedOp.result; they must be kept out of `op_fields` so
2419    // adapters with a closed-vocabulary `known_op_fields()` (HTTP,
2420    // testkit) don't reject them as unknown. The CQL adapter
2421    // returns `None` from `known_op_fields()` (open vocabulary)
2422    // which masked this for the existing workloads.
2423    let reserved = crate::vocab::op_model_fields();
2424    let op_field_names = crate::vocab::op_stmt_fields();
2425    // Activity-level params excised from op fields before the
2426    // adapter sees them. `relevancy` / `verify` stay listed here
2427    // for the legacy top-level shorthand
2428    // (`relevancy: { ... }` directly under the op); the canonical
2429    // form puts them inside `evaluations:` and is handled
2430    // separately below.
2431    let activity_params = [
2432        "ratio",
2433        "adapter",
2434        "space",
2435        "instrument",
2436        "start-timers",
2437        "stop-timers",
2438        "verify",
2439        "relevancy",
2440        "admission",
2441        "strict",
2442        "poll",
2443        "poll_interval_ms",
2444        "timeout_ms",
2445        "poll_metric_name",
2446        "emit",
2447        "batch",
2448        "max_batch_size",
2449        "batchtype",
2450        "memo",
2451        "gutter",
2452        // SRD-63 op-level status visibility. `readout: visible` opts the
2453        // op into its own timed status leaf; excised into params so the
2454        // `readout` wrapper's trigger (which reads params) sees it rather
2455        // than the field falling through to the adapter op payload.
2456        "readout",
2457        // SRD-82 op shell — a per-op error-routing override (`errors:
2458        // "<pattern>:<actions>"`), resolved into a child of the phase policy
2459        // and pinned to this op's dispenser, and the op-level `tries:`
2460        // total-attempts sigil for the conditional tries wrapper. Both are
2461        // excised from op fields so they never reach the adapter as
2462        // op-payload keys.
2463        "errors",
2464        "tries",
2465        // Tries-wrapper companion knobs (SRD-82 Part 3b): retry
2466        // pacing and retry-error exemplar sampling (`exec_events`).
2467        // Consumed at wrapper build from op params; excised here so
2468        // the documented op-level standalone form actually lands in
2469        // params instead of leaking to the adapter as payload keys.
2470        "retry_backoff",
2471        "retry_backoff_max",
2472        "retry_backoff_ratio",
2473        "retry_exemplar_rate",
2474        "retry_exemplar_max_hz",
2475        "retry_advisory",
2476    ];
2477
2478    let mut op_fields = if let Some(explicit_op) = op_field_names.iter().find_map(|k| map.get(*k)) {
2479        let mut m: HashMap<String, JVal> = match explicit_op {
2480            JVal::String(s) => {
2481                let mut m = HashMap::new();
2482                m.insert("stmt".to_string(), JVal::String(s.clone()));
2483                m
2484            }
2485            JVal::Object(o) => o.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
2486            other => {
2487                let mut m = HashMap::new();
2488                m.insert("stmt".to_string(), other.clone());
2489                m
2490            }
2491        };
2492        // Preserve sibling op-level fields so adapter-specific
2493        // extras (e.g. testkit's `result-latency`, `result-capacity`)
2494        // aren't silently dropped when the user writes shorthand:
2495        //
2496        //     insert:
2497        //       stmt: "INSERT ..."
2498        //       result-latency: "5ms"
2499        //
2500        // Without this loop the whole object would collapse to just
2501        // `stmt` and the sibling fields would never reach the adapter.
2502        // Keys already present in the explicit op payload win, so an
2503        // `op:` sub-object still has final say over its own shape.
2504        for (k, v) in map.iter() {
2505            if reserved.contains(&k.as_str())
2506                || op_field_names.contains(&k.as_str())
2507                || activity_params.contains(&k.as_str())
2508            {
2509                continue;
2510            }
2511            m.entry(k.clone()).or_insert_with(|| v.clone());
2512        }
2513        m
2514    } else {
2515        // All non-reserved, non-activity-param fields become op fields
2516        map.iter()
2517            .filter(|(k, _)| {
2518                !reserved.contains(&k.as_str())
2519                    && !op_field_names.contains(&k.as_str())
2520                    && !activity_params.contains(&k.as_str())
2521            })
2522            .map(|(k, v)| (k.clone(), v.clone()))
2523            .collect()
2524    };
2525
2526    // Excise activity-level params from op fields into params
2527    let mut op_params = op_params;
2528    for ap in &activity_params {
2529        if let Some(val) = map.get(*ap) {
2530            // Activity params excised from op fields into params map
2531            op_params.insert(ap.to_string(), val.clone());
2532        }
2533    }
2534
2535    // Canonical `evaluations:` wrapper — closed-vocab
2536    // validation/scoring config. Sub-keys are extracted and
2537    // hoisted into `op_params` so downstream consumers (e.g.
2538    // `crate::validation::parse_relevancy`,
2539    // `crate::validation::parse_assertions`) find them at the
2540    // same address whether the workload uses this canonical
2541    // form or the legacy top-level shorthand. Anything inside
2542    // `evaluations:` that isn't in `EVALUATIONS_VOCAB` is
2543    // rejected up front — the whole point of the wrapper is to
2544    // catch misspellings (`relevency:`) and misplaced wrappers
2545    // that the silent-routing path would otherwise drop on the
2546    // floor.
2547    if let Some(eval_val) = map.get("evaluations") {
2548        let eval_obj = eval_val.as_object().ok_or_else(|| {
2549            format!(
2550                "op '{name}' (block '{block_name}'): `evaluations:` must be a \
2551             mapping, got {kind}. Expected shape: \
2552             `evaluations: {{ relevancy: {{...}}, verify: [...] }}`.",
2553                kind = eval_value_kind(eval_val),
2554            )
2555        })?;
2556        for (k, v) in eval_obj.iter() {
2557            if !evaluations_vocab().contains(&k.as_str()) {
2558                return Err(format!(
2559                    "op '{name}' (block '{block_name}'): unknown key \
2560                     '{k}' under `evaluations:`. Allowed keys: [{}]. \
2561                     Each entry under `evaluations:` is a distinct \
2562                     post-execution evaluation kind — typos and \
2563                     misplaced wrappers are rejected here so silent \
2564                     skipped recall / verify can't happen.",
2565                    evaluations_vocab().join(", "),
2566                ));
2567            }
2568            // Top-level shorthand wins on collision so users
2569            // who already have `relevancy: {...}` at the op
2570            // level don't see their config replaced if they
2571            // also added `evaluations: { relevancy: {...} }`.
2572            // Warn so the duplicate is visible.
2573            if op_params.contains_key(k.as_str()) {
2574                eprintln!(
2575                    "warning: op '{name}' has '{k}' both at top level \
2576                     and under `evaluations:` — top-level wins. Pick \
2577                     one form.",
2578                );
2579                continue;
2580            }
2581            op_params.insert(k.clone(), v.clone());
2582        }
2583    }
2584
2585    // SRD-108 Part B (+ SRD-109 Part 3) — `abstract:` declares
2586    // this op as a typed slot: `{ needs: {name: type,…}, yields:
2587    // {name: type,…}, results: {name: type,…} }`. Unknown keys
2588    // are rejected; each type is a polydat type keyword, resolved
2589    // here and verified against the compiled op-template program
2590    // at pre-map synthesis.
2591    let abstract_interface: Option<crate::model::OpInterface> = match map.get("abstract") {
2592        None => None,
2593        Some(v) => {
2594            let obj = v.as_object().ok_or_else(|| format!(
2595                    "op '{name}': `abstract:` must be a mapping with                      `needs:` / `yields:` / `results:` maps of wire-name -> type"))?;
2596            let mut iface = crate::model::OpInterface::default();
2597            for (k, section) in obj {
2598                let target = match k.as_str() {
2599                    "needs" => &mut iface.needs,
2600                    "yields" => &mut iface.yields,
2601                    "results" => &mut iface.results,
2602                    other => {
2603                        return Err(format!(
2604                            "op '{name}': unknown key '{other}' under                              `abstract:` (allowed: needs, yields, results)"
2605                        ));
2606                    }
2607                };
2608                let entries = section.as_object().ok_or_else(|| format!(
2609                        "op '{name}': `abstract.{k}:` must be a mapping                          of wire-name -> type"))?;
2610                for (wire, typ) in entries {
2611                    let type_name = typ.as_str().ok_or_else(|| format!(
2612                            "op '{name}': `abstract.{k}.{wire}:` type                              must be a string, got {typ}"))?;
2613                    let port_type = crate::port_types::resolve_type_keyword(type_name)
2614                        .map_err(|e| format!("op '{name}': `abstract.{k}.{wire}:` {e}"))?;
2615                    target.insert(wire.clone(), port_type);
2616                }
2617            }
2618            Some(iface)
2619        }
2620    };
2621
2622    let condition = map
2623        .get("if")
2624        .and_then(|v| v.as_str())
2625        .map(normalize_condition_clause);
2626
2627    let delay = match map.get("delay") {
2628        None => None,
2629        Some(v) => {
2630            Some(crate::model::parse_delay_spec_value(v).map_err(|e| format!("op '{name}': {e}"))?)
2631        }
2632    };
2633
2634    // Daemon-op declaration. Parses bool / int / "on"/"off" /
2635    // "true"/"false" via `parse_daemon_spec_value`. When set
2636    // to MaxFibers(N), the cycle-pool dispatch spawns the op
2637    // on a daemon fiber instead of awaiting inline; the cap
2638    // is enforced at spawn time.
2639    let daemon = match map.get("daemon") {
2640        Some(v) => crate::model::parse_daemon_spec_value(v)
2641            .map_err(|e| format!("op '{name}' (block '{block_name}'): {e}",))?,
2642        None => crate::model::DaemonSpec::Disabled,
2643    };
2644    let daemon_cancel_grace_ms = map.get("daemon_cancel_grace_ms").and_then(|v| {
2645        v.as_u64()
2646            .or_else(|| v.as_str().and_then(|s| s.parse::<u64>().ok()))
2647    });
2648    let daemon_enabled = !daemon.is_disabled();
2649    if daemon_enabled {
2650        // `cycles:` and `ratio:` on a daemon op are workload-shape
2651        // errors — the daemon's dispatch cadence is governed by
2652        // the cycle-pool walks + per-op `rate:`, not by cycles or
2653        // ratios. Silently accepting them would hide a mis-shaped
2654        // workload; reject at parse so the operator sees the
2655        // contradiction immediately.
2656        if let Some(c) = op_params.get("cycles") {
2657            return Err(format!(
2658                "op '{name}' (block '{block_name}'): `daemon:` and \
2659                 `cycles: {c}` are mutually exclusive. A daemon op's \
2660                 dispatch cadence is governed by the cycle-pool's \
2661                 stanza walk + per-op `rate:`, not by `cycles:`."
2662            ));
2663        }
2664        if let Some(r) = op_params.get("ratio") {
2665            return Err(format!(
2666                "op '{name}' (block '{block_name}'): `daemon:` and \
2667                 `ratio: {r}` are mutually exclusive — a daemon op \
2668                 does not participate in cycle-pool ratio scheduling."
2669            ));
2670        }
2671    }
2672    if !daemon_enabled && daemon_cancel_grace_ms.is_some() {
2673        return Err(format!(
2674            "op '{name}' (block '{block_name}'): \
2675             `daemon_cancel_grace_ms` is only meaningful when \
2676             `daemon:` is enabled (true / N). Either enable `daemon:` \
2677             or drop the grace field."
2678        ));
2679    }
2680
2681    // Loop / rate primitives (apply to both cycle-pool and
2682    // daemon ops, though the typical use case is daemon+while+rate).
2683    let while_cond = map
2684        .get("while")
2685        .and_then(|v| v.as_str())
2686        .map(|s| s.trim().to_string())
2687        .filter(|s| !s.is_empty());
2688    let rate = map.get("rate").and_then(|v| {
2689        v.as_str()
2690            .map(|s| s.to_string())
2691            .or_else(|| v.as_u64().map(|n| n.to_string()))
2692            .or_else(|| v.as_f64().map(|f| f.to_string()))
2693    });
2694    // Rate without while- or per-cycle dispatch is meaningless —
2695    // an op that fires once-per-cycle can't be rate-limited in
2696    // any observable way. Warn at parse rather than silently
2697    // accepting a no-op field.
2698    if rate.is_some() && while_cond.is_none() && daemon.is_disabled() {
2699        // Soft warn via stderr; this is a workload-shape smell
2700        // but not always an error (a workload-author may be
2701        // configuring forward-compatible op templates).
2702        eprintln!(
2703            "warning: op '{name}' (block '{block_name}'): `rate:` is set \
2704             but the op has neither `while:` nor `daemon:`. The rate \
2705             limit will only fire on each cycle-pool dispatch — likely \
2706             not the intended behavior. Add `while:` for a loop or \
2707             `daemon:` to enable fiber-kind dispatch.",
2708        );
2709    }
2710
2711    let metrics = parse_metrics_field(map.get("metrics"), &name, &mut op_bindings)
2712        .map_err(|e| format!("op '{name}' metrics: {e}"))?;
2713    let cell = parse_cell_map(map.get("cell")).map_err(|e| format!("op '{name}' {e}"))?;
2714    let traverse = parse_traverse_field(map.get("traverse"), &name)?;
2715    let result = parse_result_field(map.get("result"), &name)
2716        .map_err(|e| format!("op '{name}' result: {e}"))?;
2717
2718    // Extract capture-point specs from every string-valued entry in
2719    // `op` and replace each value with the bracket-stripped form.
2720    // Adapters consume the cleaned text; `TraversingDispenser` and
2721    // other capture-aware wrappers read the harvested specs from
2722    // `ParsedOp.captures` directly — no re-parse at wrap-time.
2723    //
2724    // De-duplicates by `as_name` across multiple op-fields: the
2725    // same wire name appearing in two fields means the same
2726    // capture, not two separate writes.
2727    let mut captures: Vec<crate::bindpoints::CapturePoint> = Vec::new();
2728    // Declarative `capture:` map block — pulls JSON-Pointer-keyed
2729    // values out of structured response bodies (e.g. Jolokia
2730    // bulk-POST arrays). Each entry is a path string addressed
2731    // by [`serde_json::Value::pointer`]; a trailing `:count`
2732    // collapses the addressed sub-tree to a u64 count instead
2733    // of capturing it as-is. This complements the legacy
2734    // bracket form `[name]` embedded in op text — that form
2735    // still works for adapters whose statements have column
2736    // references; the declarative form is for adapters whose
2737    // responses are JSON and need positional / nested access.
2738    if let Some(cap_val) = map.get("capture") {
2739        let cap_obj = cap_val.as_object().ok_or_else(|| {
2740            format!(
2741                "op '{name}' (block '{block_name}'): `capture:` must be a \
2742             mapping of <wire-name> → <json-pointer-path>. Got {kind}.",
2743                kind = eval_value_kind(cap_val),
2744            )
2745        })?;
2746        for (wire_name, spec_val) in cap_obj.iter() {
2747            let raw = spec_val.as_str().ok_or_else(|| {
2748                format!(
2749                    "op '{name}' (block '{block_name}'): `capture.{wire_name}` \
2750                 must be a string (JSON-Pointer path, optionally with a \
2751                 `:count` suffix). Got {kind}.",
2752                    kind = eval_value_kind(spec_val),
2753                )
2754            })?;
2755            let (path, count, agg, row_filter) = match raw.strip_suffix(":count") {
2756                Some(p) => (p.to_string(), true, None, None),
2757                None => match parse_capture_agg_suffix(raw) {
2758                    Some(suffix) => (
2759                        suffix.path_prefix,
2760                        false,
2761                        Some(suffix.agg),
2762                        suffix.row_filter,
2763                    ),
2764                    None => (raw.to_string(), false, None, None),
2765                },
2766            };
2767            // Two accepted spellings, one meaning — but never a guess in
2768            // between:
2769            //
2770            //   `/value`, `/0/name`  RFC 6901 JSON-Pointer, used verbatim.
2771            //   `value`              a bare top-level member name, which is
2772            //                        exactly `/value` and normalized to it
2773            //                        here, so runtime has one form to resolve.
2774            //   ``                   the root document.
2775            //
2776            // A bare name may contain neither `/` nor `~`, and that is the
2777            // whole anti-ambiguity rule: `a/b` could be a pointer someone
2778            // forgot to lead with '/', or a member literally named "a/b"
2779            // (RFC 6901 spells that `/a~1b`), and `~0`/`~1` are pointer
2780            // escapes. Rather than pick a reading, name both and let the
2781            // author say which. `verify:`'s `field:` is a bare name by
2782            // definition, so an author moving between the two blocks lands
2783            // on the bare form naturally — it now works rather than erroring.
2784            let path = if path.is_empty() || path.starts_with('/') {
2785                path
2786            } else if !path.contains('/') && !path.contains('~') {
2787                format!("/{path}")
2788            } else {
2789                return Err(format!(
2790                    "op '{name}' (block '{block_name}'): \
2791                     `capture.{wire_name}` path '{path}' is ambiguous. Write \
2792                     a JSON-Pointer starting with '/' (e.g. '/{first}/...', \
2793                     escaping '~' as '~0' and '/' as '~1'), or a bare \
2794                     top-level member name containing neither '/' nor '~'. \
2795                     An empty path addresses the root document.",
2796                    first = path.split('/').next().unwrap_or(&path),
2797                ));
2798            };
2799            captures.push(crate::bindpoints::CapturePoint {
2800                row_filter,
2801                source_name: wire_name.clone(),
2802                as_name: wire_name.clone(),
2803                cast_type: None,
2804                slurp: false,
2805                path: Some(path),
2806                count,
2807                agg,
2808            });
2809        }
2810    }
2811    for value in op_fields.values_mut() {
2812        if let serde_json::Value::String(s) = value {
2813            let parsed = crate::bindpoints::parse_capture_points(s);
2814            if parsed.captures.is_empty() {
2815                continue;
2816            }
2817            for cap in parsed.captures {
2818                if !captures
2819                    .iter()
2820                    .any(|existing| existing.as_name == cap.as_name)
2821                {
2822                    captures.push(cap);
2823                }
2824            }
2825            *s = parsed.raw_template;
2826        }
2827    }
2828
2829    // Every op field and param is bind-point text the runtime
2830    // scans again later; refuse a malformed bind point here, where
2831    // the op and field can be named.
2832    for (section, fields) in [("field", &op_fields), ("param", &op_params)] {
2833        for (field, value) in fields.iter() {
2834            check_bind_points(value)
2835                .map_err(|e| format!("op '{name}' {section} '{field}': {e}"))?;
2836        }
2837    }
2838
2839    Ok(ParsedOp {
2840        traverse,
2841        name,
2842        description,
2843        op: op_fields,
2844        bindings: op_bindings,
2845        params: op_params,
2846        tags: op_tags,
2847        condition,
2848        delay,
2849        metrics,
2850        cell,
2851        result,
2852        wrappers: None,
2853        captures,
2854        abstract_interface,
2855        interface_bound: false,
2856        daemon,
2857        daemon_cancel_grace_ms,
2858        while_cond,
2859        rate,
2860    })
2861}
2862
2863/// Split an optional `where <field>='<value>'` predicate off the tail of an
2864/// aggregate's argument, returning `(field_expr, predicate)`.
2865///
2866/// `progress where kind='secondary index build'` →
2867/// `("progress", Some(("kind", "secondary index build")))`.
2868///
2869/// Single or double quotes; the value may contain spaces, which is why it is
2870/// quoted rather than whitespace-delimited.
2871fn split_capture_row_filter(arg: &str) -> (String, Option<(String, String)>) {
2872    let lower = arg.to_ascii_lowercase();
2873    let Some(idx) = lower.find(" where ") else {
2874        return (arg.trim().to_string(), None);
2875    };
2876    let field = arg[..idx].trim().to_string();
2877    let pred = arg[idx + " where ".len()..].trim();
2878    let Some((k, v)) = pred.split_once('=') else {
2879        return (arg.trim().to_string(), None);
2880    };
2881    let k = k.trim();
2882    let v = v.trim();
2883    let unquoted = v
2884        .strip_prefix('\'')
2885        .and_then(|r| r.strip_suffix('\''))
2886        .or_else(|| v.strip_prefix('"').and_then(|r| r.strip_suffix('"')));
2887    match unquoted {
2888        Some(val) if !k.is_empty() => (field, Some((k.to_string(), val.to_string()))),
2889        // An unquoted or malformed predicate is left alone rather than
2890        // silently half-applied — the caller then treats the whole string as a
2891        // field name and the unknown-field error names it.
2892        _ => (arg.trim().to_string(), None),
2893    }
2894}
2895
2896/// A declarative capture path split at its aggregation suffix.
2897struct CaptureAggSuffix {
2898    /// The path before the suffix; empty addresses the whole rows array.
2899    path_prefix: String,
2900    /// The fold the suffix names.
2901    agg: crate::bindpoints::CaptureAgg,
2902    /// The `where <field>='<value>'` row filter, as `(field, value)`.
2903    row_filter: Option<(String, String)>,
2904}
2905
2906/// Parses a `:min(field)` / `:max(field)` / `:sum(field)` suffix on a
2907/// declarative capture path, with an optional `where <field>='<value>'`
2908/// row filter inside the parentheses. Returns `None` when the spec
2909/// carries no recognized aggregation suffix.
2910fn parse_capture_agg_suffix(raw: &str) -> Option<CaptureAggSuffix> {
2911    use crate::bindpoints::CaptureAgg;
2912    if !raw.ends_with(')') {
2913        return None;
2914    }
2915    for (tag, make) in [
2916        (":min(", CaptureAgg::Min as fn(String) -> CaptureAgg),
2917        (":max(", CaptureAgg::Max as fn(String) -> CaptureAgg),
2918        (":sum(", CaptureAgg::Sum as fn(String) -> CaptureAgg),
2919    ] {
2920        if let Some(idx) = raw.rfind(tag) {
2921            let arg = &raw[idx + tag.len()..raw.len() - 1];
2922            let (field, row_filter) = split_capture_row_filter(arg);
2923            if !field.is_empty() && field.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
2924                return Some(CaptureAggSuffix {
2925                    path_prefix: raw[..idx].to_string(),
2926                    agg: make(field),
2927                    row_filter,
2928                });
2929            }
2930        }
2931    }
2932    None
2933}
2934
2935/// SRD-40b §1 + §2: parse the `metrics:` field on an op
2936/// template. Three YAML shapes accepted, dispatched on the
2937/// value's type:
2938///
2939/// - **Scalar** (bare string, §2.1): one metric with the
2940///   string as both family and `value:`.
2941/// - **Sequence** (list, §2.2): each entry is a bare-name
2942///   string OR a `name := <Polydat expression>` wire-expression.
2943///   Wire expressions are auto-injected into the op's
2944///   `bindings:` block; the metric is then a bare-name
2945///   reference to the new wire.
2946/// - **Mapping** (object, §2.3): canonical full-shape form
2947///   keyed by metric name. Each value is either a string
2948///   (treated as `value:`) or a full `MetricSpec` mapping.
2949fn parse_metrics_field(
2950    val: Option<&JVal>,
2951    op_name: &str,
2952    op_bindings: &mut BindingsDef,
2953) -> Result<HashMap<String, MetricSpec>, String> {
2954    use crate::model::MetricSpec;
2955    let Some(v) = val else {
2956        return Ok(HashMap::new());
2957    };
2958    let mut out: HashMap<String, MetricSpec> = HashMap::new();
2959    match v {
2960        JVal::String(s) => {
2961            let name = s.trim().to_string();
2962            if name.is_empty() {
2963                return Err("scalar form requires a metric name".into());
2964            }
2965            out.insert(
2966                name.clone(),
2967                MetricSpec {
2968                    value: name,
2969                    family: None,
2970                    kind: None,
2971                    unit: None,
2972                    format: None,
2973                    cell: Default::default(),
2974                },
2975            );
2976        }
2977        JVal::Array(items) => {
2978            for (idx, item) in items.iter().enumerate() {
2979                let raw = item.as_str().ok_or_else(|| {
2980                    format!(
2981                        "metrics list entry {idx}: must be a string \
2982                     (bare name or `name := <polydat expr>`)"
2983                    )
2984                })?;
2985                let trimmed = raw.trim();
2986                if let Some((name, expr)) = trimmed.split_once(":=") {
2987                    // Wire-expression form: declare the binding +
2988                    // register the metric.
2989                    let name = name.trim();
2990                    let expr = expr.trim();
2991                    if name.is_empty() || expr.is_empty() {
2992                        return Err(format!(
2993                            "metrics list entry {idx} '{raw}': wire \
2994                             expression must be `name := <expression>`"
2995                        ));
2996                    }
2997                    inject_wire_into_bindings(op_bindings, name, expr, op_name)?;
2998                    if out.contains_key(name) {
2999                        return Err(format!("duplicate metric wire '{name}' in metrics list"));
3000                    }
3001                    out.insert(
3002                        name.to_string(),
3003                        MetricSpec {
3004                            value: name.to_string(),
3005                            family: None,
3006                            kind: None,
3007                            unit: None,
3008                            format: None,
3009                            cell: Default::default(),
3010                        },
3011                    );
3012                } else {
3013                    // Bare-name form.
3014                    if trimmed.is_empty() {
3015                        return Err(format!("metrics list entry {idx}: empty name"));
3016                    }
3017                    if out.contains_key(trimmed) {
3018                        return Err(format!("duplicate metric '{trimmed}' in metrics list"));
3019                    }
3020                    out.insert(
3021                        trimmed.to_string(),
3022                        MetricSpec {
3023                            value: trimmed.to_string(),
3024                            family: None,
3025                            kind: None,
3026                            unit: None,
3027                            format: None,
3028                            cell: Default::default(),
3029                        },
3030                    );
3031                }
3032            }
3033        }
3034        JVal::Object(map) => {
3035            for (key, val) in map {
3036                if out.contains_key(key) {
3037                    return Err(format!("duplicate metric key '{key}' in metrics map"));
3038                }
3039                let mut spec = parse_metric_spec_value(val, key)?;
3040                // SRD-13d Phase 9 mapping-form auto-inject: if
3041                // `value:` isn't a bare name, promote it to an
3042                // op-template binding `<key> := <value>` and
3043                // replace the spec's `value:` with the bare key.
3044                // Mirrors the list-form `name := expr` flow.
3045                let value_trimmed = spec.value.trim();
3046                let bare = !value_trimmed.is_empty()
3047                    && value_trimmed
3048                        .chars()
3049                        .all(|c| c.is_alphanumeric() || c == '_');
3050                if !bare {
3051                    if !is_valid_ident(key) {
3052                        return Err(format!(
3053                            "metric '{key}' value '{value}' is a non-bare \
3054                             expression so the metric key must itself be a \
3055                             valid identifier (alphanumerics + underscore, \
3056                             not starting with a digit) so it can be used \
3057                             as a binding name. Rename the metric key, or \
3058                             move the expression into `bindings:` and set \
3059                             `value:` to the bare name.",
3060                            value = spec.value
3061                        ));
3062                    }
3063                    inject_wire_into_bindings(op_bindings, key, value_trimmed, op_name)?;
3064                    spec.value = key.clone();
3065                }
3066                out.insert(key.clone(), spec);
3067            }
3068        }
3069        _ => {
3070            return Err(format!(
3071                "metrics: expected scalar, sequence, or mapping; got {v:?}"
3072            ));
3073        }
3074    }
3075    Ok(out)
3076}
3077
3078/// Parse a phase-level `metrics:` field. Same three YAML shapes as
3079/// the op-level [`parse_metrics_field`] (scalar / sequence / mapping)
3080/// and the same [`MetricSpec`] schema, with one deliberate
3081/// difference: phase metrics do **not** auto-inject non-bare value
3082/// expressions into a `bindings:` block. Op metrics inject so the
3083/// closure-binding-economy walker can allocate magic-extern slots
3084/// (`body`/`count`/`ok`) for the value expression; phase metrics have
3085/// no result body and are pulled directly by the executor from
3086/// `__metric_<name>`, so the phase synthesiser emits
3087/// `volatile __metric_<name> := <value>` straight from the raw
3088/// `value:` expression preserved here.
3089/// Parse a phase-level `dimensions:` block.
3090///
3091/// ```yaml
3092/// dimensions:
3093///   tier: { type: str }
3094///   tier: str            # shorthand
3095/// ```
3096///
3097/// Unknown keys are rejected rather than dropped: a silently-ignored
3098/// dimension declaration would make a metric's `cell:` reference fail its
3099/// existence check for a reason nothing points at.
3100/// Check every `cell:` reference in a phase against its declared dimensions.
3101///
3102/// Both tiers are covered: the phase's own `metrics:` and each inline op's.
3103/// The error names the declared set, because the common failure is a name
3104/// declared one tier away rather than a nonsense name.
3105fn validate_cell_dimensions(
3106    phase_name: &str,
3107    dimensions: &std::collections::BTreeMap<String, crate::model::DimensionSpec>,
3108    ops: &[ParsedOp],
3109    phase_metrics: &HashMap<String, MetricSpec>,
3110) -> Result<(), String> {
3111    let declared = || {
3112        if dimensions.is_empty() {
3113            "none are declared on this phase".to_string()
3114        } else {
3115            format!(
3116                "declared here: {}",
3117                dimensions.keys().cloned().collect::<Vec<_>>().join(", ")
3118            )
3119        }
3120    };
3121    let check =
3122        |site: &str, cell: &std::collections::BTreeMap<String, String>| -> Result<(), String> {
3123            for dim in cell.keys() {
3124                if !dimensions.contains_key(dim) {
3125                    return Err(format!(
3126                        "phase '{phase_name}' {site}: cell \
3127                     dimension '{dim}' is not declared. A dimension is a label \
3128                     name owned by exactly one tier, so declare it on the phase \
3129                     ({dim}: str) before placing a measurement in it — {}",
3130                        declared()
3131                    ));
3132                }
3133            }
3134            Ok(())
3135        };
3136    for (name, spec) in phase_metrics {
3137        check(&format!("phase-level metric '{name}'"), &spec.cell)?;
3138    }
3139    for op in ops {
3140        for (name, spec) in &op.metrics {
3141            check(&format!("op '{}' metric '{name}'", op.name), &spec.cell)?;
3142        }
3143        check(&format!("op '{}'", op.name), &op.cell)?;
3144    }
3145    Ok(())
3146}
3147
3148/// Parse a `cell:` placement: `<dimension>: <polydat expression>`.
3149///
3150/// One grammar for a metric's `cell:` and an op's. Each expression is
3151/// reified by scope synthesis as a typed kernel binding, so a
3152/// coordinate is compiled and checkable rather than a string assembled
3153/// at runtime. The error starts at `cell`; the caller names the site.
3154fn parse_cell_map(
3155    val: Option<&JVal>,
3156) -> Result<std::collections::BTreeMap<String, String>, String> {
3157    let mut cell = std::collections::BTreeMap::new();
3158    match val {
3159        None => {}
3160        Some(JVal::Object(dims)) => {
3161            if dims.is_empty() {
3162                return Err("cell: empty. Omit `cell:` entirely, or name at least one \
3163                     dimension."
3164                    .to_string());
3165            }
3166            for (dim, expr) in dims {
3167                let expr = expr.as_str().ok_or_else(|| {
3168                    format!("cell '{dim}': expected a polydat expression string, got {expr:?}")
3169                })?;
3170                if expr.trim().is_empty() {
3171                    return Err(format!("cell '{dim}': empty expression"));
3172                }
3173                if !is_valid_ident(dim) {
3174                    return Err(format!(
3175                        "cell '{dim}': a dimension name becomes a metric label, so it \
3176                         must be a valid identifier (alphanumerics + underscore, not \
3177                         starting with a digit)"
3178                    ));
3179                }
3180                cell.insert(dim.clone(), expr.trim().to_string());
3181            }
3182        }
3183        Some(other) => {
3184            return Err(format!(
3185                "cell: expected a mapping of <dimension>: <expression>, got {other:?}"
3186            ));
3187        }
3188    }
3189    Ok(cell)
3190}
3191
3192fn parse_dimensions_field(
3193    val: Option<&JVal>,
3194    phase_name: &str,
3195) -> Result<std::collections::BTreeMap<String, crate::model::DimensionSpec>, String> {
3196    use crate::model::{DimensionSpec, DimensionType};
3197    let mut out = std::collections::BTreeMap::new();
3198    let Some(v) = val else { return Ok(out) };
3199    let JVal::Object(map) = v else {
3200        return Err(format!(
3201            "phase '{phase_name}' dimensions: expected a mapping of \
3202             <name>: <declaration>, got {v:?}"
3203        ));
3204    };
3205    for (name, decl) in map {
3206        if !is_valid_ident(name) {
3207            return Err(format!(
3208                "phase '{phase_name}' dimension '{name}': a dimension name \
3209                 becomes a metric label, so it must be a valid identifier \
3210                 (alphanumerics + underscore, not starting with a digit)"
3211            ));
3212        }
3213        let value_type = match decl {
3214            // Shorthand: `tier: str`
3215            JVal::String(s) => parse_dimension_type(s, phase_name, name)?,
3216            JVal::Object(obj) => {
3217                for k in obj.keys() {
3218                    if k != "type" {
3219                        return Err(format!(
3220                            "phase '{phase_name}' dimension '{name}': unknown \
3221                             field `{k}`. Recognised fields: type"
3222                        ));
3223                    }
3224                }
3225                match obj.get("type") {
3226                    None => DimensionType::default(),
3227                    Some(JVal::String(s)) => parse_dimension_type(s, phase_name, name)?,
3228                    Some(other) => {
3229                        return Err(format!(
3230                            "phase '{phase_name}' dimension '{name}' type: \
3231                         expected a string, got {other:?}"
3232                        ));
3233                    }
3234                }
3235            }
3236            other => {
3237                return Err(format!(
3238                    "phase '{phase_name}' dimension '{name}': expected a type \
3239                 name or a mapping, got {other:?}"
3240                ));
3241            }
3242        };
3243        out.insert(name.clone(), DimensionSpec { value_type });
3244    }
3245    Ok(out)
3246}
3247
3248fn parse_dimension_type(
3249    s: &str,
3250    phase_name: &str,
3251    dim: &str,
3252) -> Result<crate::model::DimensionType, String> {
3253    let written = s.trim();
3254    match crate::port_types::resolve_type_keyword(written) {
3255        Ok(crate::port_types::PortType::Str) => Ok(crate::model::DimensionType::Str),
3256        Ok(other) => Err(format!(
3257            "phase '{phase_name}' dimension '{dim}' type '{other}': label \
3258             values are strings; `str` is the only supported type"
3259        )),
3260        Err(e) => Err(format!("phase '{phase_name}' dimension '{dim}': {e}")),
3261    }
3262}
3263
3264fn parse_phase_metrics_field(
3265    val: Option<&JVal>,
3266    phase_name: &str,
3267) -> Result<HashMap<String, MetricSpec>, String> {
3268    use crate::model::MetricSpec;
3269    let Some(v) = val else {
3270        return Ok(HashMap::new());
3271    };
3272    let mut out: HashMap<String, MetricSpec> = HashMap::new();
3273    match v {
3274        JVal::String(s) => {
3275            // Scalar: a bare wire name used as both family and value.
3276            let name = s.trim().to_string();
3277            if name.is_empty() {
3278                return Err("scalar form requires a metric name".into());
3279            }
3280            out.insert(
3281                name.clone(),
3282                MetricSpec {
3283                    value: name,
3284                    family: None,
3285                    kind: None,
3286                    unit: None,
3287                    format: None,
3288                    cell: Default::default(),
3289                },
3290            );
3291        }
3292        JVal::Array(items) => {
3293            // Sequence: bare wire names only (no `name := expr` form —
3294            // phase metrics don't inject bindings).
3295            for (idx, item) in items.iter().enumerate() {
3296                let raw = item
3297                    .as_str()
3298                    .ok_or_else(|| format!("metrics list entry {idx}: must be a bare wire name"))?;
3299                let name = raw.trim();
3300                if name.is_empty() {
3301                    return Err(format!("metrics list entry {idx}: empty name"));
3302                }
3303                if name.contains(":=") {
3304                    return Err(format!(
3305                        "metrics list entry {idx} '{raw}': the `name := expr` \
3306                         form is op-only; for a phase, declare the wire in the \
3307                         phase `bindings:` block and list its bare name here, \
3308                         or use the mapping form `{{ {name}: {{ value: <expr> }} }}`"
3309                    ));
3310                }
3311                if out.contains_key(name) {
3312                    return Err(format!("duplicate metric '{name}' in metrics list"));
3313                }
3314                out.insert(
3315                    name.to_string(),
3316                    MetricSpec {
3317                        value: name.to_string(),
3318                        family: None,
3319                        kind: None,
3320                        unit: None,
3321                        format: None,
3322                        cell: Default::default(),
3323                    },
3324                );
3325            }
3326        }
3327        JVal::Object(map) => {
3328            // Mapping: canonical full-shape form. Raw `value:` kept.
3329            for (key, val) in map {
3330                if out.contains_key(key) {
3331                    return Err(format!("duplicate metric key '{key}' in metrics map"));
3332                }
3333                out.insert(key.clone(), parse_metric_spec_value(val, key)?);
3334            }
3335        }
3336        _ => {
3337            return Err(format!(
3338                "phase '{phase_name}' metrics: expected scalar, sequence, or \
3339             mapping; got {v:?}"
3340            ));
3341        }
3342    }
3343    Ok(out)
3344}
3345
3346/// Parse one entry under the mapping form of `metrics:`.
3347/// Accepts a bare string (treated as `value:`) or a full
3348/// `MetricSpec` object.
3349fn parse_metric_spec_value(v: &JVal, key: &str) -> Result<crate::model::MetricSpec, String> {
3350    use crate::model::MetricSpec;
3351    match v {
3352        JVal::String(s) => Ok(MetricSpec {
3353            value: s.clone(),
3354            family: None,
3355            kind: None,
3356            unit: None,
3357            format: None,
3358            cell: Default::default(),
3359        }),
3360        JVal::Object(map) => {
3361            // SRD-30 unknown-field hygiene: reject any key outside the
3362            // MetricSpec surface rather than silently dropping it (a
3363            // dropped `kind:` would let a counter/histogram silently
3364            // default to gauge). The instrument-type discriminator is
3365            // `kind`, not `type` — `type` is the word OpenMetrics /
3366            // Prometheus use, so it's the predictable mistake; give it
3367            // a targeted hint.
3368            const KNOWN: &[&str] = &["value", "family", "kind", "unit", "format", "cell"];
3369            for k in map.keys() {
3370                if KNOWN.contains(&k.as_str()) {
3371                    continue;
3372                }
3373                let hint = if k == "type" {
3374                    " — the instrument-type discriminator is `kind` \
3375                     (gauge | histogram | counter)"
3376                } else {
3377                    ""
3378                };
3379                return Err(format!(
3380                    "metric '{key}': unknown field `{k}`{hint}. Recognised \
3381                     fields: value, family, kind, unit, format, cell"
3382                ));
3383            }
3384            let value = map
3385                .get("value")
3386                .and_then(|v| v.as_str())
3387                .ok_or_else(|| {
3388                    format!(
3389                        "metric '{key}': required field `value:` missing or \
3390                     not a string"
3391                    )
3392                })?
3393                .to_string();
3394            let family = map.get("family").and_then(|v| v.as_str()).map(String::from);
3395            let unit = map.get("unit").and_then(|v| v.as_str()).map(String::from);
3396            let format = map.get("format").and_then(|v| v.as_str()).map(String::from);
3397            // Validate format syntax at parse time so the user
3398            // hears about a bad `#.##` pattern at workload
3399            // load, not first-cycle. SRD-40b §1.
3400            if let Some(f) = format.as_deref() {
3401                crate::metric_format::parse_format_spec(f)
3402                    .map_err(|e| format!("metric '{key}' format '{f}': {e}"))?;
3403            }
3404            let kind = match map.get("kind") {
3405                None => None,
3406                Some(JVal::String(s)) => Some(parse_metric_kind(s, key)?),
3407                Some(other) => {
3408                    return Err(format!(
3409                        "metric '{key}' kind: expected string, got {other:?}"
3410                    ));
3411                }
3412            };
3413            let cell =
3414                parse_cell_map(map.get("cell")).map_err(|e| format!("metric '{key}' {e}"))?;
3415            Ok(MetricSpec {
3416                value,
3417                family,
3418                kind,
3419                unit,
3420                format,
3421                cell,
3422            })
3423        }
3424        _ => Err(format!(
3425            "metric '{key}': expected string or mapping, got {v:?}"
3426        )),
3427    }
3428}
3429
3430fn parse_metric_kind(s: &str, key: &str) -> Result<crate::model::MetricKind, String> {
3431    use crate::model::MetricKind;
3432    match s.to_ascii_lowercase().as_str() {
3433        "gauge" => Ok(MetricKind::Gauge),
3434        "histogram" => Ok(MetricKind::Histogram),
3435        "counter" => Ok(MetricKind::Counter),
3436        other => Err(format!(
3437            "metric '{key}' kind '{other}': expected one of \
3438             gauge / histogram / counter"
3439        )),
3440    }
3441}
3442
3443/// Auto-inject `name := expr` into the op template's
3444/// `bindings:` block (per SRD-40b §2.2). Conflicts with an
3445/// existing declaration of the same name are a strict
3446/// workload parse error per §2.2.
3447fn inject_wire_into_bindings(
3448    bindings: &mut BindingsDef,
3449    name: &str,
3450    expr: &str,
3451    op_name: &str,
3452) -> Result<(), String> {
3453    // Look for an existing same-name declaration to refuse
3454    // shadowing. The check is textual: a line beginning with
3455    // `<name>` followed by whitespace + `:=`. Prefix matching
3456    // would surface false positives for `foo` vs `foobar`,
3457    // hence the boundary check.
3458    let line_to_inject = format!("{name} := {expr}\n");
3459    // BindingsDef has no `Empty` variant — `Map(empty)` is the
3460    // default. Detect emptiness via the existing helper, then
3461    // promote to PolydatSource for injection (we're adding a real
3462    // Polydat statement, not a name→expr pair the legacy Map form
3463    // can't carry alone).
3464    if bindings.is_empty() {
3465        *bindings = BindingsDef::PolydatSource(line_to_inject);
3466        return Ok(());
3467    }
3468    match bindings {
3469        BindingsDef::PolydatSource(src) => {
3470            if has_binding_named(src, name) {
3471                return Err(format!(
3472                    "metric wire '{name}' (op '{op_name}') collides \
3473                     with existing `bindings:` declaration of the \
3474                     same name"
3475                ));
3476            }
3477            if !src.ends_with('\n') {
3478                src.push('\n');
3479            }
3480            src.push_str(&line_to_inject);
3481        }
3482        BindingsDef::Map(map) => {
3483            if map.contains_key(name) {
3484                return Err(format!(
3485                    "metric wire '{name}' (op '{op_name}') collides \
3486                     with existing `bindings:` declaration of the \
3487                     same name"
3488                ));
3489            }
3490            map.insert(name.to_string(), expr.to_string());
3491        }
3492    }
3493    Ok(())
3494}
3495
3496/// True when `s` is a valid Polydat identifier: non-empty, first
3497/// char is a letter or underscore, remaining chars are
3498/// alphanumerics or underscore. Used by the mapping-form
3499/// metric auto-inject to confirm the metric key can stand in
3500/// as a binding name.
3501fn is_valid_ident(s: &str) -> bool {
3502    let mut chars = s.chars();
3503    match chars.next() {
3504        Some(c) if c.is_alphabetic() || c == '_' => {}
3505        _ => return false,
3506    }
3507    chars.all(|c| c.is_alphanumeric() || c == '_')
3508}
3509
3510/// True when the Polydat source contains a binding line
3511/// `<name> := …` at the start of any (whitespace-trimmed)
3512/// line. Used by the wire-expression injection to detect
3513/// shadowing without parsing the Polydat grammar.
3514fn has_binding_named(src: &str, name: &str) -> bool {
3515    for raw in src.lines() {
3516        let line = raw.trim_start();
3517        if let Some(rest) = line.strip_prefix(name) {
3518            // Boundary: next char must be whitespace or `:=`.
3519            let rest = rest.trim_start();
3520            if rest.starts_with(":=") {
3521                return true;
3522            }
3523        }
3524    }
3525    false
3526}
3527
3528/// Parse an op's `traverse:` block.
3529///
3530/// Customises the always-installed traversal layer; it does not select it, so
3531/// absence means "defaults", not "no traversal". Unknown keys are rejected
3532/// rather than dropped — a silently ignored `on_missing:` would leave the
3533/// author believing absent captures are being policed when they are not.
3534fn parse_traverse_field(
3535    val: Option<&JVal>,
3536    op_name: &str,
3537) -> Result<Option<crate::model::TraverseSpec>, String> {
3538    use crate::model::{OnMissing, TraverseSpec};
3539    let Some(v) = val else { return Ok(None) };
3540    let JVal::Object(map) = v else {
3541        return Err(format!(
3542            "op '{op_name}' traverse: expected a mapping, got {v:?}"
3543        ));
3544    };
3545    const KNOWN: &[&str] = &["path", "on_missing"];
3546    for k in map.keys() {
3547        if !KNOWN.contains(&k.as_str()) {
3548            return Err(format!(
3549                "op '{op_name}' traverse: unknown field `{k}`. Recognised \
3550                 fields: path, on_missing"
3551            ));
3552        }
3553    }
3554    let path = match map.get("path") {
3555        None => None,
3556        Some(JVal::String(p)) => {
3557            let p = p.trim();
3558            if !p.is_empty() && !p.starts_with('/') {
3559                return Err(format!(
3560                    "op '{op_name}' traverse: path '{p}' must start with '/' \
3561                     (RFC 6901 JSON-Pointer); an empty path addresses the root"
3562                ));
3563            }
3564            Some(p.to_string())
3565        }
3566        Some(other) => {
3567            return Err(format!(
3568                "op '{op_name}' traverse: path expected a string, got {other:?}"
3569            ));
3570        }
3571    };
3572    let on_missing = match map.get("on_missing") {
3573        None => OnMissing::default(),
3574        Some(JVal::String(s)) => match s.trim().to_ascii_lowercase().as_str() {
3575            "ignore" => OnMissing::Ignore,
3576            "warn" => OnMissing::Warn,
3577            "error" | "fail" => OnMissing::Error,
3578            other => {
3579                return Err(format!(
3580                    "op '{op_name}' traverse: on_missing '{other}': expected one of \
3581                 ignore / warn / error"
3582                ));
3583            }
3584        },
3585        Some(other) => {
3586            return Err(format!(
3587                "op '{op_name}' traverse: on_missing expected a string, got {other:?}"
3588            ));
3589        }
3590    };
3591    Ok(Some(TraverseSpec { path, on_missing }))
3592}
3593
3594/// SRD-66 §"Surface 1 §Schema": parse the vari-structured
3595/// `result:` field on an op template. Three shapes:
3596///
3597/// - **String** scalar — Polydat source block (multi-line or
3598///   single-line). Each `<name> := <expr>` declares one
3599///   wire.
3600/// - **List** sequence — each element is itself a
3601///   `ResultSpec` (recursively); fragments concatenate.
3602/// - **Mapping** — named-key short-forms; each value is a
3603///   string parsed as `count` / `ok` / path-expr / Polydat expr.
3604fn parse_result_field(
3605    val: Option<&JVal>,
3606    op_name: &str,
3607) -> Result<Option<crate::model::ResultSpec>, String> {
3608    let Some(v) = val else {
3609        return Ok(None);
3610    };
3611    let spec = parse_result_spec(v, op_name)?;
3612    if spec.is_empty() {
3613        Ok(None)
3614    } else {
3615        Ok(Some(spec))
3616    }
3617}
3618
3619fn parse_result_spec(v: &JVal, op_name: &str) -> Result<crate::model::ResultSpec, String> {
3620    use crate::model::ResultSpec;
3621    match v {
3622        JVal::Null => Ok(ResultSpec::String(String::new())),
3623        JVal::String(s) => Ok(ResultSpec::String(s.clone())),
3624        JVal::Array(items) => {
3625            let mut out: Vec<ResultSpec> = Vec::with_capacity(items.len());
3626            for item in items {
3627                out.push(parse_result_spec(item, op_name)?);
3628            }
3629            Ok(ResultSpec::List(out))
3630        }
3631        JVal::Object(map) => {
3632            let mut out: std::collections::BTreeMap<String, String> =
3633                std::collections::BTreeMap::new();
3634            for (key, val) in map {
3635                let source = match val {
3636                    JVal::String(s) => s.clone(),
3637                    JVal::Null => String::new(),
3638                    other => {
3639                        return Err(format!(
3640                            "op '{op_name}' result.{key}: expected string \
3641                         (short-form keyword `count`/`ok`, path \
3642                         expression, or Polydat expression); got {other}"
3643                        ));
3644                    }
3645                };
3646                if out.insert(key.clone(), source).is_some() {
3647                    return Err(format!("op '{op_name}' result: duplicate key '{key}'"));
3648                }
3649            }
3650            Ok(ResultSpec::Map(out))
3651        }
3652        _ => Err(format!(
3653            "op '{op_name}' result: expected string (GK source), \
3654             list (sequence of fragments), or mapping (named \
3655             short-forms); got {v}"
3656        )),
3657    }
3658}
3659
3660// -----------------------------------------------------------------
3661// Helpers
3662// -----------------------------------------------------------------
3663
3664/// Extract bindings from a YAML value.
3665///
3666/// If the value is a string, it's native Polydat grammar source.
3667/// If it's a mapping, it's legacy name→expression pairs.
3668fn extract_bindings(val: Option<&JVal>) -> BindingsDef {
3669    match val {
3670        Some(JVal::String(s)) => BindingsDef::PolydatSource(s.clone()),
3671        Some(JVal::Object(obj)) => {
3672            let mut map = HashMap::new();
3673            for (k, v) in obj {
3674                if let Some(s) = v.as_str() {
3675                    map.insert(k.clone(), s.to_string());
3676                } else {
3677                    map.insert(k.clone(), v.to_string());
3678                }
3679            }
3680            BindingsDef::Map(map)
3681        }
3682        _ => BindingsDef::default(),
3683    }
3684}
3685
3686/// SRD-13f Push D: inline a block's YAML-level `bindings:`
3687/// sugar into one of its enclosed ops.
3688///
3689/// Blocks are not a Polydat scope — they're YAML authoring sugar
3690/// (named groups for tag-filtering + shared defaults). A
3691/// block-level `bindings:` field is *syntactic sugar* meaning
3692/// "every op underneath has these bindings as part of its own
3693/// op-level bindings." This helper does that expansion at
3694/// parse time.
3695///
3696/// Semantics (preserves prior `merge_bindings` shape for the
3697/// only call site that still uses it):
3698/// - The op's own PolydatSource fully shadows the block's sugar
3699///   (the op declares its full binding set explicitly).
3700/// - Op Map merges with block Map (op keys override block).
3701/// - Empty op inherits the block sugar verbatim.
3702///
3703/// No cross-scope semantics: workload-level and phase-level
3704/// `bindings:` no longer flow through this helper. They reach
3705/// ops via the Polydat Kernel chain.
3706fn inline_block_sugar_into_op(block_sugar: &BindingsDef, op_own: &BindingsDef) -> BindingsDef {
3707    match (block_sugar, op_own) {
3708        (_, BindingsDef::PolydatSource(s)) if !s.trim().is_empty() => {
3709            BindingsDef::PolydatSource(s.clone())
3710        }
3711        (BindingsDef::Map(p), BindingsDef::Map(c)) => {
3712            let mut merged = p.clone();
3713            for (k, v) in c {
3714                merged.insert(k.clone(), v.clone());
3715            }
3716            BindingsDef::Map(merged)
3717        }
3718        (_, BindingsDef::Map(c)) if c.is_empty() => block_sugar.clone(),
3719        (_, child) => child.clone(),
3720    }
3721}
3722
3723/// Render a YAML/JSON param value as the text form
3724/// `add_param_binding` expects.
3725///
3726/// Scalar shapes pass through RAW (no extra quoting): a YAML
3727/// `iter_count: "3"` and a YAML `iter_count: 3` BOTH come out as
3728/// the string `"3"` here — the downstream classifier sees
3729/// numeric-shape and emits a bare U64 binding either way. YAML's
3730/// quotes are presentation, not semantic, for scalars.
3731///
3732/// Array shape gets the polydat array literal form
3733/// (`[v1, v2, v3]`) — that's the new convention the workload
3734/// surface needs to support. Array ELEMENTS are formatted with
3735/// polydat literal grammar (strings explicitly quoted) since
3736/// polydat's parser requires quotes inside array literals;
3737/// `format_jval_in_array_context` handles the recursion.
3738///
3739/// Object shape (rare for params) falls back to JSON
3740/// serialization — there's no polydat literal form for objects,
3741/// so the value passes through whatever-it-is for callers
3742/// downstream to handle.
3743pub(crate) fn format_jval_as_polydat_literal(v: &JVal) -> String {
3744    match v {
3745        JVal::Null => String::new(),
3746        JVal::Bool(b) => b.to_string(),
3747        JVal::Number(n) => n.to_string(),
3748        // Scalar strings pass through unquoted to preserve the
3749        // legacy "YAML quotes are presentation" behavior. The
3750        // downstream classifier (`add_param_binding`) figures
3751        // out the actual type from the content — numeric-shape
3752        // becomes U64/F64, identifier-shape becomes a reference,
3753        // string-shape becomes a polydat-quoted Str.
3754        JVal::String(s) => s.clone(),
3755        JVal::Array(items) => {
3756            let elts: Vec<String> = items.iter().map(format_jval_in_array_context).collect();
3757            format!("[{}]", elts.join(", "))
3758        }
3759        JVal::Object(_) => v.to_string(),
3760    }
3761}
3762
3763/// Element-context formatter: polydat array literals require
3764/// explicit quotes around string elements (`["a", "b"]`), unlike
3765/// the scalar-context formatter which leaves strings unquoted.
3766fn format_jval_in_array_context(v: &JVal) -> String {
3767    match v {
3768        JVal::String(s) => {
3769            let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
3770            format!("\"{escaped}\"")
3771        }
3772        JVal::Array(items) => {
3773            let elts: Vec<String> = items.iter().map(format_jval_in_array_context).collect();
3774            format!("[{}]", elts.join(", "))
3775        }
3776        _ => format_jval_as_polydat_literal(v),
3777    }
3778}
3779
3780fn extract_string_map(val: Option<&JVal>) -> HashMap<String, String> {
3781    let mut map = HashMap::new();
3782    if let Some(JVal::Object(obj)) = val {
3783        for (k, v) in obj {
3784            // Format every YAML value as polydat-native source.
3785            // Strings come out quote-wrapped, arrays as
3786            // `[a, b, c]`, numbers / bools bare. The downstream
3787            // `add_param_binding` classifier reads this and emits
3788            // the const binding without re-quoting.
3789            map.insert(k.clone(), format_jval_as_polydat_literal(v));
3790        }
3791    }
3792    map
3793}
3794
3795// Shared classifier helpers — the `set:` block parser routes
3796// every value through the same shape detection so the numeric /
3797// array-literal / quoted-string surface is consistent.
3798
3799fn is_polydat_quoted_string(s: &str) -> bool {
3800    if s.len() < 2 {
3801        return false;
3802    }
3803    if !s.starts_with('"') || !s.ends_with('"') {
3804        return false;
3805    }
3806    let bytes = s.as_bytes();
3807    let mut i = 1;
3808    let last = bytes.len() - 1;
3809    while i < last {
3810        if bytes[i] == b'\\' {
3811            i += 2;
3812            continue;
3813        }
3814        if bytes[i] == b'"' {
3815            return false;
3816        }
3817        i += 1;
3818    }
3819    true
3820}
3821
3822fn extract_value_map(val: Option<&JVal>) -> HashMap<String, JVal> {
3823    let mut map = HashMap::new();
3824    if let Some(JVal::Object(obj)) = val {
3825        for (k, v) in obj {
3826            map.insert(k.clone(), v.clone());
3827        }
3828    }
3829    map
3830}
3831
3832fn merge_string_maps(
3833    parent: &HashMap<String, String>,
3834    child: &HashMap<String, String>,
3835) -> HashMap<String, String> {
3836    let mut merged = parent.clone();
3837    for (k, v) in child {
3838        merged.insert(k.clone(), v.clone());
3839    }
3840    merged
3841}
3842
3843/// Activity/phase-scope param keys that must never be blast-merged onto ops.
3844/// They are consumed at phase/activity scope; leaking them into op `params`
3845/// makes an inherited `rate` collide with the `rate` wrapper's
3846/// field-ownership guard (SRD-32a). The op-level `rate:` field reaches ops via
3847/// the typed [`ParsedOp::rate`] path, not params, so this exclusion is safe.
3848const ACTIVITY_PARAM_KEYS: &[&str] = &["cycles", "concurrency", "rate", "errors", "error_rate_max"];
3849
3850/// The workload `params:` keys that select its DEFAULT adapter. An op never
3851/// inherits them: an op's `params.adapter` is an op-level override, which
3852/// outranks the phase's `adapter:`, so an inherited copy would outrank it
3853/// too and a phase could never override the workload default. An op's own
3854/// `adapter:` is written on the op and is untouched; a CLI `adapter=` still
3855/// overlays every op (SRD 21, the outermost layer).
3856const ADAPTER_SELECTOR_KEYS: &[&str] = &["adapter", "driver"];
3857
3858/// Clone `params` minus the keys an op never inherits from an enclosing
3859/// `params:` block ([`ACTIVITY_PARAM_KEYS`], [`ADAPTER_SELECTOR_KEYS`]).
3860fn exclude_non_op_keys(params: &HashMap<String, JVal>) -> HashMap<String, JVal> {
3861    params
3862        .iter()
3863        .filter(|(k, _)| {
3864            !ACTIVITY_PARAM_KEYS.contains(&k.as_str())
3865                && !ADAPTER_SELECTOR_KEYS.contains(&k.as_str())
3866        })
3867        .map(|(k, v)| (k.clone(), v.clone()))
3868        .collect()
3869}
3870
3871fn merge_value_maps(
3872    parent: &HashMap<String, JVal>,
3873    child: &HashMap<String, JVal>,
3874) -> HashMap<String, JVal> {
3875    let mut merged = parent.clone();
3876    for (k, v) in child {
3877        merged.insert(k.clone(), v.clone());
3878    }
3879    merged
3880}
3881
3882#[cfg(test)]
3883mod tests {
3884    use super::*;
3885
3886    /// A malformed bind point is refused when the workload is
3887    /// parsed, naming the op and the field or param that holds it.
3888    #[test]
3889    fn a_malformed_bind_point_is_refused_naming_its_op_and_field() {
3890        let yaml = |op_body: &str| {
3891            format!(
3892                "phases:\n  load:\n    ops:\n      write: {op_body}\nscenarios: {{ default: [load] }}\n"
3893            )
3894        };
3895        let err = parse_workload(
3896            &yaml(r#"{ stmt: "INSERT INTO t (id) VALUES ({id:String})" }"#),
3897            &HashMap::new(),
3898        )
3899        .expect_err("a retired type spelling on a bind point must be refused");
3900        assert_eq!(
3901            err.matches("op 'write' field 'stmt': bind point `{id:String}`: `String` is no longer a type keyword; write `str`").count(),
3902            1,
3903            "{err}"
3904        );
3905        let err = parse_workload(
3906            &yaml(r#"{ stmt: "op", params: { label: "{h:handle}" } }"#),
3907            &HashMap::new(),
3908        )
3909        .expect_err("an internal type on a bind point must be refused");
3910        assert!(
3911            err.contains(
3912                "op 'write' param 'label': bind point `{h:handle}`: `handle` is an internal type"
3913            ),
3914            "{err}"
3915        );
3916        parse_workload(
3917            &yaml(r#"{ stmt: "INSERT INTO t (id) VALUES ({id:str})" }"#),
3918            &HashMap::new(),
3919        )
3920        .expect("a type keyword on a bind point parses");
3921    }
3922
3923    #[test]
3924    fn phase_metrics_mapping_form_preserves_raw_value() {
3925        // Phase-level `metrics:` keeps the raw `value:` expression
3926        // (no bare-key injection into bindings — the phase synthesiser
3927        // emits `volatile __metric_<name> := <value>` directly).
3928        let yaml = r#"
3929phases:
3930  build_index:
3931    metrics:
3932      time_to_index: { value: "current_epoch_millis() - phase_start", kind: gauge }
3933    ops:
3934      work: { stmt: "op" }
3935scenarios:
3936  default: [build_index]
3937"#;
3938        let wl = parse_workload(yaml, &HashMap::new()).expect("parse");
3939        let phase = wl.phases.get("build_index").expect("phase build_index");
3940        let m = phase
3941            .metrics
3942            .get("time_to_index")
3943            .expect("time_to_index metric");
3944        assert_eq!(
3945            m.value, "current_epoch_millis() - phase_start",
3946            "raw value must be preserved verbatim"
3947        );
3948        assert_eq!(m.kind, Some(crate::model::MetricKind::Gauge));
3949        assert!(
3950            phase.bindings.is_empty(),
3951            "phase metrics must NOT auto-inject into bindings: {:?}",
3952            phase.bindings
3953        );
3954    }
3955
3956    #[test]
3957    fn tries_accepts_sugared_number_and_map_form() {
3958        // Sugared: a bare number sets the count, no backoff overrides.
3959        let sugar = r#"
3960phases:
3961  load:
3962    tries: 20
3963    ops: { work: { stmt: "op" } }
3964scenarios: { default: [load] }
3965"#;
3966        let wl = parse_workload(sugar, &HashMap::new()).expect("parse sugar");
3967        let p = wl.phases.get("load").unwrap();
3968        assert_eq!(p.tries, Some(20));
3969        assert_eq!(p.tries_backoff, None);
3970
3971        // Map form: `count` + nested `backoff` (durations kept as strings).
3972        let map = r#"
3973phases:
3974  load:
3975    tries:
3976      count: 20
3977      backoff:
3978        ratio: 2.0
3979        min: 100ms
3980        max: 10s
3981    ops: { work: { stmt: "op" } }
3982scenarios: { default: [load] }
3983"#;
3984        let wl = parse_workload(map, &HashMap::new()).expect("parse map");
3985        let p = wl.phases.get("load").unwrap();
3986        assert_eq!(p.tries, Some(20));
3987        let bo = p.tries_backoff.as_ref().expect("backoff parsed");
3988        assert_eq!(bo.ratio, Some(2.0));
3989        assert_eq!(bo.min.as_deref(), Some("100ms"));
3990        assert_eq!(bo.max.as_deref(), Some("10s"));
3991
3992        // A bad shape (string) is a loud parse error, not a silent drop.
3993        let bad = r#"
3994phases: { load: { tries: "lots", ops: { w: { stmt: "op" } } } }
3995scenarios: { default: [load] }
3996"#;
3997        assert!(
3998            parse_workload(bad, &HashMap::new()).is_err(),
3999            "non-number, non-map tries must fail to parse"
4000        );
4001    }
4002
4003    #[test]
4004    fn metric_spec_rejects_unknown_field_type_with_hint() {
4005        // `type:` is the OpenMetrics word; ours is `kind`. Reject it
4006        // loudly with a hint rather than silently dropping it (which
4007        // would default the metric to gauge).
4008        let yaml = r#"
4009phases:
4010  p:
4011    metrics:
4012      m: { type: counter, value: "x" }
4013    ops:
4014      work: { stmt: "op" }
4015scenarios:
4016  default: [p]
4017"#;
4018        let err = parse_workload(yaml, &HashMap::new())
4019            .expect_err("unknown metric field `type` must be rejected");
4020        assert!(
4021            err.contains("unknown field `type`"),
4022            "must name the offending field; got: {err}"
4023        );
4024        assert!(
4025            err.contains("kind"),
4026            "must hint at the canonical `kind` field; got: {err}"
4027        );
4028    }
4029
4030    #[test]
4031    fn metric_spec_rejects_arbitrary_unknown_field() {
4032        let yaml = r#"
4033phases:
4034  p:
4035    metrics:
4036      m: { value: "x", flavour: gauge }
4037    ops:
4038      work: { stmt: "op" }
4039scenarios:
4040  default: [p]
4041"#;
4042        let err = parse_workload(yaml, &HashMap::new())
4043            .expect_err("arbitrary unknown metric field must be rejected");
4044        assert!(
4045            err.contains("unknown field `flavour`"),
4046            "must name the offending field; got: {err}"
4047        );
4048    }
4049
4050    #[test]
4051    fn metric_spec_accepts_all_known_fields() {
4052        // Regression guard: the unknown-field check must not reject any
4053        // legitimate field.
4054        let yaml = r#"
4055phases:
4056  p:
4057    metrics:
4058      m: { value: "x", family: fam, kind: counter, unit: bytes, format: "0.00" }
4059    ops:
4060      work: { stmt: "op" }
4061scenarios:
4062  default: [p]
4063"#;
4064        let wl = parse_workload(yaml, &HashMap::new()).expect("all known fields accepted");
4065        let m = wl.phases.get("p").unwrap().metrics.get("m").unwrap();
4066        assert_eq!(m.kind, Some(crate::model::MetricKind::Counter));
4067        assert_eq!(m.unit.as_deref(), Some("bytes"));
4068        assert_eq!(m.family.as_deref(), Some("fam"));
4069    }
4070
4071    #[test]
4072    fn phase_metrics_list_form_rejects_wire_expression() {
4073        // The `name := expr` list form is op-only; for a phase the
4074        // author must use the phase `bindings:` block + a bare name,
4075        // or the mapping form. Reject loudly rather than silently.
4076        let yaml = r#"
4077phases:
4078  p:
4079    metrics:
4080      - "te := current_epoch_millis() - phase_start"
4081    ops:
4082      work: { stmt: "op" }
4083scenarios:
4084  default: [p]
4085"#;
4086        let err = parse_workload(yaml, &HashMap::new())
4087            .expect_err("list `name := expr` form must be rejected for phases");
4088        assert!(
4089            err.contains("op-only") || err.contains("mapping form"),
4090            "diagnostic should point at the op-only form; got: {err}"
4091        );
4092    }
4093
4094    #[test]
4095    fn readouts_block_form_a_scalar_binds_on_update() {
4096        let workload: serde_yaml::Value =
4097            serde_yaml::from_str(r#"readouts: phase_status"#).unwrap();
4098        let json = serde_json::to_value(&workload).unwrap();
4099        let r = parse_readouts_block(json.get("readouts")).unwrap();
4100        assert_eq!(r.on_update, vec!["phase_status".to_string()]);
4101        assert!(r.on_phase_end.is_empty());
4102    }
4103
4104    #[test]
4105    fn readouts_block_form_b_mapping_binds_explicit_slots() {
4106        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
4107            r#"
4108readouts:
4109  on_phase_end: phase_outcome
4110  on_update: "phase_status lod=compact"
4111"#,
4112        )
4113        .unwrap();
4114        let json = serde_json::to_value(&yaml).unwrap();
4115        let r = parse_readouts_block(json.get("readouts")).unwrap();
4116        assert_eq!(r.on_phase_end, vec!["phase_outcome".to_string()]);
4117        assert_eq!(r.on_update, vec!["phase_status lod=compact".to_string()]);
4118    }
4119
4120    #[test]
4121    fn readouts_block_form_c_list_composes() {
4122        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
4123            r#"
4124readouts:
4125  on_phase_end:
4126    - phase_outcome
4127    - phase_failure_hint
4128"#,
4129        )
4130        .unwrap();
4131        let json = serde_json::to_value(&yaml).unwrap();
4132        let r = parse_readouts_block(json.get("readouts")).unwrap();
4133        assert_eq!(
4134            r.on_phase_end,
4135            vec![
4136                "phase_outcome".to_string(),
4137                "phase_failure_hint".to_string(),
4138            ]
4139        );
4140    }
4141
4142    #[test]
4143    fn readouts_block_each_wildcard_expands() {
4144        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
4145            r#"
4146readouts:
4147  each_*: scope_bracket
4148"#,
4149        )
4150        .unwrap();
4151        let json = serde_json::to_value(&yaml).unwrap();
4152        let r = parse_readouts_block(json.get("readouts")).unwrap();
4153        assert_eq!(r.on_each_start, vec!["scope_bracket".to_string()]);
4154        assert_eq!(r.on_each_end, vec!["scope_bracket".to_string()]);
4155        // Other slots untouched.
4156        assert!(r.on_phase_end.is_empty());
4157        assert!(r.on_update.is_empty());
4158    }
4159
4160    #[test]
4161    fn readouts_block_phase_wildcard_expands() {
4162        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
4163            r#"
4164readouts:
4165  phase_*: trace
4166"#,
4167        )
4168        .unwrap();
4169        let json = serde_json::to_value(&yaml).unwrap();
4170        let r = parse_readouts_block(json.get("readouts")).unwrap();
4171        assert_eq!(r.on_phase_start, vec!["trace".to_string()]);
4172        assert_eq!(r.on_phase_end, vec!["trace".to_string()]);
4173        assert!(r.on_each_start.is_empty());
4174    }
4175
4176    #[test]
4177    fn readouts_block_universal_wildcard_expands_to_all() {
4178        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
4179            r#"
4180readouts:
4181  "*": trace
4182"#,
4183        )
4184        .unwrap();
4185        let json = serde_json::to_value(&yaml).unwrap();
4186        let r = parse_readouts_block(json.get("readouts")).unwrap();
4187        for slot in [
4188            &r.on_session_start,
4189            &r.on_session_end,
4190            &r.on_phase_start,
4191            &r.on_phase_end,
4192            &r.on_each_start,
4193            &r.on_each_end,
4194            &r.on_scope_start,
4195            &r.on_scope_end,
4196            &r.on_update,
4197        ] {
4198            assert_eq!(slot, &vec!["trace".to_string()]);
4199        }
4200    }
4201
4202    #[test]
4203    fn readouts_block_unknown_slot_is_error() {
4204        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
4205            r#"
4206readouts:
4207  on_unknown: phase_outcome
4208"#,
4209        )
4210        .unwrap();
4211        let json = serde_json::to_value(&yaml).unwrap();
4212        let err = parse_readouts_block(json.get("readouts")).unwrap_err();
4213        assert!(
4214            err.contains("unknown slot 'on_unknown'"),
4215            "wrong message: {err}"
4216        );
4217    }
4218
4219    #[test]
4220    fn parse_single_string_op() {
4221        let ops = parse_ops("op: select * from bar.table;").unwrap();
4222        assert_eq!(ops.len(), 1);
4223        assert_eq!(ops[0].name, "stmt1");
4224        assert_eq!(ops[0].op["stmt"], "select * from bar.table;");
4225    }
4226
4227    #[test]
4228    fn parse_ops_list_of_strings() {
4229        let yaml = r#"
4230ops:
4231  - select * from t1;
4232  - select * from t2;
4233"#;
4234        let ops = parse_ops(yaml).unwrap();
4235        assert_eq!(ops.len(), 2);
4236        assert_eq!(ops[0].op["stmt"], "select * from t1;");
4237        assert_eq!(ops[1].op["stmt"], "select * from t2;");
4238    }
4239
4240    #[test]
4241    fn parse_ops_map_of_strings() {
4242        let yaml = r#"
4243ops:
4244  read: select * from t1;
4245  write: insert into t1 values (1);
4246"#;
4247        let ops = parse_ops(yaml).unwrap();
4248        assert_eq!(ops.len(), 2);
4249        let read = ops.iter().find(|o| o.name == "read").unwrap();
4250        assert_eq!(read.op["stmt"], "select * from t1;");
4251    }
4252
4253    #[test]
4254    fn parse_named_blocks() {
4255        let yaml = r#"
4256blocks:
4257  schema:
4258    ops:
4259      create: "CREATE TABLE t (id int PRIMARY KEY);"
4260  main:
4261    ops:
4262      read: "SELECT * FROM t WHERE id={id};"
4263"#;
4264        let ops = parse_ops(yaml).unwrap();
4265        assert_eq!(ops.len(), 2);
4266        let create = ops.iter().find(|o| o.name == "create").unwrap();
4267        assert_eq!(create.tags["block"], "schema");
4268        let read = ops.iter().find(|o| o.name == "read").unwrap();
4269        assert_eq!(read.tags["block"], "main");
4270    }
4271
4272    #[test]
4273    fn parse_property_inheritance() {
4274        let yaml = r#"
4275bindings:
4276  id: Identity()
4277params:
4278  prepared: true
4279tags:
4280  workload: test
4281blocks:
4282  main:
4283    bindings:
4284      id: Hash()
4285    ops:
4286      op1: "SELECT * FROM t;"
4287"#;
4288        let ops = parse_ops(yaml).unwrap();
4289        assert_eq!(ops.len(), 1);
4290        // Block-level binding overrides doc-level
4291        assert_eq!(ops[0].bindings.as_map()["id"], "Hash()");
4292        // Doc-level param inherited
4293        assert_eq!(ops[0].params["prepared"], true);
4294        // Doc-level tag inherited
4295        assert_eq!(ops[0].tags["workload"], "test");
4296        // Auto-tag
4297        assert_eq!(ops[0].tags["block"], "main");
4298    }
4299
4300    /// The workload's default adapter is not an op-level override: an op
4301    /// inherits no `adapter` from `params:`, so a phase's `adapter:` can
4302    /// replace the default. An op's own `adapter:` stays on the op.
4303    #[test]
4304    fn an_op_does_not_inherit_the_workload_default_adapter() {
4305        let yaml = r#"
4306params:
4307  adapter: cql
4308  prepared: true
4309blocks:
4310  main:
4311    ops:
4312      plain: "SELECT * FROM t;"
4313      routed:
4314        adapter: stdout
4315        stmt: "hello"
4316"#;
4317        let ops = parse_ops(yaml).unwrap();
4318        let plain = ops.iter().find(|o| o.name == "plain").unwrap();
4319        let routed = ops.iter().find(|o| o.name == "routed").unwrap();
4320        assert!(!plain.params.contains_key("adapter"));
4321        assert_eq!(plain.params["prepared"], true);
4322        assert_eq!(routed.params["adapter"], "stdout");
4323    }
4324
4325    #[test]
4326    fn parse_auto_naming() {
4327        let yaml = r#"
4328ops:
4329  - "first op"
4330  - "second op"
4331"#;
4332        let ops = parse_ops(yaml).unwrap();
4333        assert_eq!(ops[0].name, "stmt1");
4334        assert_eq!(ops[1].name, "stmt2");
4335    }
4336
4337    #[test]
4338    fn parse_auto_tagging() {
4339        let yaml = r#"
4340ops:
4341  myop: "SELECT 1;"
4342"#;
4343        let ops = parse_ops(yaml).unwrap();
4344        assert_eq!(ops[0].tags["name"], "myop");
4345        assert_eq!(ops[0].tags["op"], "myop");
4346        assert_eq!(ops[0].tags["block"], "block0");
4347    }
4348
4349    #[test]
4350    fn condition_clause_passthrough_for_identifier() {
4351        // Bare identifier — legacy "name a binding" form.
4352        assert_eq!(normalize_condition_clause("my_flag"), "my_flag");
4353        assert_eq!(normalize_condition_clause(" my_flag "), "my_flag");
4354    }
4355
4356    #[test]
4357    fn condition_clause_passthrough_for_braced_forms() {
4358        assert_eq!(normalize_condition_clause("{my_flag}"), "{my_flag}");
4359        assert_eq!(normalize_condition_clause("{{x == 1}}"), "{{x == 1}}");
4360        assert_eq!(normalize_condition_clause("{:=x == 1:=}"), "{:=x == 1:=}");
4361    }
4362
4363    #[test]
4364    fn condition_clause_wraps_bare_expressions() {
4365        assert_eq!(
4366            normalize_condition_clause("cql_dialect == 'cass'"),
4367            "{{cql_dialect == 'cass'}}",
4368        );
4369        assert_eq!(
4370            normalize_condition_clause("a > 0 && b < 10"),
4371            "{{a > 0 && b < 10}}",
4372        );
4373        assert_eq!(normalize_condition_clause("foo(bar)"), "{{foo(bar)}}",);
4374    }
4375
4376    #[test]
4377    fn condition_clause_empty_passthrough() {
4378        assert_eq!(normalize_condition_clause(""), "");
4379        assert_eq!(normalize_condition_clause("   "), "");
4380    }
4381
4382    #[test]
4383    fn parse_op_with_fields() {
4384        let yaml = r#"
4385ops:
4386  op1:
4387    field1: value1
4388    field2: value2
4389"#;
4390        let ops = parse_ops(yaml).unwrap();
4391        assert_eq!(ops[0].op["field1"], "value1");
4392        assert_eq!(ops[0].op["field2"], "value2");
4393    }
4394
4395    #[test]
4396    fn parse_explicit_op_field() {
4397        let yaml = r#"
4398ops:
4399  op1:
4400    op:
4401      stmt: "SELECT * FROM t;"
4402      type: query
4403"#;
4404        let ops = parse_ops(yaml).unwrap();
4405        assert_eq!(ops[0].op["stmt"], "SELECT * FROM t;");
4406        assert_eq!(ops[0].op["type"], "query");
4407    }
4408
4409    #[test]
4410    fn parse_scenarios() {
4411        let yaml = r#"
4412scenarios:
4413  default:
4414    schema: run adapter=cql tags==block:schema threads==1
4415    main: run adapter=cql tags==block:main cycles=1M
4416ops:
4417  op1: "test"
4418"#;
4419        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4420        let default = &workload.scenarios["default"];
4421        assert_eq!(default.len(), 2);
4422        // Legacy command-string format: names are preserved as Phase nodes
4423        assert!(matches!(&default[0], ScenarioNode::Phase(n) if n == "schema"));
4424        assert!(matches!(&default[1], ScenarioNode::Phase(n) if n == "main"));
4425    }
4426
4427    #[test]
4428    fn parse_template_expansion() {
4429        let yaml = r#"
4430ops:
4431  op1: "SELECT * FROM t LIMIT TEMPLATE(limit, 100);"
4432"#;
4433        let ops = parse_ops(yaml).unwrap();
4434        assert_eq!(ops[0].op["stmt"], "SELECT * FROM t LIMIT 100;");
4435    }
4436
4437    #[test]
4438    fn parse_description() {
4439        let yaml = r#"
4440description: |
4441  This is a test workload.
4442ops:
4443  op1: "test"
4444"#;
4445        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4446        assert!(workload.description.unwrap().contains("test workload"));
4447    }
4448
4449    // ── Scenario malformed-node rejection (Never Ignore
4450    // Silently). The parser used to silently drop an
4451    // unrecognised scenario-node key like `iterate:` →
4452    // `{phases: [...]}`, leaving the scenario empty and
4453    // surfacing as a confusing downstream "phase not found"
4454    // error. These tests pin the loud-rejection behavior so a
4455    // refactor can't regress the silent-drop. ──
4456
4457    #[test]
4458    fn scenario_node_with_unknown_map_key_collects_parse_error() {
4459        let yaml = r#"
4460scenarios:
4461  bogus:
4462    - iterate:
4463        phases:
4464          - phase_x
4465phases:
4466  phase_x:
4467    ops:
4468      noop: "x"
4469"#;
4470        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4471        assert!(
4472            !workload.scenario_parse_errors.is_empty(),
4473            "malformed `iterate:` node MUST surface a scenario_parse_error \
4474             — silent drop is the safety bug being prevented"
4475        );
4476        let msg = workload.scenario_parse_errors[0].as_str();
4477        assert!(
4478            msg.contains("bogus"),
4479            "error must name the offending scenario: {msg}"
4480        );
4481        assert!(
4482            msg.contains("iterate"),
4483            "error must name the bad key: {msg}"
4484        );
4485        // Bogus scenario must NOT have absorbed phase_x as a Phase
4486        // node via the legacy catch-all.
4487        assert_eq!(
4488            workload.scenarios.get("bogus").map(|v| v.len()),
4489            Some(0),
4490            "malformed node must NOT silently produce ScenarioNode::Phase"
4491        );
4492    }
4493
4494    #[test]
4495    fn scenario_node_with_legacy_command_string_form_still_works() {
4496        // Pre-existing nosqlbench-style scenario shape: each
4497        // map key is a step name, value is a `run ...` CLI
4498        // string. The malformed-rejection refactor MUST NOT
4499        // break this — the discriminator is "map value is
4500        // a string" → legacy, "map value is a map/array" →
4501        // malformed.
4502        let yaml = r#"
4503scenarios:
4504  default:
4505    schema: run tags==block:schema
4506    main: run tags==block:main
4507ops:
4508  op1: "test"
4509"#;
4510        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4511        assert!(
4512            workload.scenario_parse_errors.is_empty(),
4513            "legacy command-string form must NOT be flagged as malformed: {:?}",
4514            workload.scenario_parse_errors
4515        );
4516        let default = &workload.scenarios["default"];
4517        assert_eq!(default.len(), 2);
4518        assert!(matches!(&default[0], ScenarioNode::Phase(n) if n == "schema"));
4519        assert!(matches!(&default[1], ScenarioNode::Phase(n) if n == "main"));
4520    }
4521
4522    #[test]
4523    fn scenario_node_malformed_error_lists_recognised_keys() {
4524        // The error message must point the operator at the
4525        // recognised key vocabulary so they can self-correct
4526        // without grepping the source.
4527        let yaml = r#"
4528scenarios:
4529  s1:
4530    - typoed_for_each:
4531        phases:
4532          - phase_x
4533phases:
4534  phase_x:
4535    ops:
4536      noop: "x"
4537"#;
4538        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4539        assert_eq!(workload.scenario_parse_errors.len(), 1);
4540        let msg = &workload.scenario_parse_errors[0];
4541        // Must mention at least the load-bearing alternatives.
4542        for expected in ["for_each", "scenarios", "do_while", "bindings"] {
4543            assert!(
4544                msg.contains(expected),
4545                "error message must mention `{expected}` as a valid \
4546                 alternative; got: {msg}"
4547            );
4548        }
4549    }
4550
4551    #[test]
4552    fn parse_polydat_source_bindings() {
4553        // SRD-13f Push D: workload-level `bindings:` live on
4554        // `Workload.bindings` and reach ops via the Polydat Kernel
4555        // chain at runtime — they are NOT folded into per-op
4556        // bindings at parse time.
4557        let yaml = r#"
4558bindings: |
4559  // Explicit wiring — every intermediate is named
4560  input cycle: u64
4561  h := hash(cycle)
4562  user_id := mod(h, 1000000)
4563  code_hash := hash(user_id)
4564  code := combinations(code_hash, '0-9A-Z')
4565
4566  // Equivalent concise form (nested composition):
4567  // user_id := mod(hash(cycle), 1000000)
4568  // code := combinations(hash(user_id), '0-9A-Z')
4569ops:
4570  insert: "INSERT INTO users (id, code) VALUES ({user_id}, '{code}');"
4571"#;
4572        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4573        match &workload.bindings {
4574            BindingsDef::PolydatSource(src) => {
4575                assert!(src.contains("input cycle: u64"));
4576                assert!(src.contains("user_id := mod(h, 1000000)"));
4577            }
4578            BindingsDef::Map(_) => panic!("expected PolydatSource at workload level, got Map"),
4579        }
4580        assert_eq!(workload.ops.len(), 1);
4581        // Op carries no workload bindings — they reach it via
4582        // the Polydat Kernel chain, not via parse-time merge.
4583        assert!(workload.ops[0].bindings.is_empty());
4584    }
4585
4586    #[test]
4587    fn parse_map_bindings_still_works() {
4588        // SRD-13f Push D: Map-form workload bindings live on
4589        // `Workload.bindings`, not on per-op bindings.
4590        let yaml = r#"
4591bindings:
4592  id: "Hash(); Mod(100)"
4593ops:
4594  op1: "SELECT * FROM t WHERE id={id};"
4595"#;
4596        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4597        assert_eq!(workload.bindings.as_map()["id"], "Hash(); Mod(100)");
4598        // The op itself carries no merged-in workload bindings.
4599        assert!(workload.ops[0].bindings.is_empty());
4600    }
4601
4602    #[test]
4603    fn parse_phased_workload() {
4604        let yaml = r#"
4605scenarios:
4606  default:
4607    - schema
4608    - main
4609
4610phases:
4611  schema:
4612    cycles: 1
4613    concurrency: 1
4614    ops:
4615      create_table:
4616        stmt: "CREATE TABLE t (id int PRIMARY KEY);"
4617  main:
4618    cycles: 1000
4619    concurrency: 10
4620    rate: 500.0
4621    ops:
4622      read:
4623        stmt: "SELECT * FROM t WHERE id={id};"
4624      write:
4625        stmt: "INSERT INTO t (id) VALUES ({id});"
4626"#;
4627        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4628
4629        // Phases parsed
4630        assert_eq!(workload.phases.len(), 2);
4631        assert!(workload.phases.contains_key("schema"));
4632        assert!(workload.phases.contains_key("main"));
4633
4634        // Phase order preserved
4635        assert_eq!(workload.phase_order, vec!["schema", "main"]);
4636
4637        // Schema phase config
4638        let schema = &workload.phases["schema"];
4639        assert_eq!(schema.cycles.as_deref(), Some("1"));
4640        assert_eq!(schema.concurrency.as_deref(), Some("1"));
4641        assert_eq!(schema.rate, None);
4642        assert_eq!(schema.ops.len(), 1);
4643        assert_eq!(schema.ops[0].name, "create_table");
4644
4645        // Main phase config
4646        let main = &workload.phases["main"];
4647        assert_eq!(main.cycles.as_deref(), Some("1000"));
4648        assert_eq!(main.concurrency.as_deref(), Some("10"));
4649        assert_eq!(main.rate.as_deref(), Some("500.0"));
4650        assert_eq!(main.ops.len(), 2);
4651
4652        // Scenario parsed as phase name list
4653        let default = &workload.scenarios["default"];
4654        assert_eq!(default.len(), 2);
4655        assert!(matches!(&default[0], ScenarioNode::Phase(n) if n == "schema"));
4656        assert!(matches!(&default[1], ScenarioNode::Phase(n) if n == "main"));
4657    }
4658
4659    #[test]
4660    fn parse_phased_workload_with_tags() {
4661        let yaml = r#"
4662blocks:
4663  schema:
4664    ops:
4665      create: "CREATE TABLE t (id int PRIMARY KEY);"
4666  main:
4667    ops:
4668      read: "SELECT * FROM t;"
4669
4670phases:
4671  setup:
4672    tags: "block:schema"
4673    cycles: 1
4674  run:
4675    tags: "block:main"
4676    cycles: 1000
4677"#;
4678        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4679        assert_eq!(workload.phases.len(), 2);
4680
4681        // SRD-108 Part A: the selector resolves at parse time —
4682        // the phase carries the selected block ops as if inline.
4683        let setup = &workload.phases["setup"];
4684        assert_eq!(setup.tags.as_deref(), Some("block:schema"));
4685        assert_eq!(setup.ops.len(), 1);
4686        assert_eq!(setup.ops[0].name, "create");
4687        assert_eq!(
4688            setup.ops[0].tags.get("phase").map(String::as_str),
4689            Some("setup")
4690        );
4691
4692        let run = &workload.phases["run"];
4693        assert_eq!(run.tags.as_deref(), Some("block:main"));
4694        assert_eq!(run.ops.len(), 1);
4695        assert_eq!(run.ops[0].name, "read");
4696    }
4697
4698    /// SRD-108 Part A — a selector matching nothing is a load
4699    /// error naming the phase, never a dispatch-time panic.
4700    #[test]
4701    fn phase_tag_selector_matching_nothing_is_a_load_error() {
4702        let yaml = r#"
4703blocks:
4704  schema:
4705    ops:
4706      create: "CREATE TABLE t (id int PRIMARY KEY);"
4707phases:
4708  setup:
4709    tags: "block:nonexistent"
4710    cycles: 1
4711"#;
4712        let err = parse_workload(yaml, &HashMap::new()).unwrap_err();
4713        assert!(
4714            err.contains("setup") && err.contains("matched no ops"),
4715            "error must name the phase and the failure: {err}"
4716        );
4717    }
4718
4719    /// SRD-108 Part A — inline ops and a selector together are
4720    /// rejected: one source of ops per phase.
4721    #[test]
4722    fn phase_with_inline_ops_and_selector_is_rejected() {
4723        let yaml = r#"
4724blocks:
4725  schema:
4726    ops:
4727      create: "CREATE TABLE t (id int PRIMARY KEY);"
4728phases:
4729  setup:
4730    tags: "block:schema"
4731    cycles: 1
4732    ops:
4733      also: "SELECT 1;"
4734"#;
4735        let err = parse_workload(yaml, &HashMap::new()).unwrap_err();
4736        assert!(
4737            err.contains("both inline ops and a"),
4738            "error must explain the conflict: {err}"
4739        );
4740    }
4741
4742    #[test]
4743    fn parse_phased_workload_polydat_cycles() {
4744        let yaml = r#"
4745phases:
4746  rampup:
4747    cycles: "{train_count}"
4748    concurrency: 100
4749    ops:
4750      insert:
4751        stmt: "INSERT INTO t (id) VALUES ({id});"
4752"#;
4753        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4754        let rampup = &workload.phases["rampup"];
4755        assert_eq!(rampup.cycles.as_deref(), Some("{train_count}"));
4756    }
4757
4758    // ── SRD-40b §1 + §2: `metrics:` discriminant on op template ──
4759
4760    #[test]
4761    fn parse_metrics_full_mapping_form() {
4762        let yaml = r##"
4763phases:
4764  predict:
4765    bindings: |
4766      example_factor := 1.0 + 2.5
4767    ops:
4768      synth:
4769        stmt: "noop"
4770        metrics:
4771          example_factor:
4772            value: example_factor
4773            kind: gauge
4774            unit: ratio
4775            format: "#.##"
4776"##;
4777        let wl = parse_workload(yaml, &HashMap::new()).unwrap();
4778        let op = &wl.phases["predict"].ops[0];
4779        assert_eq!(op.name, "synth");
4780        let m = &op.metrics["example_factor"];
4781        assert_eq!(m.value, "example_factor");
4782        assert_eq!(m.kind, Some(crate::model::MetricKind::Gauge));
4783        assert_eq!(m.unit.as_deref(), Some("ratio"));
4784        assert_eq!(m.format.as_deref(), Some("#.##"));
4785    }
4786
4787    #[test]
4788    fn parse_metrics_bare_string_sugar() {
4789        let yaml = r#"
4790phases:
4791  p:
4792    bindings: |
4793      overscan := 1.0
4794    ops:
4795      o:
4796        stmt: "noop"
4797        metrics: overscan
4798"#;
4799        let wl = parse_workload(yaml, &HashMap::new()).unwrap();
4800        let op = &wl.phases["p"].ops[0];
4801        let m = &op.metrics["overscan"];
4802        // Bare-string form: family + value both = "overscan"
4803        // (defaults), kind unset (defaults to gauge at runtime).
4804        assert_eq!(m.value, "overscan");
4805        assert_eq!(m.family, None);
4806        assert_eq!(m.kind, None);
4807    }
4808
4809    #[test]
4810    fn parse_metrics_list_with_wire_expression() {
4811        let yaml = r#"
4812phases:
4813  p:
4814    ops:
4815      o:
4816        stmt: "noop"
4817        metrics:
4818          - latency_pred := 0.5 + 1.5 * pow(limit, -0.4)
4819          - already_bound
4820"#;
4821        let wl = parse_workload(yaml, &HashMap::new()).unwrap();
4822        let op = &wl.phases["p"].ops[0];
4823        // Both metric entries registered.
4824        assert!(op.metrics.contains_key("latency_pred"));
4825        assert!(op.metrics.contains_key("already_bound"));
4826        // Wire expression auto-injected into op bindings.
4827        match &op.bindings {
4828            BindingsDef::PolydatSource(src) => {
4829                assert!(
4830                    src.contains("latency_pred := 0.5 + 1.5 * pow(limit, -0.4)"),
4831                    "wire not injected; bindings: {src:?}"
4832                );
4833            }
4834            other => panic!("expected PolydatSource bindings, got {other:?}"),
4835        }
4836    }
4837
4838    #[test]
4839    fn parse_metrics_mapping_form_with_wire_expression() {
4840        let yaml = r#"
4841phases:
4842  p:
4843    bindings: |
4844      base := 10
4845    ops:
4846      o:
4847        stmt: "noop"
4848        metrics:
4849          scaled:
4850            value: base * 2
4851            kind: gauge
4852"#;
4853        let wl = parse_workload(yaml, &HashMap::new()).unwrap();
4854        let op = &wl.phases["p"].ops[0];
4855        let m = &op.metrics["scaled"];
4856        // After auto-inject the spec's `value:` is the bare key.
4857        assert_eq!(m.value, "scaled");
4858        // The non-bare expression landed in op-template bindings.
4859        match &op.bindings {
4860            BindingsDef::PolydatSource(src) => {
4861                assert!(
4862                    src.contains("scaled := base * 2"),
4863                    "expression not injected; bindings: {src:?}"
4864                );
4865            }
4866            other => panic!("expected PolydatSource bindings, got {other:?}"),
4867        }
4868    }
4869
4870    #[test]
4871    fn parse_metrics_mapping_form_invalid_key_for_non_bare_value() {
4872        // Non-bare value + key that can't be a binding name → reject.
4873        let yaml = r#"
4874phases:
4875  p:
4876    ops:
4877      o:
4878        stmt: "noop"
4879        metrics:
4880          "1bad":
4881            value: foo + 1
4882            kind: gauge
4883"#;
4884        let err = parse_workload(yaml, &HashMap::new()).unwrap_err();
4885        assert!(
4886            err.contains("must itself be a valid identifier"),
4887            "expected identifier diagnostic, got: {err}"
4888        );
4889    }
4890
4891    #[test]
4892    fn parse_metrics_format_validation_runs_at_load() {
4893        let yaml = r##"
4894phases:
4895  p:
4896    ops:
4897      o:
4898        stmt: "noop"
4899        metrics:
4900          x:
4901            value: x
4902            format: "%3.2f"
4903"##;
4904        let err = parse_workload(yaml, &HashMap::new()).unwrap_err();
4905        assert!(
4906            err.contains("printf-style"),
4907            "format error not surfaced at parse time: {err}"
4908        );
4909    }
4910
4911    #[test]
4912    fn parse_metrics_wire_expression_collision_errors() {
4913        let yaml = r#"
4914phases:
4915  p:
4916    ops:
4917      o:
4918        stmt: "noop"
4919        bindings: |
4920          foo := 1.0
4921        metrics:
4922          - foo := 2.0
4923"#;
4924        let err = parse_workload(yaml, &HashMap::new()).unwrap_err();
4925        assert!(err.contains("collides"), "collision not detected: {err}");
4926    }
4927
4928    #[test]
4929    fn parse_phase_bindings_round_trip() {
4930        // SRD-13d Phase 1: phase-level `bindings:` block must
4931        // land on WorkloadPhase.bindings (not just merged into
4932        // ops) so HasGkMatter can classify it.
4933        let yaml = r#"
4934phases:
4935  p:
4936    bindings: |
4937      phase_factor := 7
4938    ops:
4939      o:
4940        stmt: "noop"
4941"#;
4942        let wl = parse_workload(yaml, &HashMap::new()).unwrap();
4943        match &wl.phases["p"].bindings {
4944            BindingsDef::PolydatSource(s) => assert!(s.contains("phase_factor := 7")),
4945            other => panic!("expected PolydatSource, got {other:?}"),
4946        }
4947    }
4948
4949    #[test]
4950    fn parse_phased_workload_default_scenario_from_order() {
4951        // No scenarios section — phases should run in definition order
4952        let yaml = r#"
4953phases:
4954  alpha:
4955    cycles: 1
4956    ops:
4957      op1:
4958        stmt: "a"
4959  beta:
4960    cycles: 2
4961    ops:
4962      op2:
4963        stmt: "b"
4964  gamma:
4965    cycles: 3
4966    ops:
4967      op3:
4968        stmt: "c"
4969"#;
4970        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4971        assert_eq!(workload.phase_order, vec!["alpha", "beta", "gamma"]);
4972        assert!(workload.scenarios.is_empty());
4973    }
4974
4975    #[test]
4976    fn parse_backward_compat_no_phases() {
4977        // Workload without phases should work exactly as before
4978        let yaml = r#"
4979ops:
4980  op1: "SELECT 1;"
4981  op2: "SELECT 2;"
4982"#;
4983        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
4984        assert!(workload.phases.is_empty());
4985        assert!(workload.phase_order.is_empty());
4986        assert_eq!(workload.ops.len(), 2);
4987    }
4988
4989    #[test]
4990    fn block_level_params_override_workload_default() {
4991        // SRD 21 §"Parameter Resolution": closest-wins. The DDL block declares
4992        // `consistency=1`, overriding the workload-level default `100` for ops
4993        // in that block. Uses an op-scope param (`consistency`); activity-scope
4994        // keys (`concurrency`/`rate`/`cycles`/`errors`) are deliberately NOT
4995        // merged onto ops (SRD-32a — see `ACTIVITY_PARAM_KEYS`), so this tests
4996        // op-param precedence with a key that actually reaches ops.
4997        let yaml = r#"
4998params:
4999  consistency: "100"
5000blocks:
5001  ddl:
5002    params:
5003      consistency: "1"
5004    ops:
5005      schema_create: "CREATE TABLE foo (id int PRIMARY KEY);"
5006  bulk:
5007    ops:
5008      insert: "INSERT INTO foo (id) VALUES (?);"
5009"#;
5010        let ops = parse_ops(yaml).unwrap();
5011        let ddl = ops.iter().find(|o| o.name == "schema_create").unwrap();
5012        let bulk = ops.iter().find(|o| o.name == "insert").unwrap();
5013        assert_eq!(
5014            ddl.params.get("consistency").and_then(|v| v.as_str()),
5015            Some("1"),
5016            "block-level override should win for ddl op",
5017        );
5018        assert_eq!(
5019            bulk.params.get("consistency").and_then(|v| v.as_str()),
5020            Some("100"),
5021            "non-overriding block inherits workload-level default",
5022        );
5023    }
5024
5025    #[test]
5026    fn cli_overrides_block_level_params() {
5027        // CLI is the outermost layer per SRD 21 — it wins even over block-level
5028        // explicit overrides. Uses an op-scope param (`consistency`); see
5029        // `block_level_params_override_workload_default` for why not an
5030        // activity-scope key like `concurrency`.
5031        let yaml = r#"
5032params:
5033  consistency: "100"
5034blocks:
5035  ddl:
5036    params:
5037      consistency: "1"
5038    ops:
5039      schema_create: "CREATE TABLE foo (id int PRIMARY KEY);"
5040"#;
5041        let mut cli = HashMap::new();
5042        cli.insert("consistency".to_string(), "200".to_string());
5043        let workload = parse_workload(yaml, &cli).unwrap();
5044        let ddl = workload
5045            .ops
5046            .iter()
5047            .find(|o| o.name == "schema_create")
5048            .unwrap();
5049        assert_eq!(
5050            ddl.params.get("consistency").and_then(|v| v.as_str()),
5051            Some("200"),
5052            "CLI override should beat block-level",
5053        );
5054        // Workload-level params likewise reflect CLI.
5055        assert_eq!(
5056            workload.params.get("consistency").map(|s| s.as_str()),
5057            Some("200"),
5058        );
5059    }
5060
5061    #[test]
5062    fn parse_polydat_source_overrides_parent_map() {
5063        // Block-level Polydat source completely replaces doc-level map bindings
5064        let yaml = r#"
5065bindings:
5066  id: "Hash()"
5067blocks:
5068  main:
5069    bindings: |
5070      input cycle: u64
5071      h := hash(cycle)
5072      id := mod(h, 1000)
5073      // Concise equivalent:
5074      // id := mod(hash(cycle), 1000)
5075    ops:
5076      op1: "SELECT * FROM t WHERE id={id};"
5077"#;
5078        let ops = parse_ops(yaml).unwrap();
5079        match &ops[0].bindings {
5080            BindingsDef::PolydatSource(src) => {
5081                assert!(src.contains("input cycle: u64"));
5082                assert!(src.contains("id := mod(h, 1000)"));
5083            }
5084            BindingsDef::Map(_) => panic!("expected PolydatSource, got Map"),
5085        }
5086    }
5087
5088    #[test]
5089    fn parse_scenarios_plural_list_form() {
5090        // The plural `scenarios: [a, b, c]` form composes
5091        // several named scenarios at one node. Each list
5092        // entry expands to an `IncludedScenario` and resolves
5093        // post-parse. Equivalent to `[- scenario: a, -
5094        // scenario: b, ...]` but reads more naturally for the
5095        // "just compose these" case.
5096        let yaml = r#"
5097scenarios:
5098  rampup:
5099    - prep
5100  query:
5101    - run
5102
5103  composed:
5104    - scenarios:
5105        - rampup
5106        - query
5107
5108phases:
5109  prep:
5110    ops:
5111      create:
5112        raw: "select 1"
5113  run:
5114    ops:
5115      sel:
5116        raw: "select {cycle}"
5117"#;
5118        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
5119        let composed = workload
5120            .scenarios
5121            .get("composed")
5122            .expect("composed scenario must parse");
5123        // After resolution the IncludedScenario wrappers carry
5124        // their resolved children. The scenario tree shape is:
5125        //   composed
5126        //     └── IncludedScenario("rampup") [Phase("prep")]
5127        //     └── IncludedScenario("query")  [Phase("run")]
5128        // Walk one level deep into each include to assert.
5129        assert_eq!(
5130            composed.len(),
5131            2,
5132            "scenarios: [a, b] should produce two top-level nodes"
5133        );
5134        let names: Vec<&str> = composed
5135            .iter()
5136            .filter_map(|n| match n {
5137                ScenarioNode::IncludedScenario { name, .. } => Some(name.as_str()),
5138                _ => None,
5139            })
5140            .collect();
5141        assert_eq!(names, vec!["rampup", "query"]);
5142        // First include resolves to its sole `Phase("prep")`.
5143        let first_children = match &composed[0] {
5144            ScenarioNode::IncludedScenario { children, .. } => children,
5145            _ => panic!("expected IncludedScenario at index 0"),
5146        };
5147        let first_phase = first_children.iter().find_map(|n| match n {
5148            ScenarioNode::Phase(p) => Some(p.as_str()),
5149            _ => None,
5150        });
5151        assert_eq!(first_phase, Some("prep"));
5152    }
5153
5154    #[test]
5155    fn parse_scenarios_plural_mixes_with_other_node_shapes() {
5156        // List entries can be a mix of bare strings and other
5157        // scenario-node shapes (objects with `scenario:`,
5158        // `for_each:`, etc.). This matches the heterogeneous
5159        // shape `parse_scenario_nodes` already accepts at the
5160        // top level, so the plural form composes naturally
5161        // with everything else.
5162        let yaml = r#"
5163scenarios:
5164  rampup:
5165    - prep
5166  composed:
5167    - scenarios:
5168        - rampup
5169        - { scenario: rampup }
5170
5171phases:
5172  prep:
5173    ops:
5174      create:
5175        raw: "select 1"
5176"#;
5177        let workload = parse_workload(yaml, &HashMap::new()).unwrap();
5178        let composed = workload.scenarios.get("composed").unwrap();
5179        // Both list entries should resolve to an IncludedScenario
5180        // wrapping the same `prep` phase.
5181        assert_eq!(composed.len(), 2);
5182        for node in composed {
5183            match node {
5184                ScenarioNode::IncludedScenario { name, children } => {
5185                    assert_eq!(name, "rampup");
5186                    assert!(
5187                        children
5188                            .iter()
5189                            .any(|c| matches!(c, ScenarioNode::Phase(p) if p == "prep"))
5190                    );
5191                }
5192                other => panic!("expected IncludedScenario, got {other:?}"),
5193            }
5194        }
5195    }
5196
5197    // -----------------------------------------------------------------
5198    // Checkpoint declaration parsing — SRD-44 §"Forms"
5199    // -----------------------------------------------------------------
5200
5201    fn parse_checkpoint_field(yaml: &str) -> Option<crate::model::Checkpoint> {
5202        let yaml = format!(
5203            "phases:\n  p:\n{}\n    ops:\n      - select 1;\n",
5204            yaml.lines()
5205                .map(|l| format!("    {l}"))
5206                .collect::<Vec<_>>()
5207                .join("\n")
5208        );
5209        let v: serde_yaml::Value = serde_yaml::from_str(&yaml).expect("yaml parse");
5210        let json: serde_json::Value = serde_json::to_value(&v).expect("json convert");
5211        let phases_obj = json
5212            .get("phases")
5213            .and_then(|p| p.as_object())
5214            .expect("phases");
5215        let phase = phases_obj
5216            .get("p")
5217            .and_then(|p| p.as_object())
5218            .expect("phase p");
5219        phase.get("checkpoint").map(|v| {
5220            serde_json::from_value::<crate::model::Checkpoint>(v.clone()).expect("checkpoint parse")
5221        })
5222    }
5223
5224    #[test]
5225    fn checkpoint_short_form_idempotent() {
5226        let cp = parse_checkpoint_field("checkpoint: idempotent").expect("present");
5227        assert!(cp.idempotent);
5228        assert!(cp.hashed);
5229        assert!(cp.verify.is_none());
5230    }
5231
5232    #[test]
5233    fn checkpoint_short_form_none_disables_skip() {
5234        let cp = parse_checkpoint_field("checkpoint: none").expect("present");
5235        assert!(!cp.idempotent);
5236        // hashed default-true is preserved even when disabled —
5237        // the disabled state is about skip eligibility, not
5238        // about the hash field.
5239        assert!(cp.hashed);
5240        assert!(cp.verify.is_none());
5241    }
5242
5243    #[test]
5244    fn checkpoint_bool_and_empty_forms_name_the_short_form() {
5245        // One spelling per meaning: `idempotent` / `none` (or a
5246        // mapping). A bool, its string spelling, or a bare null is
5247        // an error naming the short form to write.
5248        for (form, want) in [
5249            ("true", "checkpoint: idempotent"),
5250            ("false", "checkpoint: none"),
5251            ("\"true\"", "checkpoint: idempotent"),
5252            ("\"false\"", "checkpoint: none"),
5253            ("", "checkpoint: idempotent"),
5254        ] {
5255            let v: serde_json::Value = if form.is_empty() {
5256                serde_json::Value::Null
5257            } else {
5258                serde_json::to_value(serde_yaml::from_str::<serde_yaml::Value>(form).unwrap())
5259                    .unwrap()
5260            };
5261            let err = serde_json::from_value::<crate::model::Checkpoint>(v)
5262                .expect_err(form)
5263                .to_string();
5264            assert!(err.contains(want), "{form:?}: {err}");
5265        }
5266    }
5267
5268    #[test]
5269    fn checkpoint_short_forms_load_through_the_full_parser() {
5270        // The construction table and the deserializer must agree on
5271        // the short-form vocabulary (they once disagreed:
5272        // `disabled` vs `none`, so `checkpoint: none` failed to load).
5273        for (form, idempotent) in [("idempotent", true), ("none", false)] {
5274            let yaml = format!(
5275                "phases:\n  p:\n    cycles: 1\n    checkpoint: {form}\n    ops:\n      - select 1;\n"
5276            );
5277            let wl = parse_workload(&yaml, &HashMap::new())
5278                .unwrap_or_else(|e| panic!("checkpoint: {form} must load: {e}"));
5279            let cp = wl.phases["p"].checkpoint.as_ref().expect("declared");
5280            assert_eq!(cp.idempotent, idempotent, "{form}");
5281        }
5282    }
5283
5284    #[test]
5285    fn checkpoint_full_form_all_explicit() {
5286        let cp = parse_checkpoint_field("checkpoint:\n  idempotent: true\n  hashed: false")
5287            .expect("present");
5288        assert!(cp.idempotent);
5289        assert!(!cp.hashed);
5290        assert!(cp.verify.is_none());
5291    }
5292
5293    #[test]
5294    fn checkpoint_full_form_with_verify() {
5295        let cp = parse_checkpoint_field(
5296            "checkpoint:\n  idempotent: true\n  verify:\n    raw: 'SELECT 1'\n    poll: assert_one",
5297        )
5298        .expect("present");
5299        assert!(cp.idempotent);
5300        assert!(cp.hashed); // default
5301        let v = cp.verify.expect("verify body");
5302        assert_eq!(v.get("raw").and_then(|x| x.as_str()), Some("SELECT 1"));
5303        assert_eq!(v.get("poll").and_then(|x| x.as_str()), Some("assert_one"));
5304    }
5305
5306    #[test]
5307    fn checkpoint_full_form_idempotent_false_equivalent_to_none() {
5308        let cp = parse_checkpoint_field("checkpoint:\n  idempotent: false\n  hashed: true")
5309            .expect("present");
5310        assert!(!cp.idempotent);
5311        assert!(cp.hashed);
5312    }
5313
5314    #[test]
5315    fn checkpoint_unknown_short_form_errors() {
5316        // Should fail to parse — an unknown short string is a
5317        // workload bug, not silently treated as `none`.
5318        let yaml = "phases:\n  p:\n    checkpoint: maybe\n    ops:\n      - select 1;\n";
5319        let v: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
5320        let json: serde_json::Value = serde_json::to_value(&v).unwrap();
5321        let phases_obj = json.get("phases").and_then(|p| p.as_object()).unwrap();
5322        let phase = phases_obj.get("p").and_then(|p| p.as_object()).unwrap();
5323        let cp_val = phase.get("checkpoint").unwrap().clone();
5324        let err = serde_json::from_value::<crate::model::Checkpoint>(cp_val).unwrap_err();
5325        let msg = err.to_string();
5326        assert!(
5327            msg.contains("unknown short form"),
5328            "expected unknown-short-form error, got: {msg}"
5329        );
5330        assert!(
5331            msg.contains("'maybe'"),
5332            "expected the bad token in error, got: {msg}"
5333        );
5334    }
5335
5336    #[test]
5337    fn checkpoint_unknown_key_errors() {
5338        let yaml = "phases:\n  p:\n    checkpoint:\n      idempotent: true\n      bogus: yes\n    ops:\n      - select 1;\n";
5339        let v: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
5340        let json: serde_json::Value = serde_json::to_value(&v).unwrap();
5341        let cp_val = json.pointer("/phases/p/checkpoint").unwrap().clone();
5342        let err = serde_json::from_value::<crate::model::Checkpoint>(cp_val).unwrap_err();
5343        let msg = err.to_string();
5344        assert!(
5345            msg.contains("unknown key 'bogus'"),
5346            "expected unknown-key error, got: {msg}"
5347        );
5348    }
5349
5350    #[test]
5351    fn checkpoint_field_absent_yields_none() {
5352        let cp = parse_checkpoint_field("# no checkpoint declared\n");
5353        assert!(
5354            cp.is_none(),
5355            "absent declaration should yield None, not Default"
5356        );
5357    }
5358
5359    /// SRD-44 validation: a phase declared `checkpoint:
5360    /// idempotent` inside a do_while loop must be rejected at
5361    /// workload-load time. The do-loop iterates the same phase
5362    /// identity multiple times, contradicting the per-execution
5363    /// unit checkpointing assumes.
5364    #[test]
5365    fn rejects_idempotent_phase_inside_do_while() {
5366        let yaml = r#"
5367scenarios:
5368  default:
5369    - do_while: "true"
5370      phases:
5371        - probe
5372phases:
5373  probe:
5374    checkpoint: idempotent
5375    cycles: 1
5376    ops:
5377      step:
5378        stmt: "probe"
5379"#;
5380        let err = super::parse_workload(yaml, &HashMap::new())
5381            .expect_err("expected validation rejection");
5382        assert!(
5383            err.contains("checkpoint: idempotent"),
5384            "error should explain the rejection: {err}"
5385        );
5386        assert!(
5387            err.contains("'probe'"),
5388            "error should name the offending phase: {err}"
5389        );
5390        assert!(
5391            err.contains("do_while") || err.contains("do_until"),
5392            "error should mention the do-loop ancestor: {err}"
5393        );
5394    }
5395
5396    /// `do_until` triggers the same rejection.
5397    #[test]
5398    fn rejects_idempotent_phase_inside_do_until() {
5399        let yaml = r#"
5400scenarios:
5401  default:
5402    - do_until: "false"
5403      phases:
5404        - probe
5405phases:
5406  probe:
5407    checkpoint: idempotent
5408    cycles: 1
5409    ops:
5410      step:
5411        stmt: "probe"
5412"#;
5413        let err = super::parse_workload(yaml, &HashMap::new())
5414            .expect_err("expected validation rejection");
5415        assert!(err.contains("'probe'"));
5416    }
5417
5418    /// A do_while'd phase WITHOUT checkpoint declaration is
5419    /// fine — only the combination with `checkpoint:
5420    /// idempotent` is rejected.
5421    #[test]
5422    fn allows_do_while_phase_without_checkpoint_declaration() {
5423        let yaml = r#"
5424scenarios:
5425  default:
5426    - do_while: "true"
5427      phases:
5428        - probe
5429phases:
5430  probe:
5431    cycles: 1
5432    ops:
5433      step:
5434        stmt: "probe"
5435"#;
5436        super::parse_workload(yaml, &HashMap::new()).expect("plain do_while phase should parse");
5437    }
5438
5439    /// Idempotent phases NOT inside a do-loop are fine.
5440    #[test]
5441    fn allows_idempotent_phase_outside_do_loop() {
5442        let yaml = r#"
5443scenarios:
5444  default:
5445    - probe
5446phases:
5447  probe:
5448    checkpoint: idempotent
5449    cycles: 1
5450    ops:
5451      step:
5452        stmt: "probe"
5453"#;
5454        super::parse_workload(yaml, &HashMap::new())
5455            .expect("idempotent phase outside loop should parse");
5456    }
5457
5458    /// Declarative `capture:` map block on an op produces
5459    /// CapturePoint entries with [`CapturePoint::path`] set.
5460    /// JSON-Pointer paths are not validated against the
5461    /// response shape (it's a runtime read), so the parser's
5462    /// only job is to forbid obviously-malformed inputs
5463    /// (non-string values, paths missing the leading `/`).
5464    #[test]
5465    fn parses_declarative_capture_block_with_json_pointer_paths() {
5466        let yaml = r#"
5467scenarios:
5468  default:
5469    - probe
5470phases:
5471  probe:
5472    cycles: 1
5473    ops:
5474      read_state:
5475        adapter: http
5476        method: POST
5477        uri: "http://h:8778/jolokia/"
5478        body: "[]"
5479        capture:
5480          sstables: "/0/value"
5481          active_count: "/1/value:count"
5482          pending_for_cf: "/2/value"
5483"#;
5484        let wl = super::parse_workload(yaml, &HashMap::new())
5485            .expect("workload with declarative captures should parse");
5486        let phase = wl.phases.get("probe").expect("probe phase");
5487        let op = phase
5488            .ops
5489            .iter()
5490            .find(|o| o.name == "read_state")
5491            .expect("read_state op");
5492        assert_eq!(
5493            op.captures.len(),
5494            3,
5495            "expected 3 declarative captures, got {:?}",
5496            op.captures
5497        );
5498        let by_name = |n: &str| {
5499            op.captures
5500                .iter()
5501                .find(|c| c.as_name == n)
5502                .unwrap_or_else(|| panic!("capture {n} missing"))
5503        };
5504        let sstables = by_name("sstables");
5505        assert_eq!(sstables.path.as_deref(), Some("/0/value"));
5506        assert!(!sstables.count);
5507        let active = by_name("active_count");
5508        assert_eq!(
5509            active.path.as_deref(),
5510            Some("/1/value"),
5511            ":count suffix should be stripped from stored path"
5512        );
5513        assert!(active.count, ":count suffix should set CapturePoint.count");
5514        let pending = by_name("pending_for_cf");
5515        assert_eq!(pending.path.as_deref(), Some("/2/value"));
5516        assert!(!pending.count);
5517    }
5518
5519    /// SRD-75: phase-level `poll:` block parses into
5520    /// `WorkloadPhase.poll`. Distinct from the op-level
5521    /// `poll:` field which lives on a single op and routes
5522    /// through the `PollingDispenser` wrapper.
5523    #[test]
5524    fn parses_phase_level_poll_block() {
5525        let yaml = r#"
5526scenarios:
5527  default:
5528    - ensure
5529phases:
5530  ensure:
5531    cycles: 1
5532    poll:
5533      until: "sstables == 1 && active_for_cf == 0"
5534      interval_ms: 5000
5535      timeout_ms: 14400000
5536      max_error_retries: 3
5537      metric_name: ensure_wait_s
5538    ops:
5539      read_state:
5540        stmt: "noop"
5541"#;
5542        let wl =
5543            super::parse_workload(yaml, &HashMap::new()).expect("phase-poll block should parse");
5544        let phase = wl.phases.get("ensure").expect("ensure phase");
5545        let poll = phase.poll.as_ref().expect("phase.poll Some");
5546        assert_eq!(poll.until, "sstables == 1 && active_for_cf == 0");
5547        assert_eq!(poll.interval_ms.as_deref(), Some("5000"));
5548        assert_eq!(poll.timeout_ms.as_deref(), Some("14400000"));
5549        assert_eq!(poll.max_error_retries.as_deref(), Some("3"));
5550        assert_eq!(poll.metric_name.as_deref(), Some("ensure_wait_s"));
5551    }
5552
5553    #[test]
5554    fn optimize_string_is_sugar_for_objective_block() {
5555        // SRD-86 — `optimize: <string>` is shorthand for
5556        // `optimize: { objective: <string> }` with every other field defaulted.
5557        let yaml = r#"
5558scenarios:
5559  default:
5560    - search
5561phases:
5562  search:
5563    cycles: 1
5564    for_each: "ef in 1.0 .. 5.0"
5565    optimize: |
5566      0 - (ef - 4) * (ef - 4)
5567    ops:
5568      probe:
5569        stmt: "probe ef={ef}"
5570"#;
5571        let wl = super::parse_workload(yaml, &HashMap::new())
5572            .expect("string-form optimize should parse");
5573        let opt = wl
5574            .phases
5575            .get("search")
5576            .and_then(|p| p.optimize.as_ref())
5577            .expect("optimize block present");
5578        // The whole string became the objective; the rest defaulted.
5579        assert_eq!(opt.objective.trim(), "0 - (ef - 4) * (ef - 4)");
5580        assert_eq!(opt.method, "sweep");
5581        assert!(opt.servo.is_empty());
5582
5583        // ...and it is equivalent to the explicit map form.
5584        let map_yaml = yaml.replace(
5585            "    optimize: |\n      0 - (ef - 4) * (ef - 4)\n",
5586            "    optimize: { objective: \"0 - (ef - 4) * (ef - 4)\" }\n",
5587        );
5588        let wl2 = super::parse_workload(&map_yaml, &HashMap::new())
5589            .expect("map-form optimize should parse");
5590        let opt2 = wl2
5591            .phases
5592            .get("search")
5593            .and_then(|p| p.optimize.as_ref())
5594            .unwrap();
5595        assert_eq!(opt.objective.trim(), opt2.objective.trim());
5596        assert_eq!(opt.method, opt2.method);
5597    }
5598
5599    /// SRD-75 §"Workload-load validation": phase-poll +
5600    /// concurrency > 1 is rejected at parse time. The
5601    /// predicate's evaluation depends on a serial sequence
5602    /// of capture writes; concurrent cycle execution has no
5603    /// well-defined semantic here.
5604    #[test]
5605    fn rejects_phase_poll_with_concurrency_gt_one() {
5606        let yaml = r#"
5607scenarios:
5608  default:
5609    - ensure
5610phases:
5611  ensure:
5612    cycles: 1
5613    concurrency: 4
5614    poll:
5615      until: "done == 1"
5616    ops:
5617      op1:
5618        stmt: "noop"
5619"#;
5620        let err = super::parse_workload(yaml, &HashMap::new())
5621            .expect_err("poll: + concurrency > 1 must error");
5622        assert!(
5623            err.contains("poll:") && err.contains("concurrency"),
5624            "expected error to name both poll: and concurrency; got: {err}"
5625        );
5626    }
5627
5628    /// SRD-75 §"Workload-load validation": phase-poll with
5629    /// no ops is rejected — captures are produced by op
5630    /// execution; a poll-phase with no ops has nothing to
5631    /// drive the predicate.
5632    #[test]
5633    fn rejects_phase_poll_with_no_ops() {
5634        let yaml = r#"
5635scenarios:
5636  default:
5637    - ensure
5638phases:
5639  ensure:
5640    cycles: 1
5641    poll:
5642      until: "done == 1"
5643"#;
5644        let err =
5645            super::parse_workload(yaml, &HashMap::new()).expect_err("poll: without ops must error");
5646        assert!(
5647            err.contains("poll:") && err.contains("ops"),
5648            "expected error to name poll: and ops:; got: {err}"
5649        );
5650    }
5651
5652    /// Unknown keys under `poll:` are typos waiting to
5653    /// silently default. Surface them at parse time.
5654    #[test]
5655    fn rejects_unknown_keys_under_phase_poll() {
5656        let yaml = r#"
5657scenarios:
5658  default:
5659    - ensure
5660phases:
5661  ensure:
5662    cycles: 1
5663    poll:
5664      until: "done == 1"
5665      tinerval_ms: 5000
5666    ops:
5667      op1:
5668        stmt: "noop"
5669"#;
5670        let err =
5671            super::parse_workload(yaml, &HashMap::new()).expect_err("typo under poll: must error");
5672        assert!(
5673            err.contains("tinerval_ms"),
5674            "expected error to name the offending key; got: {err}"
5675        );
5676    }
5677
5678    /// SRD-75 §"on_timeout" — accepts the documented
5679    /// closed-vocabulary values and persists them on the
5680    /// parsed phase model. Both `error` and `abort` parse
5681    /// cleanly; case is normalised at parse time.
5682    #[test]
5683    fn parses_phase_poll_on_timeout_accepts_error_and_abort() {
5684        for (input, expected) in [
5685            ("error", "error"),
5686            ("abort", "abort"),
5687            ("ABORT", "abort"),
5688            ("Error", "error"),
5689        ] {
5690            let yaml = format!(
5691                r#"
5692scenarios:
5693  default:
5694    - ensure
5695phases:
5696  ensure:
5697    cycles: 1
5698    poll:
5699      until: "done == 1"
5700      on_timeout: {input}
5701    ops:
5702      op1:
5703        stmt: "noop"
5704"#
5705            );
5706            let wl = super::parse_workload(&yaml, &HashMap::new())
5707                .expect("on_timeout value should parse");
5708            let phase = wl.phases.get("ensure").expect("ensure phase");
5709            let poll = phase.poll.as_ref().expect("phase.poll Some");
5710            assert_eq!(
5711                poll.on_timeout.as_deref(),
5712                Some(expected),
5713                "on_timeout '{input}' should normalise to '{expected}'"
5714            );
5715        }
5716    }
5717
5718    /// SRD-75 §"on_timeout" — anything outside the
5719    /// closed vocabulary is rejected at parse time.
5720    /// Typos like `aborts:` or `fail:` should fail loudly,
5721    /// not silently default to `error` and obscure the
5722    /// workload-author's actual intent.
5723    #[test]
5724    fn rejects_phase_poll_unknown_on_timeout_value() {
5725        let yaml = r#"
5726scenarios:
5727  default:
5728    - ensure
5729phases:
5730  ensure:
5731    cycles: 1
5732    poll:
5733      until: "done == 1"
5734      on_timeout: fail
5735    ops:
5736      op1:
5737        stmt: "noop"
5738"#;
5739        let err = super::parse_workload(yaml, &HashMap::new())
5740            .expect_err("unknown on_timeout value must error");
5741        assert!(
5742            err.contains("on_timeout") && err.contains("'fail'"),
5743            "expected error to name the offending value; got: {err}"
5744        );
5745    }
5746
5747    /// `poll:` requires `until:` — the predicate is the
5748    /// loop's whole purpose.
5749    #[test]
5750    fn rejects_phase_poll_without_until() {
5751        let yaml = r#"
5752scenarios:
5753  default:
5754    - ensure
5755phases:
5756  ensure:
5757    cycles: 1
5758    poll:
5759      interval_ms: 5000
5760    ops:
5761      op1:
5762        stmt: "noop"
5763"#;
5764        let err = super::parse_workload(yaml, &HashMap::new())
5765            .expect_err("poll: without until: must error");
5766        assert!(
5767            err.contains("until"),
5768            "expected error to require until:; got: {err}"
5769        );
5770    }
5771
5772    /// SRD-83 Part 5 — the `effect:`/`action:` verb vocabulary is
5773    /// closed. An unknown verb used to fall silently to the shell
5774    /// default at the trip site; it is a load error now.
5775    #[test]
5776    fn rejects_unknown_stop_condition_effect() {
5777        let yaml = r#"
5778scenarios:
5779  default:
5780    - work
5781phases:
5782  work:
5783    cycles: 10
5784    stop_when:
5785      - when: "cycles_total > 5"
5786        effect: sotp
5787    ops:
5788      op1:
5789        stmt: "noop"
5790"#;
5791        let err = super::parse_workload(yaml, &HashMap::new())
5792            .expect_err("unknown effect verb must be a load error");
5793        assert!(
5794            err.contains("sotp") && err.contains("stop|fail|abort"),
5795            "expected error to name the verb and the vocabulary; got: {err}"
5796        );
5797    }
5798
5799    /// The three declared verbs — and the `action:` alias — all load.
5800    #[test]
5801    fn accepts_declared_stop_condition_effects() {
5802        let yaml = |key: &str, verb: &str| {
5803            format!(
5804                r#"
5805scenarios:
5806  default:
5807    - work
5808phases:
5809  work:
5810    cycles: 10
5811    stop_when:
5812      - when: "cycles_total > 5"
5813        {key}: {verb}
5814    ops:
5815      op1:
5816        stmt: "noop"
5817"#
5818            )
5819        };
5820        for verb in ["stop", "fail", "abort"] {
5821            super::parse_workload(&yaml("effect", verb), &HashMap::new())
5822                .unwrap_or_else(|e| panic!("effect: {verb} must load: {e}"));
5823        }
5824        // `effect:` has one spelling; `action:` is an unknown key, not an alias.
5825        assert!(
5826            super::parse_workload(&yaml("action", "abort"), &HashMap::new()).is_err(),
5827            "`action:` must be rejected"
5828        );
5829    }
5830
5831    /// The op sugars all load: `op:` as a workload's one op (string or
5832    /// template map), a block written as one string, and inside an op
5833    /// `op:` as a statement string or as the payload map.
5834    #[test]
5835    fn op_sugar_forms_load() {
5836        let stmt_of = |yaml: &str| -> String {
5837            let w = super::parse_workload(yaml, &HashMap::new())
5838                .unwrap_or_else(|e| panic!("must load:\n{yaml}\n{e}"));
5839            assert_eq!(w.ops.len(), 1, "one op from:\n{yaml}");
5840            w.ops[0]
5841                .op
5842                .get("stmt")
5843                .and_then(|v| v.as_str())
5844                .unwrap()
5845                .to_string()
5846        };
5847        assert_eq!(stmt_of("op: select 1\n"), "select 1");
5848        assert_eq!(stmt_of("op:\n  stmt: select 2\n  ratio: 3\n"), "select 2");
5849        assert_eq!(stmt_of("blocks:\n  b1: select 3\n"), "select 3");
5850        assert_eq!(stmt_of("ops:\n  o1:\n    op: select 4\n"), "select 4");
5851        assert_eq!(
5852            stmt_of("ops:\n  o1:\n    op:\n      stmt: select 5\n"),
5853            "select 5"
5854        );
5855        assert_eq!(stmt_of("ops:\n  o1:\n    stmt: select 6\n"), "select 6");
5856    }
5857
5858    /// Every retired key spelling is an error naming the key to write,
5859    /// never a silent op field or an ignored key.
5860    #[test]
5861    fn retired_op_key_spellings_name_the_canonical_key() {
5862        let cases = [
5863            ("operations: select 1\n", "under `ops:`"),
5864            ("statements: select 1\n", "under `ops:`"),
5865            ("statement: select 1\n", "under `ops:`"),
5866            ("blocks:\n  b1:\n    statements: select 1\n", "under `ops:`"),
5867            ("op:\n  - select 1\n", "under `ops:`"),
5868            ("ops: select 1\nop: select 2\n", "both `ops:` and `op:`"),
5869            (
5870                "ops: select 1\nblocks:\n  b1: select 2\n",
5871                "and `blocks:` both given",
5872            ),
5873            (
5874                "op: select 1\nblocks:\n  b1: select 2\n",
5875                "and `blocks:` both given",
5876            ),
5877            ("phases:\n  p:\n    op: select 1\n", "under `ops:`"),
5878            ("phases:\n  p:\n    statements: select 1\n", "under `ops:`"),
5879            ("ops:\n  o1:\n    statement: select 1\n", "write `stmt:`"),
5880            ("ops:\n  o1:\n    statements: select 1\n", "write `stmt:`"),
5881            ("ops:\n  o1:\n    ops: select 1\n", "write `op:`"),
5882            ("ops:\n  o1:\n    operations: select 1\n", "write `op:`"),
5883            (
5884                "ops:\n  o1:\n    stmt: select 1\n    desc: d\n",
5885                "write `description:`",
5886            ),
5887            (
5888                "ops:\n  o1:\n    stmt: select 1\n    driver: stdout\n",
5889                "write `adapter:`",
5890            ),
5891        ];
5892        for (yaml, expect) in cases {
5893            let err = match super::parse_workload(yaml, &HashMap::new()) {
5894                Ok(_) => panic!("must be rejected:\n{yaml}"),
5895                Err(e) => e,
5896            };
5897            assert!(
5898                err.contains(expect),
5899                "{yaml}\n→ {err}\nmust contain {expect:?}"
5900            );
5901        }
5902    }
5903
5904    /// A path that contains `/` but doesn't begin with one is the
5905    /// ambiguous case: `0/value` is either a JSON-Pointer missing its
5906    /// leading slash (the classic transcription bug) or a member
5907    /// literally named "0/value" (which RFC 6901 spells `/0~1value`).
5908    /// Both readings are defensible, so the parser refuses rather than
5909    /// picking one — surfaced at parse time, not as silent
5910    /// capture-misses at runtime. Bare names WITHOUT a `/` are
5911    /// unambiguous and accepted; see the tests below.
5912    #[test]
5913    fn rejects_capture_path_without_leading_slash() {
5914        let yaml = r#"
5915scenarios:
5916  default:
5917    - probe
5918phases:
5919  probe:
5920    cycles: 1
5921    ops:
5922      read_state:
5923        adapter: http
5924        method: POST
5925        uri: "http://h:8778/"
5926        body: "[]"
5927        capture:
5928          bad: "0/value"
5929"#;
5930        let err = super::parse_workload(yaml, &HashMap::new())
5931            .expect_err("path without leading / must error");
5932        assert!(
5933            err.contains("`capture.bad`") && err.contains("'/'"),
5934            "expected parse error to name the offending capture and require '/'; got: {err}"
5935        );
5936    }
5937
5938    /// A bare top-level member name means exactly `/name`, and is
5939    /// normalized to it at parse time so runtime resolves one form. This
5940    /// is the spelling `verify:`'s `field:` uses, so an author moving
5941    /// between the two blocks on one op writes the same thing twice.
5942    #[test]
5943    fn accepts_bare_member_name_as_capture_path() {
5944        let yaml = r#"
5945scenarios:
5946  default:
5947    - probe
5948phases:
5949  probe:
5950    cycles: 1
5951    ops:
5952      read_state:
5953        adapter: http
5954        method: GET
5955        uri: "http://h:8778/"
5956        capture:
5957          bare: "value"
5958          pointer: "/value"
5959          rooted: ""
5960"#;
5961        let wl = super::parse_workload(yaml, &HashMap::new()).expect("both spellings must parse");
5962        let op = wl
5963            .phases
5964            .get("probe")
5965            .expect("phase")
5966            .ops
5967            .iter()
5968            .find(|o| o.name == "read_state")
5969            .expect("op");
5970        let path_of = |wire: &str| {
5971            op.captures
5972                .iter()
5973                .find(|c| c.as_name == wire)
5974                .unwrap_or_else(|| panic!("capture {wire} missing"))
5975                .path
5976                .clone()
5977                .expect("declarative capture carries a path")
5978        };
5979        assert_eq!(
5980            path_of("bare"),
5981            "/value",
5982            "a bare name normalizes to the equivalent pointer"
5983        );
5984        assert_eq!(
5985            path_of("pointer"),
5986            "/value",
5987            "and is indistinguishable from the pointer spelling downstream"
5988        );
5989        assert_eq!(
5990            path_of("rooted"),
5991            "",
5992            "empty still addresses the root document"
5993        );
5994    }
5995
5996    /// `~` is a JSON-Pointer escape introducer (`~0` = `~`, `~1` = `/`), so
5997    /// a bare name containing one is ambiguous for the same reason `/` is.
5998    #[test]
5999    fn rejects_bare_name_containing_pointer_escape_char() {
6000        let yaml = r#"
6001scenarios:
6002  default:
6003    - probe
6004phases:
6005  probe:
6006    cycles: 1
6007    ops:
6008      read_state:
6009        adapter: http
6010        method: GET
6011        uri: "http://h:8778/"
6012        capture:
6013          bad: "a~1b"
6014"#;
6015        let err = super::parse_workload(yaml, &HashMap::new())
6016            .expect_err("a bare name with '~' must error");
6017        assert!(
6018            err.contains("`capture.bad`") && err.contains("ambiguous"),
6019            "expected an ambiguity error naming the capture; got: {err}"
6020        );
6021    }
6022
6023    #[test]
6024    fn set_value_bare_is_reference() {
6025        // A bare `set:` value is a wire REFERENCE (consistent with
6026        // comprehension r-values); a string literal is the explicit
6027        // polydat-quoted form; a number/bool is a literal; a sequence is a list.
6028        fn set_source(pair: &str) -> String {
6029            let yaml = format!(
6030                "scenarios:\n  s:\n    - set: {{ {pair} }}\n      \
6031                 phases:\n        - p\nops:\n  p: \"test\"\n"
6032            );
6033            let wl = super::parse_workload(&yaml, &HashMap::new()).expect("parse");
6034            for n in &wl.scenarios["s"] {
6035                if let ScenarioNode::Bindings { source, .. } = n {
6036                    return source.trim().to_string();
6037                }
6038            }
6039            panic!("no Bindings node for `set: {{ {pair} }}`");
6040        }
6041        // bare identifier → wire reference (unquoted)
6042        assert_eq!(set_source("x: mnc"), "const x := mnc");
6043        assert_eq!(set_source("x: verbose"), "const x := verbose");
6044        // explicit polydat-quoted form → a string literal
6045        assert_eq!(set_source(r#"x: '"verbose"'"#), r#"const x := "verbose""#);
6046        // a YAML sequence → a list literal (of references)
6047        assert_eq!(set_source("x: [a, b]"), "const x := [a, b]");
6048        // numbers/bools are literals (serde distinguishes 8 from "8")
6049        assert_eq!(set_source("x: 8"), "const x := 8");
6050        assert_eq!(set_source(r#"x: "8""#), r#"const x := "8""#);
6051        assert_eq!(set_source("x: true"), "const x := true");
6052    }
6053}