Skip to main content

nmbrs_runtime/
runner.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shared run pipeline for persona binaries.
5//!
6//! Encapsulates workload parsing → Polydat compilation → activity
7//! construction → execution (single or phased).
8//!
9//! Each persona binary links its adapter crates (which register
10//! themselves via `inventory::submit!`) and calls [`run()`].
11//! The persona adds nothing but adapters and node functions —
12//! all orchestration logic lives here.
13
14use std::collections::HashMap;
15use std::sync::Arc;
16
17use crate::activity::Activity;
18use crate::adapter::{find_adapter_registration, registered_adapter_params};
19use crate::bindings::build_workload_root_kernel;
20use crate::opseq::SequencerType;
21use crate::synthesis::OpBuilder;
22use nmbrs_metrics::labels::Labels;
23use nmbrs_metrics::scheduler::Reporter;
24use nmbrs_workload::tags::TagFilter;
25
26/// The run-style `key=value` param vocabulary, injected by the CLI layer
27/// from its own command-spec (`nmbrs::completion::RUN_KV_PARAMS`) so there is
28/// ONE source of truth and zero hand-synced copies. `None` until installed
29/// (library/test consumers that drive the runner directly without the CLI):
30/// in that case the param-vocabulary validations below are skipped — those
31/// are a CLI-surface concern, and the binary always installs the list before
32/// any run. See [`install_known_params`] / [`known_params`].
33static KNOWN_PARAMS: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
34
35/// Install the run-style param vocabulary (the keys the CLI command-spec
36/// accepts, sans the trailing `=`). Called once at binary startup from the
37/// CLI layer, which owns the canonical list. Idempotent — first wins.
38pub fn install_known_params(keys: Vec<&'static str>) {
39    let _ = KNOWN_PARAMS.set(keys);
40}
41
42/// The installed param vocabulary, or `None` when no CLI layer registered
43/// one. Validators treat `None` as "skip the closed-vocabulary check" so a
44/// direct library/test driver isn't held to the CLI's param surface.
45/// Adapter-specific params are still discovered from inventory regardless.
46fn known_params() -> Option<&'static [&'static str]> {
47    KNOWN_PARAMS.get().map(|v| v.as_slice())
48}
49
50/// Whether `name` is an installed CLI param key. When no vocabulary is
51/// installed (library/test driver), every name is treated as known so the
52/// closed-vocabulary validations no-op rather than false-reject a workload.
53pub(crate) fn is_cli_param(name: &str) -> bool {
54    known_params().map(|p| p.contains(&name)).unwrap_or(true)
55}
56
57/// Spec-derived flag vocabulary (SRD-15 CLI substrate): the run command's
58/// DECLARED flags, split by arity, installed at binary startup exactly like
59/// [`install_known_params`]. Before this, [`parse_params`] validated argv
60/// against its own hardcoded lists ([`RECOGNIZED_BARE_FLAGS`] /
61/// [`SESSION_DIR_FLAGS`]), which had drifted from the spec — declared flags
62/// like `--no-prompt` (bool) and the space form of `--kernel-opt` were
63/// hard-rejected while help and completion advertised them. The hardcoded lists remain only as the
64/// library/test-driver fallback.
65static KNOWN_BARE_FLAGS: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
66static KNOWN_VALUE_FLAGS: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
67
68/// Install the run-style flag vocabulary (long forms + aliases from the CLI
69/// command-spec, split by arity). Idempotent — first wins.
70pub fn install_known_flags(bare: Vec<&'static str>, value: Vec<&'static str>) {
71    let _ = KNOWN_BARE_FLAGS.set(bare);
72    let _ = KNOWN_VALUE_FLAGS.set(value);
73}
74
75/// Recognized bare (boolean) flag: the installed spec list, or the
76/// hardcoded fallback. `--refine` is runner-internal (injected by the
77/// refine command, never user-declared) so it is always recognized.
78pub(crate) fn is_recognized_bare_flag(arg: &str) -> bool {
79    arg == "--refine"
80        || KNOWN_BARE_FLAGS
81            .get()
82            .map(|v| v.contains(&arg))
83            .unwrap_or_else(|| RECOGNIZED_BARE_FLAGS.contains(&arg))
84}
85
86/// Recognized value-taking flag (space form consumes the next token):
87/// the installed spec list, or the hardcoded session-flag fallback.
88pub(crate) fn known_value_flags() -> &'static [&'static str] {
89    KNOWN_VALUE_FLAGS
90        .get()
91        .map(|v| v.as_slice())
92        .unwrap_or(SESSION_DIR_FLAGS)
93}
94
95/// Every recognized flag, bare and value-taking: the candidates an
96/// unrecognized `--flag` is matched against for a suggestion.
97fn known_flags() -> Vec<&'static str> {
98    let bare: &[&str] = KNOWN_BARE_FLAGS
99        .get()
100        .map(|v| v.as_slice())
101        .unwrap_or(RECOGNIZED_BARE_FLAGS);
102    bare.iter().chain(known_value_flags()).copied().collect()
103}
104
105/// A CLI flag's value, accepting `--flag=value` and `--flag value`.
106///
107/// The same two spellings [`crate::session::resolve_flag`] accepts, minus its
108/// environment-variable fallback and conflict check — for flags that are
109/// CLI-only by design. Written out because the flags declared in the command
110/// spec are advertised (in `--help` and completion) as taking a value, and a
111/// reader matching only `--flag=` would silently ignore the spelling the
112/// completer suggests.
113fn cli_flag_value(args: &[String], flag: &str) -> Option<String> {
114    let eq_prefix = format!("{flag}=");
115    let mut iter = args.iter();
116    while let Some(arg) = iter.next() {
117        if let Some(rest) = arg.strip_prefix(&eq_prefix) {
118            return Some(rest.to_string());
119        }
120        if arg == flag {
121            return iter.next().cloned();
122        }
123    }
124    None
125}
126
127/// Session-dir file holding end-of-run summary output that is
128/// routed to stdout (SRD-46 `to stdout`) but could not be written
129/// inline because a TUI owned the terminal. The post-run printer
130/// flushes it verbatim once the terminal is back in cooked mode.
131///
132/// Dot-prefixed, and deliberately NOT matching the `_summary.`
133/// artifact pattern: artifacts are the `sessiondir` destination,
134/// and their presence must never by itself imply a stdout write.
135pub const DEFERRED_STDOUT_FILE: &str = ".report_stdout.md";
136
137/// Convert the workload-model `SummaryConfig` (parsed from the
138/// `summary:` workload field or the `--summary` CLI flag) into
139/// the SQLite reporter's `ReportConfig`. Used by both the
140/// in-run summary path (workload finished, render to
141/// `summary.md`) and the standalone `nmbrs --summary` command,
142/// so both produce identical output for the same spec.
143pub fn report_config_from_summary(
144    config: &nmbrs_workload::model::SummaryConfig,
145    exec_id_filter: Option<u64>,
146) -> nmbrs_metrics::reporters::sqlite::ReportConfig {
147    nmbrs_metrics::reporters::sqlite::ReportConfig {
148        columns: config.columns.clone(),
149        row_filters: config.row_filters.clone(),
150        aggregates: config
151            .aggregates
152            .iter()
153            .map(|a| nmbrs_metrics::reporters::sqlite::ReportAggregate {
154                function: a.function.to_string(),
155                column_pattern: a.column_pattern.clone(),
156                label_key: a.label_key.clone(),
157                label_pattern: a.label_pattern.clone(),
158                group_by: a.group_by.clone(),
159            })
160            .collect(),
161        show_details: config.show_details,
162        exec_id_filter,
163    }
164}
165
166/// Try to resolve a workload name (bare or with extension) to an
167/// actual file path, searching the current directory and
168/// `./workloads/`. Returns `None` if nothing matches.
169///
170/// Exposed for shell-completion tooling. Application code should
171/// just use [`run_with_observer`] which calls this internally.
172pub fn resolve_workload_file_public(name: &str) -> Option<String> {
173    resolve_workload_file(name)
174}
175
176/// List the scenario names declared at the top level of a workload
177/// YAML file. Used by shell-completion tooling to offer
178/// `scenario=<tab>` suggestions. Returns an empty vector on any
179/// parse error — completion is best-effort, not a hard check.
180pub fn scenarios_in_workload_file(path: &str) -> Vec<String> {
181    let Ok(src) = std::fs::read_to_string(path) else {
182        return Vec::new();
183    };
184    let Ok(doc) = serde_yaml::from_str::<serde_yaml::Value>(&src) else {
185        return Vec::new();
186    };
187    let Some(scenarios) = doc.get("scenarios") else {
188        return Vec::new();
189    };
190    let Some(map) = scenarios.as_mapping() else {
191        return Vec::new();
192    };
193    map.keys()
194        .filter_map(|k| k.as_str().map(String::from))
195        .collect()
196}
197
198/// Run a workload. Adapters are discovered from link-time inventory
199/// registrations — the calling binary just needs to link the adapter
200/// crates it wants available.
201/// Execution depth: how far through the pipeline to go.
202///
203/// Ordering (shallowest → deepest):
204/// `Phase < Dispenser < Op < Cycle < Full`.
205/// `PartialOrd`/`Ord` follow this ordering so depth-gating
206/// sites can write `ctx.diag.depth >= ExecDepth::Cycle` etc.
207#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
208pub enum ExecDepth {
209    /// Compile scope-level kernels, stop before op-template
210    /// kernels / adapter `map_op` / metric instruments. No
211    /// adapters created.
212    Phase,
213    /// `dryrun=dispenser`: phase walk + every op template's
214    /// dispenser is constructed (adapter `map_op` fires; the
215    /// wrapper plan resolves and wraps; the cursor source
216    /// factory is built). NO cycles run. This is the
217    /// construction-time inspection level: catches `map_op`
218    /// failures (bad prepared statement, schema mismatch),
219    /// wrapper-resolver violations, source-factory init
220    /// errors — without paying any per-cycle cost. Distinct
221    /// from `Phase` (which builds NO dispensers) and `Op`
222    /// (which runs full cycles with the wrapper short-
223    /// circuit).
224    Dispenser,
225    /// `dryrun=op`: phase walk + dispenser construction +
226    /// per-cycle wrapper-stack execution. The DRYRUN wrapper
227    /// short-circuits the inner adapter `execute()`; every
228    /// other layer (bind-point eval, wrapper pulls, metric
229    /// timing) runs faithfully. The auto-bump in the runner
230    /// lifts `Op` to `Cycle` so the cycle loop actually
231    /// dispatches.
232    Op,
233    /// Run cycles with dry-run adapter.
234    Cycle,
235    /// Normal execution.
236    Full,
237}
238
239/// Diagnostic configuration parsed from `dryrun=` parameter.
240#[derive(Clone)]
241pub struct DiagnosticConfig {
242    /// How far to execute.
243    pub depth: ExecDepth,
244    /// Emit value-provenance / wiring view: how each named wire
245    /// was computed and where its inputs originated. Surfaced by
246    /// `dryrun=wiring`. (Was previously `dryrun=polydat` — the rename
247    /// keeps the polydat runtime an internal concept; the user-
248    /// facing concept is "wiring" between named values.)
249    pub show_wiring: bool,
250    /// Emit dimensional labels for all phases.
251    pub show_labels: bool,
252    /// Walk the post-construction component tree, render every
253    /// declared dynamic control, and exit. SRD 23 §"Enumeration:
254    /// controls are structural".
255    pub list_controls: bool,
256}
257
258impl DiagnosticConfig {
259    /// Normal execution, no diagnostics.
260    pub fn normal() -> Self {
261        Self {
262            depth: ExecDepth::Full,
263            show_wiring: false,
264            show_labels: false,
265            list_controls: false,
266        }
267    }
268
269    /// Parse from `dryrun=` value (e.g., "phase,wiring" or "cycle").
270    /// If no depth flag (phase/cycle/full) is given, defaults to `Phase`.
271    pub fn parse(spec: &str) -> Self {
272        let mut config = Self::normal();
273        let mut depth_set = false;
274        for flag in spec.split(',') {
275            match flag.trim() {
276                "phase" => {
277                    config.depth = ExecDepth::Phase;
278                    depth_set = true;
279                }
280                "dispenser" => {
281                    config.depth = ExecDepth::Dispenser;
282                    depth_set = true;
283                }
284                "op" => {
285                    config.depth = ExecDepth::Op;
286                    depth_set = true;
287                }
288                "cycle" => {
289                    config.depth = ExecDepth::Cycle;
290                    depth_set = true;
291                }
292                "full" => {
293                    config.depth = ExecDepth::Full;
294                    depth_set = true;
295                }
296                "wiring" => {
297                    // Value-provenance view. Needs depth >= Op for
298                    // kernels to exist; bump depth so a bare
299                    // `dryrun=wiring` produces output instead of
300                    // silently doing nothing.
301                    config.show_wiring = true;
302                    if !depth_set {
303                        config.depth = ExecDepth::Op;
304                        depth_set = true;
305                    }
306                }
307                "labels" => config.show_labels = true,
308                "controls" => {
309                    // Implies an early exit before any phase
310                    // runs — `controls` is a discovery dump, not
311                    // an execution mode.
312                    config.list_controls = true;
313                    config.depth = ExecDepth::Phase;
314                    depth_set = true;
315                }
316                // `emit` / `silent` / `json` are the dryrun output
317                // modes — they live on `ActivityConfig::dry_run_mode`
318                // and drive the dryrun template-parameter injection
319                // that the outermost `DryRunWrapper` keys off. The
320                // runner reads them via a separate
321                // `params.get("dryrun")` lookup below and bumps
322                // depth to Cycle so the cycle path runs. The depth-
323                // config parser tolerates these tokens silently so
324                // an operator passing `dryrun=fields` doesn't see a
325                // misleading "unknown flag" warning.
326                "fields" | "silent" | "json" => {}
327                // `dryrun=kernels` is a planning-only mode — it
328                // builds the scope tree, then walks every
329                // materialised scope and prints its polydat
330                // source. Depth stays at Phase; the runner
331                // dispatches to a kernel-dump short-circuit
332                // before any phase activation.
333                "kernels" => {}
334                _ => crate::diag!(
335                    crate::observer::LogLevel::Warn,
336                    "warning: unknown dryrun flag '{flag}'"
337                ),
338            }
339        }
340        // Default to phase depth if no explicit depth was given
341        if !depth_set {
342            config.depth = ExecDepth::Phase;
343        }
344        config
345    }
346}
347
348/// Walk a component subtree and print every declared control
349/// (name, type, current value, scope, final flag, applier
350/// count) in a stable order. Used by `dryrun=controls` and any
351/// other discovery-style call site.
352pub fn render_controls_tree(
353    root: &std::sync::Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
354    out: &mut dyn std::io::Write,
355) -> std::io::Result<()> {
356    use nmbrs_metrics::component::find;
357    use nmbrs_metrics::selector::Selector;
358
359    writeln!(out, "Declared dynamic controls (SRD 23):")?;
360    let all = find(root, &Selector::new());
361    let mut entries: Vec<(String, String, String, String, String, String)> = Vec::new();
362    for comp in all {
363        let guard = match comp.read() {
364            Ok(g) => g,
365            Err(_) => continue,
366        };
367        let path = guard
368            .effective_labels()
369            .iter()
370            .map(|(k, v)| format!("{k}={v}"))
371            .collect::<Vec<_>>()
372            .join(",");
373        for ctl in guard.controls().list() {
374            let scope = match ctl.branch_scope() {
375                nmbrs_metrics::controls::BranchScope::Local => "local",
376                nmbrs_metrics::controls::BranchScope::Subtree => "subtree",
377            };
378            let final_marker = match ctl.final_scope() {
379                Some(s) => format!("final@{s}"),
380                None => "-".to_string(),
381            };
382            entries.push((
383                if path.is_empty() {
384                    "<root>".into()
385                } else {
386                    path.clone()
387                },
388                ctl.name().to_string(),
389                ctl.value_type_name().to_string(),
390                ctl.value_string(),
391                format!(
392                    "scope={scope}, {final_marker}, appliers={}",
393                    ctl.applier_count()
394                ),
395                if ctl.accepts_f64_writes() {
396                    "f64-writable".into()
397                } else {
398                    "no-f64".into()
399                },
400            ));
401        }
402    }
403    if entries.is_empty() {
404        writeln!(out, "  (no controls declared)")?;
405        return Ok(());
406    }
407    entries.sort();
408    for (path, name, ty, value, meta, write) in entries {
409        writeln!(
410            out,
411            "  {path}\n    {name}: {value}  [{ty}]  {meta}  {write}",
412        )?;
413    }
414    Ok(())
415}
416
417/// Render the SRD-13d scope-elision summary for `dryrun=op`.
418/// One line per scope-tree node (DFS pre-order), showing the
419/// logical name and the materialised/elides-to mark.
420///
421/// Format follows SRD-13d §5.3:
422/// ```text
423/// scope elision summary
424/// ------------------------
425/// workload                                           materialised=true
426/// workload.scenario.default                          materialised=false  elides-to=workload
427/// workload.scenario.default.phase.predict            materialised=true
428/// ```
429///
430/// `materialised=true` means the node owns a kernel; `false`
431/// means it elides into its nearest materialised ancestor
432/// (shown as `elides-to=<logical_name>`). Nodes whose mark
433/// is still `None` (predicate hasn't fired — should not
434/// happen post-`classify_and_mark`) are surfaced as `unknown`
435/// rather than silently skipped.
436pub fn render_scope_elision_summary(
437    tree: &crate::scope_tree::ScopeTree,
438    out: &mut dyn std::io::Write,
439) -> std::io::Result<()> {
440    let summary = crate::scope_elision::elision_summary(tree);
441    // Width of the logical-name column — 4-space gutter past
442    // the longest name (or 48ch min) so the materialised marks
443    // line up cleanly even with deeply-nested phase trees.
444    let name_width = summary
445        .iter()
446        .map(|(_, _, _, name, _)| name.len())
447        .max()
448        .unwrap_or(0)
449        .max(48);
450
451    writeln!(out, "scope elision summary")?;
452    writeln!(out, "------------------------")?;
453    for (idx, _depth, materialised, logical_name, _kind) in &summary {
454        match materialised {
455            Some(true) => {
456                writeln!(
457                    out,
458                    "{:<width$}    materialised=true",
459                    logical_name,
460                    width = name_width
461                )?;
462            }
463            Some(false) => {
464                let elides_to = tree
465                    .nearest_materialised(*idx)
466                    .map(|p| tree.nodes[p].logical_name.clone())
467                    .unwrap_or_else(|| "<unknown>".to_string());
468                writeln!(
469                    out,
470                    "{:<width$}    materialised=false  elides-to={}",
471                    logical_name,
472                    elides_to,
473                    width = name_width
474                )?;
475            }
476            None => {
477                writeln!(
478                    out,
479                    "{:<width$}    materialised=unknown",
480                    logical_name,
481                    width = name_width
482                )?;
483            }
484        }
485    }
486    Ok(())
487}
488
489pub async fn run(args: &[String]) -> Result<(), String> {
490    // Default tui=off observer — stderr with the same Info-level
491    // filter the TUI's log panel applies by default. `loglevel=`
492    // CLI param overrides; absent means Info.
493    //
494    // We need to peek at one CLI param before kicking off the
495    // full runner pipeline. Strip a leading `run` subcommand the
496    // same way `run_with_observer` does at its own param-parse
497    // step, so this peek doesn't reject perfectly valid CLI
498    // shapes (`nmbrs run loglevel=debug …`).
499    let stripped: &[String] = match args.first().map(|s| s.as_str()) {
500        Some("run") => &args[1..],
501        _ => args,
502    };
503    let cli_params = parse_params(stripped);
504    let min_level = cli_params
505        .get("loglevel")
506        .or_else(|| cli_params.get("loglevel-display"))
507        .or_else(|| cli_params.get("loglevel_display"))
508        .and_then(|s| parse_log_level(s))
509        .unwrap_or(crate::observer::LogLevel::Info);
510    let retain_level = cli_params
511        .get("loglevel-retain")
512        .or_else(|| cli_params.get("loglevel_retain"))
513        .and_then(|s| parse_log_level(s))
514        .unwrap_or(crate::observer::LogLevel::Debug);
515    crate::observer::set_retain_level(retain_level);
516    crate::observer::set_display_level(min_level);
517    run_with_observer(
518        args,
519        Arc::new(crate::observer::StderrObserver::with_min_level(min_level)),
520    )
521    .await
522}
523
524/// Parse a CLI/workload `loglevel=` value. Case-insensitive,
525/// accepts the standard names plus the abbreviations the log
526/// sink emits (`DBG` / `INF` / `WRN` / `ERR`).
527pub fn parse_log_level(s: &str) -> Option<crate::observer::LogLevel> {
528    use crate::observer::LogLevel;
529    match s.trim().to_ascii_lowercase().as_str() {
530        "trace" | "trc" => Some(LogLevel::Trace),
531        "debug" | "dbg" => Some(LogLevel::Debug),
532        "info" | "inf" => Some(LogLevel::Info),
533        "warn" | "wrn" | "warning" => Some(LogLevel::Warn),
534        "error" | "err" => Some(LogLevel::Error),
535        _ => None,
536    }
537}
538
539/// Run with a custom observer for phase lifecycle events.
540/// The TUI persona uses this to inject a TuiObserver that updates
541/// the display state instead of printing to stderr.
542pub async fn run_with_observer(
543    args: &[String],
544    observer: Arc<dyn crate::observer::RunObserver>,
545) -> Result<(), String> {
546    let args: &[String] = match args.first().map(|s| s.as_str()) {
547        Some("run") => &args[1..],
548        // Reject unknown subcommands — don't silently fall through to execution
549        Some(cmd) if !cmd.contains('=') && !cmd.ends_with(".yaml") && !cmd.ends_with(".yml") => {
550            return Err(format!(
551                "unknown command '{cmd}'. Use 'run' or pass a workload file."
552            ));
553        }
554        _ => args,
555    };
556    // Reject conflicting duplicate `key=value` params (e.g. two
557    // different `scenario=` values) before any work — otherwise the
558    // last silently wins. Errors here, before session creation.
559    detect_conflicting_duplicate_params(args)?;
560    run_impl(args, observer).await
561}
562
563/// The session-level metrics services [`build_session_metrics`] builds.
564struct SessionMetrics {
565    cadence_reporter: std::sync::Arc<nmbrs_metrics::cadence_reporter::CadenceReporter>,
566    cadence_tree: nmbrs_metrics::cadence::CadenceTree,
567    metrics_query: std::sync::Arc<nmbrs_metrics::metrics_query::MetricsQuery>,
568    /// Stops the metrics scheduler.
569    stop_handle: std::sync::Arc<nmbrs_metrics::scheduler::StopHandle>,
570}
571
572/// SRD-88 — build the session-level metrics services: the cadence
573/// tree + reporter, the shared `MetricsQuery`, and the metrics
574/// scheduler (whose `StopHandle` is returned). One set per session;
575/// every execution sharing the session routes through these. Reads
576/// the session component (capture root), the sqlite reporter (cadence
577/// subscription), and the observer (cadence prefs + live reporters).
578fn build_session_metrics(
579    session: &crate::session::Session,
580    sqlite_reporter: &std::sync::Arc<
581        std::sync::Mutex<Option<nmbrs_metrics::reporters::sqlite::SqliteReporter>>,
582    >,
583    observer: &Arc<dyn crate::observer::RunObserver>,
584    merged_params: &HashMap<String, String>,
585    openmetrics_url: &Option<String>,
586    args: &[String],
587    params: &HashMap<String, String>,
588) -> Result<SessionMetrics, String> {
589    // `metrics_cadence` (effective param) may set a sub-second finest
590    // cadence + base interval; otherwise the default 1 s base + declared
591    // cadences. The base interval drives both the cadence tree and the
592    // scheduler tick below, so the finest cadence the settle detector
593    // samples and the capture pulse stay in lockstep.
594    let (base_interval, cadences) = resolve_cadence_config(merged_params, observer)?;
595    let cadence_tree = nmbrs_metrics::cadence::CadenceTree::plan_validated(
596        cadences,
597        nmbrs_metrics::cadence::DEFAULT_MAX_FAN_IN,
598        base_interval,
599    )
600    .map_err(|e| format!("cadence tree: {e}"))?;
601    let cadence_reporter = Arc::new(nmbrs_metrics::cadence_reporter::CadenceReporter::new(
602        cadence_tree.clone(),
603    ));
604    let metrics_query = Arc::new(nmbrs_metrics::metrics_query::MetricsQuery::new(
605        cadence_reporter.clone(),
606        session.component.clone(),
607    ));
608    session.set_metrics_query(metrics_query.clone());
609    nmbrs_metrics::polydat_nodes::set_global_query(metrics_query.clone());
610    // SRD-86 §"The metric-reader surface" / SRD-90 §M5 — install the live
611    // in-process metrics-access service the `metricsql_*` nodes locate via
612    // `queryapi::live_access()`. It is a HYBRID (SRD-90): the in-memory cadence
613    // tier (fine, recent, retention-bounded) over the session's durable sqlite
614    // store (coarse, the older tail), composed by union-minus-overlap — a recent
615    // windowed read is served entirely from memory (the common case never opens
616    // sqlite), and a query older than the in-memory horizon spills to the
617    // durable tail. Both tiers scope to the reading execution (mem via the
618    // read-exec hook; cold via `CurrentReadExec`), so a concurrent spill never
619    // leaks a neighbour's series. Best-effort: if the sqlite tail can't be
620    // opened (sqlite disabled, db absent), the live service is the mem tier
621    // alone — byte-identical to before this seam.
622    let mem_access = std::sync::Arc::new(nmbrs_metrics::queryapi::MetricsQueryAccess::new(
623        metrics_query.clone(),
624    ));
625    // The composed read store: the in-memory cadence tier over the durable
626    // sqlite tail (union-minus-overlap). The cold tier reads `All` executions
627    // at the SQL level — per-execution scoping is the injected `exec_id`
628    // dimensional label (below), uniform across both tiers.
629    let composed: std::sync::Arc<dyn nmbrs_metrics::queryapi::MetricAccess> = {
630        let db = session.output_dir.join("metrics.db");
631        match nmbrs_metrics::queryapi::sqlite::SqliteDataSource::open(&db) {
632            Ok(cold) => {
633                let cold = cold.with_execution_selection(
634                    nmbrs_metrics::queryapi::sqlite::ExecutionSelection::All,
635                );
636                let mem_for_horizon = mem_access.clone();
637                std::sync::Arc::new(nmbrs_metrics::queryapi::HybridStore::new(vec![
638                    nmbrs_metrics::queryapi::Tier::new(
639                        mem_access.clone(),
640                        std::sync::Arc::new(move || mem_for_horizon.earliest_ms()),
641                    ),
642                    nmbrs_metrics::queryapi::Tier::unbounded(std::sync::Arc::new(cold)),
643                ]))
644            }
645            Err(e) => {
646                crate::diag!(
647                    crate::observer::LogLevel::Debug,
648                    "metrics: hybrid sqlite tail unavailable ({e}); live reads are in-memory only"
649                );
650                mem_access.clone()
651            }
652        }
653    };
654    // SRD-89 §3b / SRD-90 §M6 — scope every live read to its execution via the
655    // `exec_id` dimensional-label matcher, applied uniformly to both tiers.
656    nmbrs_metrics::queryapi::install_live_access(std::sync::Arc::new(
657        nmbrs_metrics::queryapi::ExecScopedAccess::new(composed),
658    ));
659    // SRD-88 — teach the live-metric reader which execution is asking, so
660    // its reads scope to that execution's own series (the store is shared
661    // across concurrent executions). The hook reads nmbrs-runtime's
662    // task-local execution context; `None` outside any scope (single-run).
663    nmbrs_metrics::queryapi::install_read_exec_id_hook(|| {
664        crate::execution_context::try_current().map(|c| c.exec_id)
665    });
666    observer.on_metrics_query(metrics_query.clone());
667
668    let session_for_capture = session.component.clone();
669    let mut sched_builder = nmbrs_metrics::scheduler::SchedulerBuilder::new()
670        .base_interval(base_interval)
671        .with_cadence_reporter(cadence_reporter.clone())
672        .with_cadence_tree(cadence_tree.clone());
673
674    // SRD-42 §"SQLite — near-time persistence": subscribe the
675    // SQLite reporter via the CadenceReporter push path so slow
676    // disk can't stall the cascade. The subscription runs on its
677    // own dispatch thread with a per-subscription timeout.
678    //
679    // Preferred write cadence is 30 s — coarse enough to keep
680    // write volume low for long runs, fine enough for post-run
681    // analysis. Aligns to the nearest declared cadence ≥ 30 s
682    // (default declared set includes 30 s so this resolves exactly).
683    // Journal mode is WAL (set in SqliteReporter::new via
684    // `PRAGMA journal_mode=WAL`), so readers never block writers.
685    //
686    // Always-on: this subscription fires whenever the SQLite
687    // reporter was constructed successfully. Operators don't need
688    // to opt in with any extra param — every run produces a
689    // `metrics.db` in its session directory by default.
690    let sqlite_cadence = cadence_tree.align_to_declared(std::time::Duration::from_secs(30));
691    if let (Some(cadence), Ok(guard)) = (sqlite_cadence, sqlite_reporter.lock())
692        && guard.is_some()
693    {
694        drop(guard);
695        let sqlite_for_sub = sqlite_reporter.clone();
696        match cadence_reporter.subscribe(
697            cadence,
698            Box::new(MutexReporter(sqlite_for_sub)),
699            nmbrs_metrics::cadence_reporter::SubscriptionOpts::default(),
700        ) {
701            Ok(_) => {
702                crate::diag!(
703                    crate::observer::LogLevel::Info,
704                    "metrics: SQLite writes every {:?} (WAL mode)",
705                    cadence
706                );
707            }
708            Err(e) => {
709                crate::diag!(
710                    crate::observer::LogLevel::Warn,
711                    "metrics: SQLite subscription failed: {e}"
712                );
713            }
714        }
715    }
716
717    // Single-file metrics log — opt-in, for OUTSIDE OBSERVERS. The session
718    // SQLite db is always written and stays the system of record; this only
719    // duplicates the same coalesced cadence windows into one plain JSONL file so
720    // a process can tail or ship metrics without linking SQLite, opening a db
721    // another process is writing in WAL mode, or knowing the schema. Enable via
722    // any of (a path enables it; `true` uses `<session>/metrics.jsonl`):
723    //   * `--metrics-log[=<path>]` flag on the CLI
724    //   * `metrics-log=<path|true>` in workload params
725    //   * `NMBRS_METRICS_LOG=<path|true>` env var
726    // Tell display surfaces where the session lives, so the one that keeps a
727    // durable transcript can open it and flush what it buffered before the
728    // directory existed. Default-on: the settled half of the display is
729    // already sequenced, append-only data, so persisting it costs one file
730    // handle and answers "what did the run actually show me" after the fact.
731    observer.session_dir_ready(&session.output_dir);
732
733    // Session-level system-performance sampler (SRD-118). Enabled per
734    // session with `sysmon=`; off when absent. A named category is
735    // REQUIRED: a host that cannot supply it aborts the session with
736    // instructions rather than silently monitoring less than was asked
737    // for. `sysmon=any` takes what the host has and says what it left
738    // out.
739    crate::sysmon_params::start(params, &session.component, observer)?;
740
741    let metrics_log_setting: Option<String> = args
742        .iter()
743        .find_map(|a| {
744            a.strip_prefix("--metrics-log")
745                .map(|rest| rest.strip_prefix('=').unwrap_or("true").to_string())
746        })
747        .or_else(|| params.get("metrics-log").cloned())
748        .or_else(|| std::env::var("NMBRS_METRICS_LOG").ok());
749    // `true` / `false`, or a file path. A retired boolean spelling
750    // (`on`, `1`, …) is an error naming the canonical word, never a
751    // file named `on`.
752    let metrics_log_path = match metrics_log_setting.as_deref() {
753        None | Some("false") => None,
754        Some("true") => Some(session.output_dir.join("metrics.jsonl")),
755        Some(retired @ ("on" | "off" | "yes" | "no" | "1" | "0" | "")) => {
756            return Err(format!(
757                "metrics-log={retired}: write metrics-log=true, metrics-log=false, \
758                 or metrics-log=<path>"
759            ));
760        }
761        Some(explicit) => {
762            // An explicit path from the `--metrics-log=` FLAG is the
763            // operator's own and is taken verbatim. The `metrics-log`
764            // PARAM (a workload file can set it) and the env form are
765            // confined to the session directory: a shared workload
766            // must never be able to name a write target elsewhere.
767            let from_flag = args.iter().any(|a| a.starts_with("--metrics-log"));
768            if from_flag {
769                Some(std::path::PathBuf::from(explicit))
770            } else {
771                Some(crate::session::confine_to_dir(&session.output_dir, explicit).map_err(
772                    |e| format!("metrics-log: {e} (an explicit path outside the session directory is only accepted from the --metrics-log= flag)"),
773                )?)
774            }
775        }
776    };
777    if let Some(log_path) = metrics_log_path {
778        match nmbrs_metrics::reporters::metrics_log::MetricsLogReporter::new(&log_path) {
779            Ok(reporter) => {
780                // Same cadence as the database, deliberately: the log is an
781                // alternative READ of what the db holds, so matching granularity
782                // is what makes the two comparable.
783                if let Some(cadence) =
784                    cadence_tree.align_to_declared(std::time::Duration::from_secs(30))
785                {
786                    match cadence_reporter.subscribe(
787                        cadence,
788                        Box::new(reporter),
789                        nmbrs_metrics::cadence_reporter::SubscriptionOpts::default(),
790                    ) {
791                        Ok(_) => {
792                            crate::diag!(
793                                crate::observer::LogLevel::Info,
794                                "metrics: JSONL log every {:?} -> {} (session db unaffected)",
795                                cadence,
796                                log_path.display()
797                            );
798                        }
799                        Err(e) => {
800                            crate::diag!(
801                                crate::observer::LogLevel::Warn,
802                                "metrics: metrics log subscribe failed: {e}"
803                            );
804                        }
805                    }
806                }
807            }
808            Err(e) => {
809                crate::diag!(
810                    crate::observer::LogLevel::Warn,
811                    "metrics: metrics log disabled: {e}"
812                );
813            }
814        }
815    }
816
817    // Per-instance JSONL snapshot reporter — opt-in. Writes
818    // one file per (metric, label-tuple) in `<session>/metrics/`,
819    // one JSON record appended per snapshot tick. Useful when
820    // you want a per-instance trace to tail / awk / import
821    // into a notebook without opening the SQLite db, but most
822    // sessions never read these files and the SQLite db
823    // already carries the same data. Enable via any of:
824    //   * `--per-instance-metrics` flag on the CLI
825    //   * `per-instance-metrics=true` in workload params
826    //   * `NMBRS_PER_INSTANCE_METRICS=true` env var
827    let per_instance_enabled = args.iter().any(|a| a == "--per-instance-metrics")
828        || params.get("per-instance-metrics").map_or(Ok(false), |s| {
829            nmbrs_workload::boolean::parse_bool("per-instance-metrics", s)
830        })?
831        || nmbrs_workload::boolean::env_flag("NMBRS_PER_INSTANCE_METRICS")?;
832    if per_instance_enabled {
833        let per_instance_dir = session.output_dir.join("metrics");
834        match nmbrs_metrics::reporters::per_instance::PerInstanceReporter::new(&per_instance_dir) {
835            Ok(reporter) => {
836                if let Some(cadence) =
837                    cadence_tree.align_to_declared(std::time::Duration::from_secs(30))
838                {
839                    match cadence_reporter.subscribe(
840                        cadence,
841                        Box::new(reporter),
842                        nmbrs_metrics::cadence_reporter::SubscriptionOpts::default(),
843                    ) {
844                        Ok(_) => {
845                            crate::diag!(
846                                crate::observer::LogLevel::Info,
847                                "metrics: per-instance JSONL writes every {:?} into {}",
848                                cadence,
849                                per_instance_dir.display()
850                            );
851                        }
852                        Err(e) => {
853                            crate::diag!(
854                                crate::observer::LogLevel::Warn,
855                                "metrics: per-instance subscription failed: {e}"
856                            );
857                        }
858                    }
859                }
860            }
861            Err(e) => {
862                crate::diag!(
863                    crate::observer::LogLevel::Warn,
864                    "metrics: per-instance reporter disabled ({}): {e}",
865                    per_instance_dir.display()
866                );
867            }
868        }
869    }
870
871    // Same routing for the VictoriaMetrics / Prometheus push reporter
872    // when `--report-to` (or equivalent param) was provided.
873    // `jobname` / `instance` params match the nosqlbench-java
874    // `PromPushReporterComponent` convention; they're substituted
875    // into any `JOBNAME` / `INSTANCE` placeholders in the URL.
876    if let Some(url) = openmetrics_url.as_ref()
877        && let Some(cadence) = cadence_tree.align_to_declared(std::time::Duration::from_secs(10))
878    {
879        let jobname = merged_params
880            .get("jobname")
881            .cloned()
882            .unwrap_or_else(|| "default".to_string());
883        let instance = merged_params
884            .get("instance")
885            .cloned()
886            .unwrap_or_else(|| "default".to_string());
887        let mut vm =
888            match nmbrs_metrics::reporters::victoriametrics::VictoriaMetricsReporter::from_spec(url)
889            {
890                Ok(r) => r,
891                Err(_) => {
892                    nmbrs_metrics::reporters::victoriametrics::VictoriaMetricsReporter::new(url)
893                }
894            };
895        vm = vm.with_jobname(jobname).with_instance(instance);
896        if let Some(token_path) = merged_params.get("prompush_apikeyfile") {
897            match vm.with_bearer_token_file(token_path) {
898                Ok(r) => vm = r,
899                Err(e) => {
900                    crate::diag!(
901                        crate::observer::LogLevel::Warn,
902                        "prompush_apikeyfile '{token_path}': {e}"
903                    );
904                    vm = nmbrs_metrics::reporters::victoriametrics
905                            ::VictoriaMetricsReporter::from_spec(url)
906                            .unwrap_or_else(|_| nmbrs_metrics::reporters::victoriametrics
907                                ::VictoriaMetricsReporter::new(url))
908                            .with_jobname(
909                                merged_params.get("jobname").cloned()
910                                    .unwrap_or_else(|| "default".to_string()),
911                            )
912                            .with_instance(
913                                merged_params.get("instance").cloned()
914                                    .unwrap_or_else(|| "default".to_string()),
915                            );
916                }
917            }
918        }
919        let _ = cadence_reporter.subscribe(
920            cadence,
921            Box::new(vm),
922            nmbrs_metrics::cadence_reporter::SubscriptionOpts::default(),
923        );
924    }
925
926    // Register the observer's reporters at their requested cadences
927    // on the scheduler tree (base-interval live-frame forwarding for
928    // sparklines / live histogram).
929    for (interval, reporter) in observer.reporters() {
930        sched_builder = sched_builder.add_reporter(interval, BoxedReporter(reporter));
931    }
932
933    let scheduler = sched_builder.build(Box::new(move || {
934        nmbrs_metrics::component::capture_tree(&session_for_capture, base_interval)
935    }));
936    let stop_handle = Arc::new(scheduler.start());
937
938    // Install the session-wide Ctrl-C handler. First SIGINT
939    // requests cooperative shutdown (fibers exit at cycle
940    // boundary, profiler + cadence reporter flush in normal
941    // teardown order); second SIGINT force-exits. Idempotent —
942    // safe to call again on retry / reentry paths.
943    crate::session_signals::install_signal_handler();
944
945    // SRD-93 M7 — SIGQUIT inventory: log every Running component's
946    // labels + instrument count, so "why is nothing moving" is
947    // answerable from outside even when the run is wedged. Runs on
948    // the signal-dispatch thread; read-only over the tree.
949    let dump_root = session.component.clone();
950    crate::session_signals::set_diag_dump_hook(Box::new(move || {
951        fn walk(
952            node: &std::sync::Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
953            out: &mut Vec<String>,
954        ) {
955            let g = node.read().unwrap_or_else(|e| e.into_inner());
956            if g.state() == nmbrs_metrics::component::ComponentState::Running {
957                out.push(format!(
958                    "{} ({} instrument(s))",
959                    g.effective_labels(),
960                    g.instruments().len(),
961                ));
962            }
963            for child in g.children() {
964                walk(child, out);
965            }
966        }
967        let mut lines = Vec::new();
968        walk(&dump_root, &mut lines);
969        crate::diag!(
970            crate::observer::LogLevel::Info,
971            "session: SIGQUIT inventory — {} running component(s)",
972            lines.len()
973        );
974        for line in lines {
975            crate::diag!(crate::observer::LogLevel::Info, "  {line}");
976        }
977    }));
978
979    Ok(SessionMetrics {
980        cadence_reporter,
981        cadence_tree,
982        metrics_query,
983        stop_handle,
984    })
985}
986
987/// SRD-88 — the shared, session-tier context, created ONCE per session
988/// (`SessionHost::setup`); every execution sharing the session runs
989/// against it. Holds the session (dir / id / `session` component), the
990/// durable sqlite store + shutdown guard, the session-aligned metrics
991/// services and the session-tier profiler. Per-execution work +
992/// workload load happens in `run_execution`.
993struct SessionHost {
994    session: crate::session::Session,
995    sqlite_reporter:
996        std::sync::Arc<std::sync::Mutex<Option<nmbrs_metrics::reporters::sqlite::SqliteReporter>>>,
997    cadence_reporter: std::sync::Arc<nmbrs_metrics::cadence_reporter::CadenceReporter>,
998    #[allow(dead_code)]
999    cadence_tree: nmbrs_metrics::cadence::CadenceTree,
1000    #[allow(dead_code)]
1001    metrics_query: std::sync::Arc<nmbrs_metrics::metrics_query::MetricsQuery>,
1002    stop_handle: std::sync::Arc<nmbrs_metrics::scheduler::StopHandle>,
1003    refine_plan: Option<Arc<crate::refine_plan::RefinePlan>>,
1004    resume_target: Option<std::path::PathBuf>,
1005    refine_requested: bool,
1006    refine_scope: Option<String>,
1007    /// SRD-106 — the session id the `stick_session` rung
1008    /// re-attached to, when it engaged. Drives the D4
1009    /// `session_notice` announcement (first notable event of
1010    /// the run) and nothing else.
1011    stick_reattached: Option<String>,
1012    profiler: Option<crate::profiler::ProfileGuard>,
1013    sqlite_guard: nmbrs_metrics::reporters::sqlite::SqliteShutdownGuard,
1014    /// SRD-88 — the checkpoint writer is SESSION-tier: one per session
1015    /// (`<session>/checkpoint.jsonl` + its single resume lock), shared
1016    /// by every execution. Per-execution resume *plans* are still
1017    /// derived per execution in `run_execution` from `saved_doc` + that
1018    /// execution's pre-map; only the writer/lock is shared (so N
1019    /// concurrent in-process executions don't fight over the lock).
1020    checkpoint_writer: std::sync::Arc<crate::checkpoint::CheckpointWriter>,
1021    saved_doc: Option<crate::checkpoint::Checkpoint>,
1022}
1023
1024impl SessionHost {
1025    /// Build the shared session-tier context. Workload-INDEPENDENT:
1026    /// session identity = `scenario=` param; metrics services +
1027    /// profiler read CLI `params`, not workload-merged params.
1028    fn setup(
1029        args: &[String],
1030        observer: Arc<dyn crate::observer::RunObserver>,
1031    ) -> Result<SessionHost, String> {
1032        // Set global observer so all code can log through it
1033        crate::observer::set_global_observer(observer.clone());
1034
1035        // Wire error handler logging through the observer.
1036        // Per-cycle error lines fire from inside an executing
1037        // phase, so prefix with the running phase's scope-depth
1038        // indent — the same alignment the polling-op messages,
1039        // phase startup/complete lines, and DONE summary use.
1040        // The errorhandler crate stays scope-agnostic; the
1041        // bridging closure here is what makes the output
1042        // hierarchic in tui=terminal mode.
1043        //
1044        // Level = Debug so the per-cycle warns land in the
1045        // session log (retain_level defaults to Debug) but
1046        // don't spam the realtime status surface (display_level
1047        // defaults to Info). The structured form of each
1048        // per-cycle error is collected into the phase's
1049        // PhaseErrorDetail buffer and rendered in one block by
1050        // the `error_readout` builtin at PhaseEnd — the
1051        // operator sees the normative ✓/✗ phase line first,
1052        // then the error block, instead of N noisy lines
1053        // interleaved with progress as the phase runs.
1054        nmbrs_errorhandler::handlers::set_log_fn(|msg| {
1055            let indent = crate::scene_tree::running_phase_indent();
1056            crate::observer::log(crate::observer::LogLevel::Debug, &format!("{indent}{msg}"));
1057        });
1058
1059        // Route nmbrs-metrics diagnostic warnings through the observer so
1060        // reporter write failures, histogram-record errors, etc. don't
1061        // slip past the TUI as raw stderr prints. Indent matches the
1062        // running phase the same way the errorhandler bridge above does
1063        // — these emits fire mid-phase from the metrics pipeline.
1064        nmbrs_metrics::diag::set_warn_fn(|msg| {
1065            let indent = crate::scene_tree::running_phase_indent();
1066            crate::observer::log(crate::observer::LogLevel::Warn, &format!("{indent}{msg}"));
1067        });
1068        nmbrs_metrics::diag::set_info_fn(|msg| {
1069            let indent = crate::scene_tree::running_phase_indent();
1070            crate::observer::log(crate::observer::LogLevel::Info, &format!("{indent}{msg}"));
1071        });
1072
1073        // Audit sink is installed after session creation
1074        // below (so it can target `<session>/audit.log`).
1075        // Until then, the crate-default eprintln fallback
1076        // is in effect for any audit::log calls fired
1077        // during init. Workload-emitted lines fire mid-phase
1078        // (well after the install), so they don't reach
1079        // stderr.
1080
1081        let args = normalize_args(args);
1082        let params = parse_params(&args);
1083        // The run's effective params (workload `params:` overlaid by CLI, CLI
1084        // wins) — the consolidated set the session-tier services read, so a
1085        // setting like `metrics_cadence` / `jobname` / `per-instance-metrics`
1086        // works whether declared in the workload or passed on the command line.
1087        // Operational reads below (resume, session identity) stay on the raw CLI
1088        // `params` — they are not workload-declarable.
1089        let eff_params = effective_params(&args);
1090        // `scenario_for_session` is recomputed below from the refine block's
1091        // params (the session-dir name); `openmetrics_url` feeds the
1092        // session metrics services.
1093        let openmetrics_url: Option<String> = cli_flag_value(&args[..], "--report-openmetrics-to")
1094            .or_else(|| {
1095                args.iter()
1096                    .find_map(|a| a.strip_prefix("report-openmetrics-to="))
1097                    .map(|s| s.to_string())
1098            });
1099        // SRD-106 Part 3 — the `stick_session` resolution rung: the
1100        // LOWEST-precedence session rung. A workload may declare that
1101        // iterative re-attachment is its intended usage; when the
1102        // operator expressed no session intent of their own, a run
1103        // re-attaches to `sessions/latest` and layers a new execution
1104        // per SRD-77 — mechanically the refine path, so the D2
1105        // provenance gates govern what re-runs. Defeated by ANY
1106        // explicit session selection (`--session*` name/path/reuse),
1107        // any re-attachment flag (`resume=` / `--resume-latest` /
1108        // `--refine`), the `--session new` bare token, and dryruns
1109        // (resume-inert per SRD-44). CLI `stick_session=true|false`
1110        // overrides the workload's declaration.
1111        let stick_reattach: Option<std::path::PathBuf> = {
1112            let cli_stick: Option<bool> = params
1113                .get("stick_session")
1114                .map(|v| nmbrs_workload::boolean::parse_bool("stick_session", v))
1115                .transpose()?;
1116            let stick_on =
1117                cli_stick.unwrap_or_else(|| peek_stick_session(&params, &args).unwrap_or(false));
1118            let reattach_expressed = args
1119                .iter()
1120                .any(|a| a == "--refine" || a == "--resume-latest")
1121                || params.contains_key("resume")
1122                || params.contains_key("resume_latest");
1123            if !stick_on || reattach_expressed || crate::session::args_request_dryrun(&args) {
1124                None
1125            } else {
1126                let spec = crate::session::resolve_session_dir(&args);
1127                let operator_selected = !spec.is_empty()
1128                    || spec.force_new
1129                    || spec.reuse != crate::session::SessionReuse::Error;
1130                if operator_selected {
1131                    None
1132                } else {
1133                    // `sessions/latest` must resolve to a prior session
1134                    // with a checkpoint — anything less means there is
1135                    // nothing valid to re-attach to, and the run falls
1136                    // through to today's fresh-session default silently
1137                    // (no announcement for a no-op).
1138                    let latest = crate::session::default_sessions_root().join("latest");
1139                    std::fs::read_link(&latest)
1140                        .ok()
1141                        .map(|t| {
1142                            if t.is_absolute() {
1143                                t
1144                            } else {
1145                                crate::session::default_sessions_root().join(t)
1146                            }
1147                        })
1148                        .filter(|d| d.join("checkpoint.jsonl").is_file())
1149                }
1150            }
1151        };
1152        let stick_reattached: Option<String> = stick_reattach
1153            .as_ref()
1154            .and_then(|d| d.file_name())
1155            .and_then(|s| s.to_str())
1156            .map(String::from);
1157        if let Some(id) = stick_reattached.as_deref() {
1158            crate::diag!(
1159                crate::observer::LogLevel::Info,
1160                "stick_session: re-attaching to {id} — pass `--session new` to start fresh"
1161            );
1162        }
1163
1164        let resume_target: Option<std::path::PathBuf> = {
1165            let explicit = params.get("resume").filter(|s| !s.is_empty()).map(|s| {
1166                let p = std::path::PathBuf::from(s);
1167                if p.is_file() {
1168                    p
1169                } else if p.is_dir() {
1170                    p.join("checkpoint.jsonl")
1171                } else {
1172                    crate::session::default_sessions_root()
1173                        .join(s)
1174                        .join("checkpoint.jsonl")
1175                }
1176            });
1177            let resume_latest = params.get("resume_latest").map_or(Ok(false), |s| {
1178                nmbrs_workload::boolean::parse_bool("resume_latest", s)
1179            })? || args.iter().any(|a| a == "--resume-latest")
1180                || stick_reattach.is_some();
1181            if resume_latest {
1182                // Resolve the symlink to a concrete session dir
1183                // *now* — once `Session::new` runs the symlink will
1184                // be repointed at the new session.
1185                let latest = crate::session::default_sessions_root().join("latest");
1186                let resolved = std::fs::read_link(&latest)
1187                    .ok()
1188                    .map(|target| {
1189                        if target.is_absolute() {
1190                            target
1191                        } else {
1192                            crate::session::default_sessions_root().join(target)
1193                        }
1194                    })
1195                    .map(|d| d.join("checkpoint.jsonl"));
1196                explicit.or(resolved)
1197            } else {
1198                explicit
1199            }
1200        };
1201
1202        // SRD-77 refine: the `nmbrs refine` verb injects `--refine`
1203        // into argv before delegating to the runner. Detected here
1204        // so we can load the session's prior `phase_outcomes` and
1205        // build a skip plan + bump `exec_id` before the session is
1206        // re-attached. Implies `--resume-latest` semantics for
1207        // session dir resolution (the resolver at line 950+ already
1208        // produces the right `resume_target` when `--resume-latest`
1209        // was passed alongside `--refine` by `refine_command`).
1210        // SRD-106: an engaged `stick_session` re-attach IS a refine
1211        // layering — new execution, prior outcomes as provenance.
1212        let refine_requested = args.iter().any(|a| a == "--refine") || stick_reattach.is_some();
1213
1214        // Session: root context for this run. Creates logs/{scenario}_{timestamp}/
1215        // for fresh runs; reuses the prior session dir when resuming
1216        // so the metrics.db is appended-to in-place per SRD-44
1217        // §"Wholesale metrics-purge".
1218        let scenario_for_session = params
1219            .get("scenario")
1220            .map(|s| s.as_str())
1221            .unwrap_or("default");
1222        // SRD-77 — refine_plan is populated only when:
1223        //   1. `--refine` was passed (refine verb is in flight)
1224        //   2. The resume_target resolves to an existing session dir
1225        // Computed BEFORE Session construction so the plan's
1226        // `next_exec_id` can flow into `Session::refine`.
1227        // SRD-77 refine scope. Default `missing` (skip phases with
1228        // a prior completed outcome) when `--refine` is set without
1229        // an explicit `scope=`. `scope=all` builds the plan for
1230        // exec_id bumping + session re-attach but leaves the skip
1231        // set empty, so every phase runs and new outcomes overwrite
1232        // the prior ones (the cardinal history stays — prior rows
1233        // keep their old exec_id, new rows land under the bumped
1234        // exec_id). `scope=changed` requires `phase_hash` storage
1235        // on PhaseOutcome (follow-up push) and is rejected here
1236        // with a "not yet implemented" diag so the operator isn't
1237        // silently dropped to `missing` semantics.
1238        let refine_scope: Option<&str> = params
1239            .get("scope")
1240            .map(|s| s.as_str())
1241            .filter(|_| refine_requested);
1242        let refine_plan: Option<Arc<crate::refine_plan::RefinePlan>> = if refine_requested {
1243            resume_target
1244                .as_ref()
1245                .and_then(|p| p.parent().map(|d| d.to_path_buf()))
1246                .and_then(|prior_dir| {
1247                    if !prior_dir.exists() {
1248                        crate::diag!(
1249                            crate::observer::LogLevel::Warn,
1250                            "refine: prior session dir not found ({}); \
1251                         running every phase as if this were a fresh `nmbrs run`",
1252                            prior_dir.display()
1253                        );
1254                        return None;
1255                    }
1256                    let mut plan =
1257                        crate::refine_plan::RefinePlan::load_from_session_dir(&prior_dir);
1258                    if plan.is_none() {
1259                        crate::diag!(
1260                            crate::observer::LogLevel::Warn,
1261                            "refine: no readable phase_outcomes in {}; \
1262                         running every phase as if this were a fresh `nmbrs run`",
1263                            prior_dir.display()
1264                        );
1265                    }
1266                    if let Some(p) = plan.as_mut() {
1267                        p.scope = match refine_scope {
1268                            Some("all") => {
1269                                crate::diag!(
1270                                    crate::observer::LogLevel::Info,
1271                                    "refine: scope=all — every phase will run \
1272                                 under exec_id={}",
1273                                    p.next_exec_id
1274                                );
1275                                crate::refine_plan::RefineScope::All
1276                            }
1277                            Some("changed") => {
1278                                crate::diag!(
1279                                    crate::observer::LogLevel::Info,
1280                                    "refine: scope=changed — comparing each \
1281                                 phase's program hash against the prior \
1282                                 outcome; unchanged phases skip, changed \
1283                                 phases re-run under exec_id={}",
1284                                    p.next_exec_id
1285                                );
1286                                crate::refine_plan::RefineScope::Changed
1287                            }
1288                            _ => crate::refine_plan::RefineScope::Missing,
1289                        };
1290                    }
1291                    plan.map(Arc::new)
1292                })
1293        } else {
1294            None
1295        };
1296        // SRD-77 — `--on-removed=` policy. When refine attaches to
1297        // a session whose prior outcomes name phases the current
1298        // workload no longer declares, the default behavior is
1299        // ERROR (refuse to proceed) — silently keeping orphan
1300        // outcomes hides intent, silently dropping them loses
1301        // data. `--on-removed=keep` retains them (no work);
1302        // `--on-removed=drop` is reserved for a future push that
1303        // wires the deletion + interactive confirm.
1304        //
1305        // The check compares the prior `phase_name` set against
1306        // the current workload's `phases:` map keys. Sweep-cell
1307        // variants (same name, different labels) are aggregated by
1308        // name here — a missing name covers every prior cell of
1309        // it. Tighter (name+labels) granularity is a follow-up
1310        // when label-set comparison becomes load-bearing.
1311        // (`on_removed_policy` is consulted per-execution, in `run_execution`.)
1312        // Build the session (the shared, session-tier container). SRD-88:
1313        // the session carries only `session=<id>`; the execution's
1314        // identity (`exec_id`, `workload`) is declared one tier down, on
1315        // its own component (below). [[HOST:session]]
1316        let session = match (refine_plan.as_ref(), resume_target.as_ref()) {
1317            (Some(plan), Some(p)) if p.exists() => {
1318                let prior_dir = p
1319                    .parent()
1320                    .map(|d| d.to_path_buf())
1321                    .unwrap_or_else(crate::session::latest_session_dir);
1322                crate::diag!(
1323                    crate::observer::LogLevel::Info,
1324                    "refine: attached to session {}; \
1325                 prior outcomes={}, completed phases to skip={}, \
1326                 next exec_id={}",
1327                    prior_dir.display(),
1328                    plan.prior_outcomes_seen,
1329                    plan.completed.len(),
1330                    plan.next_exec_id
1331                );
1332                crate::session::Session::reattach(prior_dir, scenario_for_session)
1333            }
1334            (_, Some(p)) if p.exists() => {
1335                let prior_dir = p
1336                    .parent()
1337                    .map(|d| d.to_path_buf())
1338                    .unwrap_or_else(crate::session::latest_session_dir);
1339                crate::session::Session::reattach(prior_dir, scenario_for_session)
1340            }
1341            _ => crate::session::Session::new_with_args(scenario_for_session, &args),
1342        };
1343        let session_log_path = session.output_dir.join("session.log");
1344        if let Err(e) = crate::observer::set_log_file(&session_log_path) {
1345            crate::diag!(
1346                crate::observer::LogLevel::Warn,
1347                "warning: failed to open session log {}: {e}",
1348                session_log_path.display()
1349            );
1350        }
1351
1352        // `--trace=<spec>` (repeatable). Collected from raw `args`
1353        // because parse_params is HashMap-keyed and would collapse
1354        // repeated flags. See trace_router for spec grammar.
1355        let trace_specs = collect_repeated_flag(&args, "trace");
1356        match crate::trace_router::init(&trace_specs, &session.output_dir) {
1357            Ok(0) => {} // no --trace specified, router stays empty
1358            Ok(n) => crate::diag!(
1359                crate::observer::LogLevel::Info,
1360                "trace router: {n} route(s) configured"
1361            ),
1362            Err(e) => crate::diag!(
1363                crate::observer::LogLevel::Warn,
1364                "trace router init failed: {e}"
1365            ),
1366        }
1367
1368        crate::diag!(
1369            crate::observer::LogLevel::Info,
1370            "session: {} ({})",
1371            session.id,
1372            session.output_dir.display()
1373        );
1374
1375        // Polydat library audit channel: route polydat's
1376        // `audit::log/info/warn/...` calls through this
1377        // process's observer so they land in `session.log`
1378        // alongside every other diagnostic line, with a
1379        // `[lib]` subsystem tag so the operator can filter them
1380        // out if they're noisy. Replaces the standalone
1381        // `<session>/audit.log` file — same content, one fewer
1382        // place to look.
1383        // SRD-82 §"Panic reporting: one full render" — the runtime's
1384        // fiber/op catchers render eval-panic diagnostics in full via
1385        // the phase error list, so the polydat hook degrades to a
1386        // one-line notice instead of the full body + backtrace hint.
1387        polydat::set_panic_reporting_downstream(true);
1388
1389        polydat::audit::set_log_fn(|level, msg| {
1390            use polydat::audit::LogLevel as AuditLevel;
1391            let mapped = match level {
1392                AuditLevel::Trace | AuditLevel::Debug => crate::observer::LogLevel::Debug,
1393                AuditLevel::Info => crate::observer::LogLevel::Info,
1394                AuditLevel::Warn => crate::observer::LogLevel::Warn,
1395                AuditLevel::Error => crate::observer::LogLevel::Error,
1396            };
1397            crate::observer::log(mapped, &format!("[lib] {msg}"));
1398        });
1399
1400        // SQLite metrics in session directory. SRD-88: creating the
1401        // reporter (connection + schema + the session-INVARIANT
1402        // `session` metadata key) is session-tier — one per session,
1403        // shared by every execution. The per-execution metadata
1404        // (workload / scenario / params / the SRD-77 `executions` row)
1405        // is written separately below, per execution, so N concurrent
1406        // executions each record their own without clobbering.
1407        let sqlite_path = session.metrics_path();
1408        let sqlite_reporter = nmbrs_metrics::reporters::sqlite::SqliteReporter::new(&sqlite_path)
1409            .map(|mut r| {
1410                r.set_metadata("session", &session.id);
1411                crate::diag!(
1412                    crate::observer::LogLevel::Info,
1413                    "metrics: {}",
1414                    sqlite_path.display()
1415                );
1416                r
1417            })
1418            .map_err(|e| {
1419                crate::diag!(
1420                    crate::observer::LogLevel::Warn,
1421                    "warning: SQLite metrics disabled: {e}"
1422                )
1423            })
1424            .ok();
1425        let sqlite_reporter = std::sync::Arc::new(std::sync::Mutex::new(sqlite_reporter));
1426
1427        // RAII shutdown guard — runs `consolidate_wal` at session
1428        // end via Drop. Reliable across every Rust unwind path:
1429        // normal completion, error `?` propagation, first-Ctrl-C
1430        // → stop flag → runner unwind. The only path that skips
1431        // it is `std::process::exit` (second Ctrl-C force-exit),
1432        // which is the operator's declared "I don't want to
1433        // wait" escape hatch. The guard MUST live until after
1434        // every reporter has finished writing — bind it here at
1435        // the top of the run-impl block so it drops in
1436        // last-created / first-dropped order relative to local
1437        // variables; the explicit `_` binding pins its lifetime
1438        // to the function scope (otherwise the temporary would
1439        // drop immediately).
1440        let _sqlite_shutdown_guard =
1441            nmbrs_metrics::reporters::sqlite::SqliteShutdownGuard::new(sqlite_reporter.clone());
1442
1443        // Periodic WAL checkpoint so concurrent read-only
1444        // tooling (`nmbrs report` against a live session,
1445        // ad-hoc `sqlite3 metrics.db` inspection, the realtime
1446        // metricsql preview) sees committed writes without
1447        // waiting for session end. SQLite's WAL holds frames
1448        // until either:
1449        //   1. `wal_autocheckpoint` (page-count threshold,
1450        //      default 1000 pages) fires on a writer, OR
1451        //   2. an explicit `PRAGMA wal_checkpoint(...)` runs.
1452        //
1453        // Under bursty workloads (a tight rampup followed by a
1454        // long synchronous wait — exactly the SRD-75
1455        // ensure_compacted shape) writers can stall under the
1456        // autocheckpoint threshold for many minutes, during
1457        // which readers see stale data. A 60-second background
1458        // task running `PRAGMA wal_checkpoint(PASSIVE)` bounds
1459        // the staleness without blocking writers.
1460        //
1461        // PASSIVE mode is the cheap variant: it merges all
1462        // currently-committed WAL frames into the main `.db`
1463        // without truncating the WAL file or pausing writers.
1464        // The tokio task runs for the runtime's lifetime and is
1465        // cancelled on shutdown; the final `consolidate_wal`
1466        // (TRUNCATE flavour) at session end produces the
1467        // archival "no -wal sidecar" form.
1468        {
1469            let reporter = sqlite_reporter.clone();
1470            tokio::spawn(async move {
1471                let mut interval = tokio::time::interval(std::time::Duration::from_secs(60));
1472                // First tick is immediate; skip it so the
1473                // post-session-start state has a chance to
1474                // settle before the first checkpoint fires.
1475                interval.tick().await;
1476                loop {
1477                    interval.tick().await;
1478                    if let Ok(g) = reporter.lock()
1479                        && let Some(r) = g.as_ref()
1480                    {
1481                        r.passive_checkpoint();
1482                    }
1483                }
1484            });
1485        }
1486
1487        // SRD-88 — session-tier metrics services, configured from CLI params.
1488        let SessionMetrics {
1489            cadence_reporter,
1490            cadence_tree,
1491            metrics_query,
1492            stop_handle,
1493        } = build_session_metrics(
1494            &session,
1495            &sqlite_reporter,
1496            &observer,
1497            &eff_params,
1498            &openmetrics_url,
1499            &args,
1500            &eff_params,
1501        )?;
1502        crate::session_signals::install_signal_handler();
1503        let _profiler =
1504            crate::profiler::ProfileGuard::maybe_start(&params, Some(&session.output_dir));
1505
1506        // SRD-88 — the SESSION-tier checkpoint writer (one per session;
1507        // holds the single resume lock) + the resume doc. Executions share
1508        // the writer and each derives its own resume plan from `saved_doc`.
1509        let checkpoint_path = session.output_dir.join("checkpoint.jsonl");
1510        let saved_doc = match resume_target.as_ref() {
1511            Some(p) => match crate::checkpoint::storage::read(p) {
1512                Ok(Some(doc)) => Some(doc),
1513                Ok(None) => {
1514                    crate::diag!(
1515                        crate::observer::LogLevel::Warn,
1516                        "resume: no checkpoint found at {} — fresh session",
1517                        p.display()
1518                    );
1519                    None
1520                }
1521                Err(e) => return Err(format!("resume: {e}")),
1522            },
1523            None => None,
1524        };
1525        let invocation = saved_doc.as_ref().map(|d| d.invocation + 1).unwrap_or(1);
1526        let started_at = saved_doc
1527            .as_ref()
1528            .map(|d| d.started_at.clone())
1529            .unwrap_or_else(crate::checkpoint::storage::now_rfc3339);
1530        // A dry-run is resume-inert (SRD-44): it short-circuits ops and may
1531        // run against placeholder params, so it must persist NO checkpoint —
1532        // otherwise its (synthetic) phase completions poison a later
1533        // `--resume-latest`. `Session::new_with_args` already withholds the
1534        // `latest` symlink from a dry-run; this withholds the checkpoint too.
1535        let checkpoint_writer =
1536            std::sync::Arc::new(if crate::session::args_request_dryrun(&args) {
1537                crate::checkpoint::CheckpointWriter::disabled(checkpoint_path.clone())
1538            } else {
1539                match saved_doc.as_ref() {
1540                    Some(_doc) => crate::checkpoint::CheckpointWriter::from_existing(
1541                        checkpoint_path.clone(),
1542                        saved_doc.clone().unwrap(),
1543                        crate::checkpoint::storage::now_rfc3339(),
1544                        invocation,
1545                    ),
1546                    None => crate::checkpoint::CheckpointWriter::new(
1547                        checkpoint_path.clone(),
1548                        session.id.clone(),
1549                        started_at,
1550                        invocation,
1551                    ),
1552                }
1553            });
1554
1555        Ok(SessionHost {
1556            session,
1557            sqlite_reporter,
1558            cadence_reporter,
1559            cadence_tree,
1560            metrics_query,
1561            stop_handle,
1562            refine_plan,
1563            resume_target,
1564            refine_requested,
1565            refine_scope: refine_scope.map(|s| s.to_string()),
1566            stick_reattached,
1567            profiler: _profiler,
1568            sqlite_guard: _sqlite_shutdown_guard,
1569            checkpoint_writer,
1570            saved_doc,
1571        })
1572    }
1573
1574    /// Session teardown — once, after every execution (SRD-88).
1575    async fn shutdown(self) {
1576        if let Some(mut profiler) = self.profiler {
1577            profiler.finish();
1578        }
1579        self.stop_handle.stop().await;
1580        let _teardown_t = std::time::Instant::now();
1581        self.cadence_reporter.shutdown().await;
1582        crate::diag!(
1583            crate::observer::LogLevel::Debug,
1584            "shutdown: cadence reporter flush+join {:?}",
1585            _teardown_t.elapsed()
1586        );
1587        // Release the live-access reader (the HybridStore's sqlite cold-tier
1588        // connection on metrics.db) BEFORE consolidating the WAL: the
1589        // `journal_mode=DELETE` flip in `consolidate_wal` needs an EXCLUSIVE
1590        // db lock, which a still-open reader connection on the same file
1591        // blocks ("database is locked"). The session is fully stopped here, so
1592        // no live reads remain.
1593        nmbrs_metrics::queryapi::uninstall_live_access();
1594        crate::diag!(
1595            crate::observer::LogLevel::Info,
1596            "shutting down — consolidating metrics.db WAL"
1597        );
1598        self.sqlite_guard.consume();
1599        crate::diag!(crate::observer::LogLevel::Info, "shutdown complete");
1600        // Shutdown-ladder bookkeeping: the run drained through the full
1601        // process-level cleanup, so a still-ticking level-1 countdown
1602        // (Ctrl-C during the final drain) goes quiet instead of
1603        // announcing op cancellation for a run that no longer has ops.
1604        crate::session_signals::mark_shutdown_complete();
1605    }
1606}
1607
1608/// SRD-88 — run ONE execution against a shared [`SessionHost`]. Does
1609/// NOT tear the session down (that is `SessionHost::shutdown`).
1610async fn run_execution(
1611    host: &SessionHost,
1612    args: &[String],
1613    observer: Arc<dyn crate::observer::RunObserver>,
1614) -> Result<(), String> {
1615    let session = &host.session;
1616    let session_id = host.session.id.clone();
1617    let sqlite_reporter = host.sqlite_reporter.clone();
1618    let cadence_reporter = host.cadence_reporter.clone();
1619    let stop_handle = host.stop_handle.clone();
1620    let resume_target = host.resume_target.clone();
1621    let refine_plan = host.refine_plan.clone();
1622    let refine_requested = host.refine_requested;
1623    let refine_scope = host.refine_scope.as_deref();
1624    let stick_reattached = host.stick_reattached.clone();
1625    let mut diag = DiagnosticConfig::normal();
1626
1627    // Detect scenario shorthand: `workload.yaml <scenario_name>` → `scenario=<name>`
1628    let args = normalize_args(args);
1629    let mut params = parse_params(&args);
1630
1631    // ── SRD-109 Part 2 — driver-manifest resolution ──
1632    //
1633    // `driver=<name>` resolves a driver manifest (local
1634    // `drivers/<name>/driver.yaml` under the cwd first, then the
1635    // bundled catalog entry `drivers/<name>/driver`; both at once
1636    // favors the local one, with a warning). The manifest supplies
1637    // the implementation library (as workload= when none was
1638    // given, else as impl=), the backing adapter, and default
1639    // params at lowest precedence. A `driver=` value matching no
1640    // manifest is an error: `driver=` never names an adapter.
1641    if let Some(driver_name) = params.get("driver").cloned() {
1642        let (manifest, library_ref) = resolve_driver_manifest(&driver_name)?;
1643        // A positional `<file>.yaml` argument counts as a given
1644        // workload — the manifest's library must not displace it.
1645        let workload_given = params.contains_key("workload")
1646            || args
1647                .iter()
1648                .any(|a| a.ends_with(".yaml") || a.ends_with(".yml"));
1649        apply_driver_manifest(
1650            &mut params,
1651            &driver_name,
1652            manifest,
1653            library_ref,
1654            workload_given,
1655        )?;
1656    }
1657    let params = params;
1658
1659    // Load workload — from inline op= or YAML file.
1660    let mut workload_file: Option<String> = None;
1661    // SRD-85: true when the workload came from the bundled
1662    // catalog — its identity is a catalog name, not a path, and
1663    // relative resolution context falls back to the cwd.
1664    let mut workload_is_bundled = false;
1665    let mut workload_source_text: Option<String> = None;
1666    let mut workload = if let Some(op_str) = params.get("op") {
1667        if params.contains_key("workload") {
1668            crate::diag!(
1669                crate::observer::LogLevel::Warn,
1670                "warning: op= overrides workload="
1671            );
1672        }
1673        nmbrs_workload::inline::synthesize_inline_workload(op_str)
1674            .map_err(|e| format!("inline workload: {e}"))?
1675    } else {
1676        let workload_raw = params
1677            .get("workload")
1678            .cloned()
1679            .or_else(|| {
1680                args.iter()
1681                    .find(|a| a.ends_with(".yaml") || a.ends_with(".yml"))
1682                    .cloned()
1683            })
1684            .ok_or("no workload specified. Use workload=file.yaml or op=\"...\"")?;
1685
1686        // SRD-85 resolution: local files first (as-is, with
1687        // extensions, under cwd `workloads/`), then the bundled
1688        // catalog by exact name. Both at once is a hard error.
1689        match resolve_workload(&workload_raw)? {
1690            ResolvedWorkload::Path(workload_path) => {
1691                workload_file = Some(workload_path.clone());
1692
1693                // SRD-72: parse_workload_from_path resolves any
1694                // `extends:` chain before delegating to parse_workload.
1695                // The merged YAML text is what the parser consumes; the
1696                // raw on-disk text is still kept for diagnostic
1697                // `<path>:<line>:<col>` reporting (no source-map across
1698                // include boundaries today — diagnostics on inherited
1699                // fields point at the merged-output position).
1700                let yaml_source = std::fs::read_to_string(&workload_path)
1701                    .map_err(|e| format!("read workload '{workload_path}': {e}"))?;
1702                let workload = nmbrs_workload::parse::parse_workload_from_path(
1703                    std::path::Path::new(&workload_path),
1704                    &params,
1705                )
1706                .map_err(|e| format!("parse workload: {e}"))?;
1707                workload_source_text = Some(yaml_source);
1708                workload
1709            }
1710            ResolvedWorkload::Bundled(bundled) => {
1711                // Catalog name is the workload identity for the
1712                // session (session.log, summaries, phase
1713                // outcomes) — bundled runs have no path.
1714                workload_file = Some(bundled.name.to_string());
1715                workload_is_bundled = true;
1716                // SRD-72 + SRD-85: a bundled workload's
1717                // `extends:` chain resolves through the catalog
1718                // (no directory context).
1719                let (merged, res_warnings) =
1720                    nmbrs_workload::extends::load_and_merge_bundled(bundled)
1721                        .map_err(|e| format!("bundled workload `{}`: {e}", bundled.name))?;
1722                let mut workload = nmbrs_workload::parse::parse_workload(&merged, &params)
1723                    .map_err(|e| format!("parse bundled workload `{}`: {e}", bundled.name))?;
1724                workload.resolution_warnings.extend(res_warnings);
1725                workload_source_text = Some(bundled.source.to_string());
1726                workload
1727            }
1728        }
1729    };
1730
1731    // ── SRD-108 Part B — implementation binding (load time) ──
1732    //
1733    // Two invocation forms:
1734    //   workload=<impl>                  — the impl's `implements:`
1735    //       pulls its blueprint; the BLUEPRINT becomes the
1736    //       effective workload with the impl's op bodies bound in.
1737    //   workload=<blueprint> impl=<impl> — the blueprint is the
1738    //       entry point; `impl=` names the implementation, whose
1739    //       own `implements:` must resolve to the same blueprint.
1740    // All rules are load errors; by the time synthesis runs the
1741    // workload is ordinary and fully concrete.
1742    let impl_param = params.get("impl").cloned();
1743    if let Some(target) = workload.implements.clone() {
1744        if impl_param.is_some() {
1745            return Err(format!(
1746                "workload '{}' is an implementation (declares \
1747                 `implements:`), so `impl=` does not apply — invoke \
1748                 either the implementation directly or the blueprint \
1749                 with impl=",
1750                workload_file.as_deref().unwrap_or("<inline>")
1751            ));
1752        }
1753        workload = bind_into_declared_blueprint(
1754            workload,
1755            &target,
1756            workload_file.as_deref(),
1757            workload_is_bundled,
1758            &params,
1759        )?;
1760    } else if let Some(impl_ref) = impl_param {
1761        let base_dir = (!workload_is_bundled)
1762            .then(|| {
1763                workload_file
1764                    .as_deref()
1765                    .map(std::path::Path::new)
1766                    .and_then(|p| p.parent().map(|d| d.to_path_buf()))
1767            })
1768            .flatten();
1769        let bundled_origin = workload_is_bundled
1770            .then_some(workload_file.as_deref())
1771            .flatten();
1772        let (implementation, impl_id) =
1773            load_secondary_workload(&impl_ref, &params, base_dir.as_deref(), bundled_origin)?;
1774        let declared = implementation.implements.clone().ok_or_else(|| {
1775            format!(
1776                "impl='{impl_ref}' resolves to '{impl_id}', which declares no \
1777             `implements:` — an implementation module must name its \
1778             blueprint"
1779            )
1780        })?;
1781        // The impl's declared target must be the SAME document the
1782        // operator invoked as workload=.
1783        // The impl doc's `implements:` resolves relative to the
1784        // IMPL doc's own directory (extends precedent).
1785        let impl_dir = std::path::Path::new(&impl_id)
1786            .parent()
1787            .map(|d| d.to_path_buf());
1788        let declared_id =
1789            workload_ref_identity(&declared, impl_dir.as_deref(), Some(impl_id.as_str()))?;
1790        let invoked_id = workload_file
1791            .clone()
1792            .map(|f| canonical_identity(&f))
1793            .unwrap_or_default();
1794        if declared_id != invoked_id {
1795            return Err(format!(
1796                "impl='{impl_id}' declares implements='{declared}' \
1797                 (resolves to '{declared_id}'), which is not the invoked \
1798                 workload '{invoked_id}'"
1799            ));
1800        }
1801        crate::diag!(
1802            crate::observer::LogLevel::Info,
1803            "implements: binding '{impl_id}' into blueprint '{invoked_id}'"
1804        );
1805        nmbrs_workload::implements::bind_implementation(&mut workload, implementation)
1806            .map_err(|e| format!("implements binding: {e}"))?;
1807    }
1808    {
1809        let unbound = nmbrs_workload::implements::unbound_abstract_slots(&workload);
1810        if !unbound.is_empty() {
1811            return Err(format!(
1812                "abstract op slot(s) [{}] unbound — pass impl=<workload> \
1813                 or invoke an implementing workload (SRD-108)",
1814                unbound.join(", ")
1815            ));
1816        }
1817    }
1818
1819    // Overlay CLI params on the workload's declared params (CLI wins) so
1820    // synthesis (next) can read the operator's `cycles=N` / `concurrency=N`
1821    // overrides and promote them onto the synthetic phase. Same precedence
1822    // rule the session-tier services use via [`effective_params`], so a key
1823    // means the same thing whether declared in the workload or on the CLI.
1824    // Also covers the inline (`op=`) path that loaded empty params.
1825    workload.params = overlay_cli_params(std::mem::take(&mut workload.params), &params);
1826
1827    // Unification: the scenario-tree executor is the sole
1828    // execution path. Workloads that arrive without an
1829    // explicit `phases:` block (the `op=` inline form, the
1830    // `blocks:` shorthand, top-level `ops:` lists) get an
1831    // implicit `main` phase + `default` scenario synthesized
1832    // here. Idempotent on workloads that already declare
1833    // phases. See [`nmbrs_workload::model::Workload::synthesize_default_phase`].
1834    workload.synthesize_default_phase();
1835
1836    // `{workload_dir}`: the directory the workload file is in, so a
1837    // workload can name a file kept beside it (the logfile adapter's
1838    // fixture logs, SRD-117 §3.2). It is supplied as a param, and only
1839    // to a workload that reads it, so every scope resolves it as it
1840    // does any param and a workload that never mentions it is
1841    // untouched. A workload that declares the name itself keeps its
1842    // own value. Bundled and inline workloads have no directory of
1843    // their own and get the working directory, as relative paths in
1844    // them already do.
1845    if !workload.params.contains_key(WORKLOAD_DIR_PARAM)
1846        && collect_param_references(&workload)
1847            .placeholders
1848            .contains(WORKLOAD_DIR_PARAM)
1849    {
1850        let dir = workload_file
1851            .as_deref()
1852            .filter(|_| !workload_is_bundled)
1853            .and_then(|file| std::path::Path::new(file).parent())
1854            .filter(|dir| !dir.as_os_str().is_empty())
1855            .map_or_else(|| ".".to_string(), |dir| dir.to_string_lossy().into_owned());
1856        workload.params.insert(WORKLOAD_DIR_PARAM.to_string(), dir);
1857        if !workload
1858            .declared_params
1859            .iter()
1860            .any(|p| p == WORKLOAD_DIR_PARAM)
1861        {
1862            workload
1863                .declared_params
1864                .push(WORKLOAD_DIR_PARAM.to_string());
1865        }
1866    }
1867
1868    let merged_params = workload.params.clone();
1869
1870    // A workload's own `driver:` param is not an adapter selector
1871    // (only a CLI `driver=` names a manifest, resolved above).
1872    if merged_params.contains_key("driver") && !params.contains_key("driver") {
1873        return Err(format!(
1874            "workload param `driver: {}` does not select an adapter; write `adapter: {}`",
1875            merged_params["driver"], merged_params["driver"]
1876        ));
1877    }
1878
1879    // Extract core config
1880    let driver = merged_params
1881        .get("adapter")
1882        .cloned()
1883        .unwrap_or_else(|| "stdout".into());
1884    let explicit_cycles: Option<u64> = merged_params.get("cycles").and_then(|s| parse_count(s));
1885    let concurrency: usize = match merged_params.get("concurrency") {
1886        Some(s) => s
1887            .parse()
1888            .map_err(|_| format!("concurrency value '{s}' is not a valid integer"))?,
1889        None => 1,
1890    };
1891    let rate: Option<f64> = match merged_params.get("rate") {
1892        Some(s) => Some(
1893            s.parse()
1894                .map_err(|_| format!("rate value '{s}' is not a valid number"))?,
1895        ),
1896        None => None,
1897    };
1898    // Workload-root total-attempts budget — the `tries` sigil for the
1899    // conditional TriesDispenser (SRD-82 Part 3b). Absent = ops without
1900    // their own `tries:` run single-attempt with no retry wrapper. `N ≥ 2`
1901    // retries adapter-retryable op errors (CQL timeouts/overloads) up to N
1902    // total attempts before the failure propagates to the result level;
1903    // `1` = explicit single-attempt; `0` = ops fail without executing.
1904    let tries: Option<u32> = match merged_params.get("tries") {
1905        Some(s) => Some(
1906            s.parse()
1907                .map_err(|_| format!("tries value '{s}' is not a valid integer"))?,
1908        ),
1909        None => None,
1910    };
1911    let tag_filter = merged_params.get("tags").cloned();
1912    let seq_type = merged_params
1913        .get("seq")
1914        .map(|s| SequencerType::parse(s).unwrap_or(SequencerType::Bucket))
1915        .unwrap_or(SequencerType::Bucket);
1916    let mut error_spec = merged_params
1917        .get("errors")
1918        .cloned()
1919        .unwrap_or_else(|| ".*:warn,stop".to_string());
1920    // `error_rate_max` — the OPT-IN session-wide error-rate circuit
1921    // breaker. When set, a phase fails once >this share of its ops error
1922    // (after a 50-op floor); per-phase `error_rate_max:` overrides it.
1923    // NO default (SRD-82 §"AggregateGuard retired as a default"): the
1924    // former silent 0.1 default was hidden, non-optional, and possibly
1925    // not what the operator wanted — operators built duplicate
1926    // `stop_when` backstops precisely because this one was invisible.
1927    // Aggregate health belongs to visible, workload-authored `stop_when`
1928    // conditions (SRD-83); this knob remains only as an explicit opt-in.
1929    let error_rate_max: Option<f64> = match merged_params.get("error_rate_max") {
1930        Some(s) => match s.trim().parse::<f64>() {
1931            Ok(v) if v >= 0.0 => Some(v),
1932            _ => {
1933                eprintln!(
1934                    "error: error_rate_max must be a non-negative number \
1935                           (e.g. 0.1 = 10%); got '{s}'"
1936                );
1937                std::process::exit(2);
1938            }
1939        },
1940        None => None,
1941    };
1942    // SRD-44 §"--force-retry-failed": when set on a resume
1943    // invocation, prepend a `.*:retry,warn` rule to the errors
1944    // cascade so any failure surfaces a retry rather than the
1945    // workload's normal stop / fail behaviour. Idempotent: when
1946    // set on a fresh run, it still applies (doesn't gate on
1947    // is_resume) — operators who want the override on a fresh
1948    // run get it; operators who pass it accidentally without
1949    // resume= get the same generous-retry policy they'd see on
1950    // resume.
1951    let force_retry_failed = params.get("force_retry_failed").map_or(Ok(false), |s| {
1952        nmbrs_workload::boolean::parse_bool("force_retry_failed", s)
1953    })? || args.iter().any(|a| a == "--force-retry-failed");
1954    if force_retry_failed {
1955        error_spec = format!(".*:retry,warn;{error_spec}");
1956        crate::diag!(
1957            crate::observer::LogLevel::Info,
1958            "--force-retry-failed: errors cascade prefixed with '.*:retry,warn'"
1959        );
1960    }
1961
1962    // Validate CLI parameters (runner-known + adapter-registered + workload-declared).
1963    //
1964    // Allow-list = installed param vocabulary ∪ adapter-registered ∪
1965    // `workload.declared_params` (the original YAML keys from
1966    // the workload's `params:` block). We do **not** consult
1967    // `workload.params` here — `parse.rs` merges every CLI arg
1968    // into that map regardless of whether the workload declared
1969    // it, so checking against it would let any CLI param through
1970    // and silently drop typos like `profile=perf` (vs.
1971    // `profiler=perf`). `declared_params` preserves the user's
1972    // declared surface independent of CLI overlays, which is
1973    // what the closed-vocabulary check needs. Skipped entirely
1974    // when no CLI vocabulary is installed (library/test driver).
1975    if let Some(cli_params) = known_params() {
1976        let adapter_params = registered_adapter_params();
1977        let all_known: Vec<&str> = cli_params
1978            .iter()
1979            .copied()
1980            .chain(adapter_params.iter().copied())
1981            .chain(workload.declared_params.iter().map(|s| s.as_str()))
1982            .collect();
1983        for key in params.keys() {
1984            if !all_known.contains(&key.as_str()) {
1985                return Err(unrecognized_param_error(&args, key, &all_known));
1986            }
1987        }
1988    }
1989
1990    // Validate workload-declared params are actually referenced.
1991    // Unreferenced params can shadow runner params (e.g., a workload
1992    // declaring `concurrency` as a param masks the CLI parameter
1993    // validation, but if nothing in the workload uses `{concurrency}`
1994    // the value is silently ignored).
1995    //
1996    // AND the reverse direction (SRD-N param-reference validator):
1997    // every `{name}` placeholder in the workload must resolve to a
1998    // declared param, a known runner/adapter param, or an iter-var
1999    // introduced by some Comprehension in the scenario tree. A
2000    // stray `{undeclared}` would otherwise survive
2001    // `expand_workload_params` as a literal and trip the Polydat parser
2002    // later with a cryptic "expected expression, got LBrace" — that
2003    // surfaces too late and doesn't name the offender. The check
2004    // here points at the placeholder by name so the operator sees
2005    // what to fix.
2006    {
2007        // First — catch `{name}` placeholders that appear inside
2008        // Polydat expression bodies outside of string literals. The
2009        // Polydat grammar doesn't accept `{...}` as expression syntax;
2010        // a `{name}` there will always fail compile with a
2011        // cryptic "expected expression, got LBrace". Catch it
2012        // here with a targeted message naming the YAML file and
2013        // line so the operator can jump straight to it.
2014        let mut invalid_polydat_braces: Vec<PolydatBraceFinding> =
2015            collect_polydat_brace_refs(&workload);
2016        if !invalid_polydat_braces.is_empty() {
2017            invalid_polydat_braces.sort();
2018            invalid_polydat_braces.dedup();
2019            let file_path = workload_file.as_deref().unwrap_or("<inline>");
2020            let lines: Vec<String> = invalid_polydat_braces
2021                .iter()
2022                .map(|f| {
2023                    let yaml_line = workload_source_text
2024                        .as_deref()
2025                        .and_then(|src| find_yaml_line_for_brace(src, &f.placeholder));
2026                    let prefix = match yaml_line {
2027                        Some(n) => format!("{file_path}:{n}"),
2028                        None => file_path.to_string(),
2029                    };
2030                    format!(
2031                        "  {prefix}: in {} — `{{{}}}`. Use bare `{}`.",
2032                        f.location, f.placeholder, f.placeholder
2033                    )
2034                })
2035                .collect();
2036            return Err(format!(
2037                "`{{...}}` braces in Polydat expression context (invalid syntax).\n\
2038                 Polydat accepts bare identifiers; braces are only for YAML string\n\
2039                 interpolation (op `prepared:`/`raw:`, `cycles:`, etc.).\n{}",
2040                lines.join("\n"),
2041            ));
2042        }
2043
2044        crate::params::check_param_names(workload.declared_params.iter())?;
2045
2046        let referenced = collect_param_references(&workload);
2047        let adapter_params: std::collections::HashSet<&'static str> =
2048            registered_adapter_params().into_iter().collect();
2049        let iter_var_names = collect_iter_var_names(&workload);
2050        let wire_names = collect_polydat_binding_names(&workload);
2051
2052        // Declared/known direction: every declared param must be
2053        // referenced — except adapter-registered params, which
2054        // the driver consumes directly from the merged params
2055        // (e.g. `host`/`port`/`consistency` for CQL). Declaring
2056        // one in `params:` is how a workload surfaces the knob
2057        // with a default in `describe workloads` without a
2058        // textual `{name}` reference.
2059        // Every offender is named, in sorted order, so one run shows
2060        // the whole list and two runs show the same one.
2061        let mut unreferenced: Vec<&str> = workload
2062            .declared_params
2063            .iter()
2064            .map(|s| s.as_str())
2065            .filter(|name| !is_cli_param(name) && !adapter_params.contains(name))
2066            .filter(|name| !referenced.contains(name))
2067            .collect();
2068        unreferenced.sort_unstable();
2069        unreferenced.dedup();
2070        match unreferenced.as_slice() {
2071            [] => {}
2072            [name] => {
2073                return Err(format!(
2074                    "workload declares param '{name}' but it is never referenced as \
2075                     '{{{name}}}' in any op, phase, scenario, or binding. Remove it or use it."
2076                ));
2077            }
2078            names => {
2079                return Err(format!(
2080                    "workload declares params [{}] but none of them is ever referenced \
2081                     (as '{{name}}' or by bare name) in any op, phase, scenario, or \
2082                     binding. Remove them or use them.",
2083                    names.join(", ")
2084                ));
2085            }
2086        }
2087
2088        // Undeclared direction: every curly-brace placeholder
2089        // must resolve. The legitimate-name set spans every
2090        // declaration site the runtime can satisfy:
2091        //   - workload.declared_params (the `params:` block)
2092        //   - the installed CLI param vocabulary (`cycles`, `concurrency`, …)
2093        //   - adapter-registered params (driver-specific config)
2094        //   - iter-vars from Comprehensions in the scenario tree
2095        //     (`k`, `limit`, `profile` from `for_each: "k in …"`)
2096        let declared_set: std::collections::HashSet<&str> = workload
2097            .declared_params
2098            .iter()
2099            .map(|s| s.as_str())
2100            .collect();
2101        let mut undeclared: Vec<&str> = referenced
2102            .placeholders
2103            .iter()
2104            .map(|s| s.as_str())
2105            .filter(|name| !declared_set.contains(*name))
2106            .filter(|name| !is_cli_param(name))
2107            .filter(|name| !adapter_params.contains(name))
2108            .filter(|name| !iter_var_names.contains(*name))
2109            .filter(|name| !wire_names.contains(*name))
2110            .collect();
2111        if !undeclared.is_empty() {
2112            undeclared.sort();
2113            return Err(format!(
2114                "workload references undeclared placeholder{plural} {names} — \
2115                 add to the `params:` block, or check for a typo. Recognised \
2116                 sources for `{{name}}` placeholders: workload `params:`, \
2117                 runner/adapter built-ins, scenario-tree iter-vars from \
2118                 `for_each:`/`for_combinations:`, and wire names from Polydat \
2119                 `bindings:`.",
2120                plural = if undeclared.len() == 1 { "" } else { "s" },
2121                names = undeclared
2122                    .iter()
2123                    .map(|n| format!("`{{{n}}}`"))
2124                    .collect::<Vec<_>>()
2125                    .join(", "),
2126            ));
2127        }
2128    }
2129
2130    // Extract workload structure before consuming. M3.6:
2131    // `workload_params` is the set of *workload-declared* params
2132    // (the YAML `params:` block, with CLI overrides applied) —
2133    // these are what get injected as `const` bindings on the
2134    // workload kernel. The full `workload.params` map also
2135    // contains ad-hoc CLI params like `cycles=`, `workload=`,
2136    // `tags=`, etc., which are not declared bindings and must
2137    // not become identifiers in the Polydat source. Filter by
2138    // `declared_params` to keep only the YAML-declared subset.
2139    let declared: std::collections::HashSet<&String> = workload.declared_params.iter().collect();
2140    let workload_params: HashMap<String, String> = workload
2141        .params
2142        .iter()
2143        .filter(|(k, _)| declared.contains(*k))
2144        .map(|(k, v)| (k.clone(), v.clone()))
2145        .collect();
2146    drop(declared);
2147    let mut phases = workload.phases;
2148    // Inline-expression rewrite per phase. The
2149    // `rewrite_inline_exprs` call later in this function (around
2150    // line 818) operates on `all_ops_for_compile` — a flattened
2151    // copy used for the workload-level kernel — but
2152    // `build_op_template_scope_kernel` (SRD-13d Phase 9) reads
2153    // op definitions from `phases.get(name).ops`, which is the
2154    // ORIGINAL parsed structure. Without this per-phase rewrite,
2155    // op-template kernels never see the synthesised
2156    // `__expr_N := <expr>` bindings and the conditional /
2157    // inline-expression machinery breaks for any op that lands
2158    // on the Phase 9 path. Rewriting in place here keeps the
2159    // two compile paths consistent.
2160    for phase in phases.values_mut() {
2161        crate::scope::rewrite_inline_exprs(&mut phase.ops)?;
2162    }
2163    let phase_order = workload.phase_order;
2164    let scenarios = workload.scenarios;
2165    let workload_readouts = workload.readouts.clone();
2166    // SRD-32a Push 3 — workload-root wrapper override.
2167    // Innermost-to-outermost list, extracted once and
2168    // installed onto every Activity via `set_wrappers_override`
2169    // before `run_with_driver` runs the cascade. Per-op
2170    // `wrappers:` overrides on individual templates shadow
2171    // this entry; CLI flags (not yet implemented) would set
2172    // it independently on the Activity.
2173    let workload_wrappers_override: Option<Vec<String>> = workload
2174        .wrappers
2175        .as_ref()
2176        .filter(|c| !c.order.is_empty())
2177        .map(|c| c.order.clone());
2178    // SRD-63 §8 / Push 8: extract the CLI `--readout=<body>`
2179    // override before any binder is built. Resolved through
2180    // the same `resolve_flag` helper as `--session-path`,
2181    // so it picks up the matching `NMBRS_READOUT` env var
2182    // when set. `None` ⇒ workload bindings + builtin
2183    // defaults run unchanged.
2184    let cli_readout_override = crate::session::resolve_flag(&args[..], "--readout");
2185
2186    // SRD-32a Push 3 — CLI overrides for wrapper composition
2187    // ordering. Two flags:
2188    //
2189    // - `--wrap-order=<list>` — innermost-to-outermost
2190    //   permutation that applies to every op in this run.
2191    //   Workload-root and per-op blocks shadow it (config-
2192    //   locality wins, SRD-04 Rule 5). When neither workload-
2193    //   level override is set, this CLI value plumbs through
2194    //   to `Activity::wrappers_override` for every phase.
2195    // - `--wrap-default-order=<list>` — replaces the
2196    //   resolver's *built-in* default-order tiebreaker for
2197    //   the run. Useful when the operator wants a permanent
2198    //   tilt (e.g. always put validate outside throttle in
2199    //   their environment) without editing every workload.
2200    //   Validated against the constraint graph at session
2201    //   start; an inconsistent list is a hard error.
2202    //
2203    // Both flags accept a comma-separated list. Empty / unset
2204    // ⇒ runtime default applies.
2205    let cli_wrap_order: Option<Vec<String>> =
2206        crate::session::resolve_flag(&args[..], "--wrap-order")
2207            .map(|s| {
2208                s.split(',')
2209                    .map(|t| t.trim().to_string())
2210                    .filter(|t| !t.is_empty())
2211                    .collect()
2212            })
2213            .filter(|v: &Vec<String>| !v.is_empty());
2214    let cli_wrap_default_order: Option<Vec<String>> =
2215        crate::session::resolve_flag(&args[..], "--wrap-default-order")
2216            .map(|s| {
2217                s.split(',')
2218                    .map(|t| t.trim().to_string())
2219                    .filter(|t| !t.is_empty())
2220                    .collect()
2221            })
2222            .filter(|v: &Vec<String>| !v.is_empty());
2223
2224    // Effective workload-level wrapper override: workload's
2225    // own `wrappers: { order: [...] }` block wins over the
2226    // CLI flag (config-locality, SRD-04 Rule 5). Per-op
2227    // overrides on individual ParsedOps shadow either.
2228    let workload_wrappers_override: Option<Vec<String>> =
2229        workload_wrappers_override.or(cli_wrap_order);
2230    // Unified report block (SRD-46). Tables auto-render at
2231    // end-of-run; plot specs persist into the session db so
2232    // post-hoc `nmbrs report ...` can replay them. Empty
2233    // `report:` block ⇒ no auto-render and no persisted specs.
2234    let workload_report = workload.report.clone();
2235    let workload_summaries: HashMap<String, nmbrs_workload::model::SummaryConfig> = workload_report
2236        .items()
2237        .filter(|i| matches!(i.kind, nmbrs_workload::report::Kind::Table))
2238        .map(|i| {
2239            (
2240                i.name.clone(),
2241                nmbrs_workload::model::SummaryConfig::parse(&i.body),
2242            )
2243        })
2244        .collect();
2245
2246    // Collect ALL ops: top-level ops + all phase inline ops.
2247    let mut ops = workload.ops;
2248
2249    // Filter top-level ops by tags (CLI-level tag filter)
2250    if let Some(ref filter) = tag_filter {
2251        ops =
2252            TagFilter::filter_ops(&ops, filter).map_err(|e| format!("invalid tag filter: {e}"))?;
2253    }
2254
2255    // Classify phase ops for compilation:
2256    // - Phases with own bindings or for_each: saved raw, compiled per-phase
2257    // - Phases without own bindings: included in outer (workload) kernel
2258    let mut phase_ops_for_compile: Vec<nmbrs_workload::model::ParsedOp> = Vec::new();
2259    let mut phase_raw_ops: HashMap<String, Vec<nmbrs_workload::model::ParsedOp>> = HashMap::new();
2260    let mut phases_needing_own_kernel: std::collections::HashSet<String> =
2261        std::collections::HashSet::new();
2262    for (name, phase) in &phases {
2263        let has_own_bindings = phase.ops.iter().any(|op| !op.bindings.is_empty());
2264        if phase.for_each.is_some() || has_own_bindings {
2265            phase_raw_ops.insert(name.clone(), phase.ops.clone());
2266            phases_needing_own_kernel.insert(name.clone());
2267        } else {
2268            phase_ops_for_compile.extend(phase.ops.iter().cloned());
2269        }
2270    }
2271
2272    // For non-phased workloads, require at least some ops
2273    if ops.is_empty() && phases.is_empty() {
2274        return Err("no ops selected (tag filter may have excluded all ops)".into());
2275    }
2276
2277    if phases.is_empty() {
2278        crate::diag!(
2279            crate::observer::LogLevel::Info,
2280            "{} ops, {} cycles, concurrency={}, adapter={}",
2281            ops.len(),
2282            explicit_cycles
2283                .map(|c| c.to_string())
2284                .unwrap_or("auto".into()),
2285            concurrency,
2286            driver
2287        );
2288    } else {
2289        // Always log to session.log; stderr suppression is the
2290        // observer's job (TuiObserver gates eprintln internally).
2291        crate::diag!(
2292            crate::observer::LogLevel::Info,
2293            "{} phases, {} top-level ops, adapter={}",
2294            phases.len(),
2295            ops.len(),
2296            driver
2297        );
2298    }
2299
2300    // Collect --polydat-lib=path flags
2301    let polydat_lib_paths: Vec<std::path::PathBuf> = args
2302        .iter()
2303        .filter_map(|a| a.strip_prefix("--polydat-lib="))
2304        .map(std::path::PathBuf::from)
2305        .collect();
2306    let strict = args.iter().any(|a| a == "--strict")
2307        || params.get("strict").map_or(Ok(false), |s| {
2308            nmbrs_workload::boolean::parse_bool("strict", s)
2309        })?;
2310
2311    // SRD-68 follow-up — session-wide op-template synthesis opt level.
2312    // `--kernel-opt=release|diagnostic` or `kernel_opt=…`. Release
2313    // (default) lets the closure-binding economy DCE unreferenced
2314    // magic-extern slots; Diagnostic force-allocates body/count/ok and
2315    // every result-binding LHS slot so step-debug / cycle-replay can
2316    // inspect writes the workload doesn't otherwise consume.
2317    let kernel_opt: polydat::kernel::KernelOptLevel = {
2318        let raw =
2319            cli_flag_value(&args[..], "--kernel-opt").or_else(|| params.get("kernel_opt").cloned());
2320        match raw {
2321            None => polydat::kernel::KernelOptLevel::default(),
2322            Some(s) => polydat::kernel::KernelOptLevel::parse(s.trim()).map_err(|bad| {
2323                format!("unknown --kernel-opt value '{bad}' — use 'release' or 'diagnostic'")
2324            })?,
2325        }
2326    };
2327
2328    // Parse dryrun= param into diagnostic config
2329    if let Some(spec) = params.get("dryrun") {
2330        diag = DiagnosticConfig::parse(spec);
2331    }
2332
2333    // skipped_phases= — how fully-gated-off phases are represented
2334    // (elide | mark | prune). Default: mark.
2335    if let Some(spec) = params.get("skipped_phases") {
2336        match crate::observer::SkippedPhaseDisplay::parse(spec) {
2337            Some(mode) => crate::observer::set_skipped_phase_display(mode),
2338            None => {
2339                return Err(format!(
2340                    "unknown skipped_phases value '{spec}' — use 'elide', 'mark', or 'prune'"
2341                ));
2342            }
2343        }
2344    }
2345
2346    // completed_phases= — how much of a completed node's block is
2347    // retained in scrollback (full | headers). Default: full (SRD-92
2348    // R5 — completion is never a full collapse).
2349    if let Some(spec) = params.get("completed_phases") {
2350        match crate::observer::CompletedPhaseDisplay::parse(spec) {
2351            Some(mode) => crate::observer::set_completed_phase_display(mode),
2352            None => {
2353                return Err(format!(
2354                    "unknown completed_phases value '{spec}' — use 'full' or 'headers'"
2355                ));
2356            }
2357        }
2358    }
2359
2360    // "Never Ignore Silently" — scenario-parse errors are
2361    // ALWAYS fatal regardless of strict mode. The parser used
2362    // to silently drop unknown scenario-node keys (e.g.
2363    // `iterate:` misspellings, stray `phases:` siblings),
2364    // which led to downstream "phase 'iterate' not found"
2365    // confusion masking the real bug. The parser now collects
2366    // every malformed-node case here and we refuse to dispatch.
2367    if !workload.scenario_parse_errors.is_empty() {
2368        return Err(format!(
2369            "scenario parse error{plural} — workload is malformed:\n  - {msgs}",
2370            plural = if workload.scenario_parse_errors.len() == 1 {
2371                ""
2372            } else {
2373                "s"
2374            },
2375            msgs = workload.scenario_parse_errors.join("\n  - "),
2376        ));
2377    }
2378
2379    // SRD-46 + SRD-15: surface report-block warnings collected
2380    // by the parser. Strict mode promotes to a hard error so a
2381    // workload with `defaults`-collisions or empty groups can't
2382    // silently pass; otherwise we log them and continue.
2383    if !workload.report_warnings.is_empty() {
2384        if strict {
2385            return Err(format!(
2386                "report-block warnings (strict mode promotes to errors):\n  - {}",
2387                workload.report_warnings.join("\n  - "),
2388            ));
2389        }
2390        for w in &workload.report_warnings {
2391            crate::observer::log_tagged(
2392                crate::observer::LogLevel::Warn,
2393                crate::observer::EventTag::in_flight(crate::observer::EventCategory::Report),
2394                &format!("report: {w}"),
2395            );
2396        }
2397    }
2398
2399    // SRD-85 nearest-first reference resolution: a target that
2400    // matched multiple same-named resources resolved to the
2401    // nearest (filesystem favored) and is surfaced here — the
2402    // shadowing is allowed but never silent. Strict promotes.
2403    if !workload.resolution_warnings.is_empty() {
2404        if strict {
2405            return Err(format!(
2406                "reference-resolution warnings (strict mode promotes to errors):\n  - {}",
2407                workload.resolution_warnings.join("\n  - "),
2408            ));
2409        }
2410        for w in &workload.resolution_warnings {
2411            crate::observer::log_tagged(
2412                crate::observer::LogLevel::Warn,
2413                crate::observer::EventTag::in_flight(crate::observer::EventCategory::Resolution),
2414                &format!("resolve: {w}"),
2415            );
2416        }
2417    }
2418
2419    // Dry-run mode resolution.
2420    //
2421    // The mode string is a LABEL — there is no "silent" or
2422    // "op" or "cycle" adapter. The real adapter from the
2423    // workload is constructed in full (connect, prepare,
2424    // metadata, dispenser init); the `DryRunWrapper` is
2425    // installed at the outermost wrapper position and per-
2426    // cycle short-circuits the inner stack so the adapter's
2427    // `execute()` never fires. The mode string carries
2428    // operator intent through the log (`dryrun: injected
2429    // `dryrun: <mode>` …`) and only the `fields` mode has a
2430    // structural side-effect (forces the fields wrapper on so
2431    // rendered op text reaches stdout).
2432    //
2433    // Mapping:
2434    //   dryrun=cycle  → mode="cycle",  wrapper short-circuit
2435    //   dryrun=op     → mode="op",     wrapper short-circuit
2436    //   dryrun=silent → mode="silent", wrapper short-circuit
2437    //   dryrun=fields → mode="fields", wrapper short-circuit + fields-render on
2438    //   dryrun=full   → mode=None,     real execution
2439    let dry_run: Option<&str> = if diag.depth == ExecDepth::Cycle {
2440        Some("cycle")
2441    } else {
2442        params.get("dryrun").and_then(|s| match s.as_str() {
2443            "fields" => Some("fields"),
2444            "silent" => Some("silent"),
2445            "op" => Some("op"),
2446            _ => None,
2447        })
2448    };
2449
2450    // Auto-bump depth to Cycle for any dryrun mode that
2451    // installs the wrapper — cycles must dispatch for the
2452    // wrapper to have anything to short-circuit. Without the
2453    // bump, `dryrun=silent` / `dryrun=fields` / `dryrun=op`
2454    // would silently produce no output because the
2455    // phase-early-complete branch at executor.rs:2998 elides
2456    // the cycle loop when depth < Cycle.
2457    if dry_run.is_some() && diag.depth < ExecDepth::Cycle {
2458        diag.depth = ExecDepth::Cycle;
2459    }
2460
2461    // (OpenMetrics push URL is resolved in `SessionHost::setup` — the
2462    // metrics push reporter is a session-tier service.)
2463
2464    // Resolve the resume source BEFORE creating the new session
2465    // — `Session::new` eagerly remaps `logs/latest` at the new
2466    // session id, so any path resolution that depends on the old
2467    // `latest` target has to happen first. Stored as
2468    // `resume_target` and consulted later when constructing the
2469    // checkpoint writer + plan. SRD-44 §"Resume CLI surface".
2470    //
2471    // SRD-88 — per-execution: the session name (host already used the
2472    // same value to name the session dir) + the refine on-removed
2473    // policy, recomputed here from this execution's params.
2474    let scenario_for_session = params
2475        .get("scenario")
2476        .map(|s| s.as_str())
2477        .unwrap_or("default");
2478    let on_removed_policy: &str = params
2479        .get("on_removed")
2480        .map(|s| s.as_str())
2481        .unwrap_or("error");
2482    if let Some(plan) = refine_plan.as_ref() {
2483        let current_names: std::collections::HashSet<&str> =
2484            phases.keys().map(|s| s.as_str()).collect();
2485        let mut removed: Vec<&str> = plan
2486            .seen_identities
2487            .iter()
2488            .map(|(name, _)| name.as_str())
2489            .filter(|n| !current_names.contains(n))
2490            .collect();
2491        removed.sort();
2492        removed.dedup();
2493        if !removed.is_empty() {
2494            match on_removed_policy {
2495                "error" => {
2496                    return Err(format!(
2497                        "refine: workload removes {n} phase{plural} that have \
2498                         prior outcomes in this session:\n  - {names}\n\
2499                         Pass `on_removed=keep` to retain the prior outcomes \
2500                         (no work, no error); `on_removed=drop` is reserved \
2501                         (not yet implemented). Default `error` refuses to \
2502                         proceed so accidental axis-trim doesn't drop history \
2503                         silently.",
2504                        n = removed.len(),
2505                        plural = if removed.len() == 1 { "" } else { "s" },
2506                        names = removed.join("\n  - "),
2507                    ));
2508                }
2509                "keep" => {
2510                    crate::diag!(
2511                        crate::observer::LogLevel::Info,
2512                        "refine: on_removed=keep — retaining prior outcomes \
2513                         for {n} removed phase(s): {names}",
2514                        n = removed.len(),
2515                        names = removed.join(", ")
2516                    );
2517                }
2518                "drop" => {
2519                    crate::diag!(
2520                        crate::observer::LogLevel::Warn,
2521                        "refine: on_removed=drop is reserved — not yet \
2522                         implemented. Treating as `keep` (retaining prior \
2523                         outcomes) for now: {names}",
2524                        names = removed.join(", ")
2525                    );
2526                }
2527                other => {
2528                    return Err(format!(
2529                        "refine: unknown on_removed= policy '{other}'; \
2530                         expected `error` (default), `keep`, or `drop`"
2531                    ));
2532                }
2533            }
2534        }
2535    }
2536
2537    // SRD-88 — a CONCURRENT execution runs inside a scoped
2538    // `ExecutionContext` whose `exec_id` was allocated distinctly per
2539    // sibling; use it so each concurrent execution's metric rows /
2540    // metadata / `executions` row are separable. Outside a scoped
2541    // context (single-run), fall back to the SRD-77 verb/exec_id:
2542    // `refine` numbers from the prior outcomes' max+1, `run`/`resume`
2543    // start at 1 — byte-identical to before.
2544    let (exec_verb, exec_id_seed): (&'static str, u64) =
2545        match crate::execution_context::try_current() {
2546            Some(ctx) => ("run", ctx.exec_id),
2547            None => match (refine_plan.as_ref(), resume_target.as_ref()) {
2548                (Some(plan), Some(p)) if p.exists() => ("refine", plan.next_exec_id),
2549                (_, Some(p)) if p.exists() => ("resume", 1),
2550                _ => ("run", 1),
2551            },
2552        };
2553    // SRD-88 §2 — start this execution under the session: derive
2554    // its component (carrying `exec_id` + `workload`) as a child
2555    // of the session component. Phase components attach under
2556    // `execution.component`, so every metric inherits this
2557    // execution's identity without any tier redeclaring a label.
2558    let execution = crate::session::Execution::start(
2559        session,
2560        workload_file.as_deref().unwrap_or("inline"),
2561        scenario_for_session,
2562        exec_verb,
2563        exec_id_seed,
2564    );
2565    let exec_id = execution.exec_id;
2566
2567    // dryrun=controls: defer the tree walk until after phase
2568    // construction. `list_controls` implies depth=Phase, which
2569    // means every phase compiles and attaches its component —
2570    // that's when activity-scoped controls get declared — but
2571    // no cycles run. Walking here would only see session-root
2572    // controls. The renderer fires at the very end of the run,
2573    // just before the session returns.
2574
2575    // Direct the diagnostic log sink at <session_dir>/session.log so every
2576    // observer::log() call is captured durably, even under the TUI.
2577    // SRD-77 / SRD-88 — per-execution metadata + the in-flight
2578    // `executions` row. Written through the shared session reporter
2579    // but scoped to THIS execution's `exec_id`, so concurrent
2580    // executions sharing the session each record their own workload
2581    // / scenario / params without clobbering. `ended_at_nanos` /
2582    // `disposition` stay NULL until the shutdown-flush guard updates
2583    // them. `scope` is non-NULL only under refine.
2584    {
2585        let mut cli_keys: Vec<&String> = params.keys().collect();
2586        cli_keys.sort();
2587        let cli_text: String = cli_keys
2588            .iter()
2589            .filter_map(|k| params.get(*k).map(|v| format!("{k}={v}")))
2590            .collect::<Vec<_>>()
2591            .join("\n");
2592        let scope_for_row: Option<&str> = if refine_requested {
2593            Some(refine_scope.unwrap_or("missing"))
2594        } else {
2595            None
2596        };
2597        if let Ok(mut guard) = sqlite_reporter.lock()
2598            && let Some(r) = guard.as_mut()
2599        {
2600            let exec_id = execution.exec_id;
2601            let sid = session.id.clone();
2602            r.set_execution_metadata(&sid, exec_id, "workload", &execution.workload);
2603            r.set_execution_metadata(&sid, exec_id, "scenario", &execution.scenario);
2604            r.set_execution_metadata(
2605                &sid,
2606                exec_id,
2607                "start_time",
2608                &format!(
2609                    "{}",
2610                    std::time::SystemTime::now()
2611                        .duration_since(std::time::UNIX_EPOCH)
2612                        .unwrap()
2613                        .as_secs()
2614                ),
2615            );
2616            for (k, v) in &merged_params {
2617                r.set_execution_metadata(&sid, exec_id, &format!("param.{k}"), v);
2618            }
2619            // Reproducibility: the metrics db alone re-creates the run
2620            // (raw workload YAML + verbatim CLI params).
2621            if let Some(yaml) = workload_source_text.as_deref() {
2622                r.set_execution_metadata(&sid, exec_id, "workload_yaml", yaml);
2623            }
2624            r.set_execution_metadata(&sid, exec_id, "cli_params", &cli_text);
2625            r.insert_execution_start(
2626                &session.id,
2627                execution.exec_id,
2628                execution.verb,
2629                scope_for_row,
2630                execution.started_at_nanos,
2631                workload_source_text.as_deref().unwrap_or(""),
2632                &cli_text,
2633            );
2634        }
2635    }
2636
2637    // SRD-63 Push 9a: fire `EventType::SessionStart` once at the
2638    // workload root. Workloads bind structural rows to
2639    // this slot via `readouts: { on_session_start: … }`;
2640    // unbound slots stay quiet (no built-in default
2641    // emission today). Fires whether the run takes the
2642    // phased or single-activity branch below.
2643    {
2644        let session_ctx = crate::readout_context::LifecycleContext {
2645            event: crate::lifecycle::EventType::SessionStart,
2646            subject_name: session.id.clone(),
2647            subject_labels: String::new(),
2648            depth_indent: String::new(),
2649            use_color: crate::observer::use_color(),
2650            stick_reattached: stick_reattached.clone().unwrap_or_default(),
2651        };
2652        // SRD-106 D4 — when the stick_session rung engaged, seed
2653        // the slot with the `session_notice` builtin so the
2654        // announcement is the first notable event of the run,
2655        // ahead of any phase event. Workload-bound
2656        // on_session_start readouts still render after it; runs
2657        // without stick keep the slot's quiet default.
2658        let default_body = if stick_reattached.is_some() {
2659            crate::readouts::parse::bake("session_notice")
2660                .map(|(body, _)| body)
2661                .ok()
2662        } else {
2663            None
2664        };
2665        crate::readout_context::fire_lifecycle(
2666            crate::lifecycle::EventType::SessionStart,
2667            &workload_readouts,
2668            default_body,
2669            &session_ctx,
2670            Some(&sqlite_reporter),
2671        );
2672    }
2673
2674    // Merge all ops for param expansion and Polydat compilation.
2675    let _num_top_level_ops = ops.len();
2676    let mut all_ops_for_compile: Vec<nmbrs_workload::model::ParsedOp> = ops;
2677    all_ops_for_compile.extend(phase_ops_for_compile);
2678
2679    // === Pre-compile rewrites ===
2680    //
2681    // Stage 2 (post-M3.6): the workload-params kernel
2682    // (`crate::params::build_workload_params_kernel`) installs
2683    // every workload param as a `final <name> := <literal>`
2684    // binding on the workload-root kernel. Descendant scopes
2685    // see those bindings via `materialize_wiring_from_outer` + standard GK
2686    // scope-chain lookup. The legacy
2687    // `rewrite_workload_param_idents_in_bindings` text pass
2688    // (which substituted `{name}` → literal value before
2689    // compilation) was redundant once that path landed and
2690    // produced broken output for in-string placeholders
2691    // (`"{dataset}:{profile}"` → `""example":"default""`),
2692    // so it has been retired.
2693    //
2694    // What's left here: rewrite inline `{{expr}}` constructs to
2695    // named bindings so the Polydat compiler can hoist them as
2696    // `const __expr_N := …` entries. That pass is a bind-point
2697    // shape transform, not a value substitution — it operates
2698    // independently of workload params.
2699    crate::scope::rewrite_inline_exprs(&mut all_ops_for_compile)?;
2700
2701    // The workload-level `bindings:` (top-level YAML block) is
2702    // a first-class workload-scope input — separate from any
2703    // op's bindings. We pass it through to the compiler as a
2704    // distinct source so cursor declarations and other
2705    // workload-scoped Polydat statements land on the workload kernel
2706    // alongside the workload params, *without* going through
2707    // the op-binding param-ident rewrite (which would text-
2708    // substitute `{name}` placeholders inside string literals).
2709    // Polydat's standard string-interpolation handles `{name}` at
2710    // compile time against the `final <name> := <literal>`
2711    // bindings that workload-params injection installs (M3.6 path).
2712    // SRD-13f Push D: workload-level `bindings:` reach the
2713    // workload-root kernel ONLY through this explicit channel
2714    // now. The parser no longer merges workload bindings into
2715    // ops (`nmbrs_workload::parse::inline_block_sugar_into_op`
2716    // is the only remaining parser-time inlining; it operates
2717    // on block-level YAML sugar, not workload-level). Both
2718    // BindingsDef forms route through here:
2719    //   - PolydatSource: pass through verbatim.
2720    //   - Map: legacy semicolon-chain syntax translated to GK
2721    //     source lines via `legacy_chain_map_to_polydat_lines`.
2722    let workload_level_polydat: Option<String> = match &workload.bindings {
2723        nmbrs_workload::model::BindingsDef::PolydatSource(s) if !s.trim().is_empty() => {
2724            Some(s.clone())
2725        }
2726        nmbrs_workload::model::BindingsDef::Map(m) if !m.is_empty() => Some(
2727            crate::bindings::legacy_chain_map_to_polydat_lines(m)
2728                .map_err(|e| format!("workload-level bindings: {e}"))?,
2729        ),
2730        _ => None,
2731    };
2732
2733    // === Polydat Compilation ===
2734
2735    let workload_dir: Option<&std::path::Path> = if workload_is_bundled {
2736        // A catalog name is not a path — don't derive a bogus
2737        // directory from its namespace segments. Bundled
2738        // workloads get the cwd as their relative-resolution
2739        // context (same as inline workloads).
2740        Some(std::path::Path::new("."))
2741    } else {
2742        workload_file
2743            .as_ref()
2744            .and_then(|p| std::path::Path::new(p).parent())
2745            .or_else(|| Some(std::path::Path::new(".")))
2746    };
2747
2748    let mut config_refs: Vec<String> = params
2749        .values()
2750        .filter(|v| v.starts_with('{') && v.ends_with('}'))
2751        .map(|v| {
2752            let mut inner = v[1..v.len() - 1].to_string();
2753            // Expand workload params in config expressions
2754            for (key, value) in &workload_params {
2755                let placeholder = format!("{{{key}}}");
2756                if inner.contains(&placeholder) {
2757                    inner = inner.replace(&placeholder, value);
2758                }
2759            }
2760            inner
2761        })
2762        .collect();
2763    for (name, phase) in &phases {
2764        if phase.for_each.is_some() {
2765            continue; // for_each phase cycles resolved per-iteration
2766        }
2767        if let Some(ref c) = phase.cycles
2768            && c.starts_with('{')
2769            && c.ends_with('}')
2770        {
2771            let mut inner = c[1..c.len() - 1].to_string();
2772            for (key, value) in &workload_params {
2773                let placeholder = format!("{{{key}}}");
2774                if inner.contains(&placeholder) {
2775                    inner = inner.replace(&placeholder, value);
2776                }
2777            }
2778            config_refs.push(inner);
2779        }
2780        let _ = name; // suppress unused warning
2781    }
2782
2783    // Parse limit param for cursor clamping
2784    let cursor_limit: Option<u64> = merged_params.get("limit").and_then(|s| s.parse().ok());
2785
2786    // Build the workload-params root kernel first. This is the
2787    // canonical home for every declared workload parameter —
2788    // one `final <name> := <literal>` per param, compiled into
2789    // a stand-alone kernel whose outputs every descendant
2790    // `materialize_wiring_from_outer`s through. Replaces the prior approach
2791    // of patching params into multiple places (per-op binding
2792    // text substitution, per-kernel `final` injection in
2793    // `build_scope`). See `nmbrs-runtime::params`.
2794    // `build_workload_params_kernel` already prefixes its error
2795    // with "workload params kernel:" and appends the generated
2796    // source for diagnosis — propagate it verbatim rather than
2797    // re-wrapping (which doubled the prefix and dropped the
2798    // source dump).
2799    let params_kernel = crate::params::build_workload_params_kernel(&workload_params)?;
2800
2801    // Build the workload kernel directly as a subscope of the
2802    // params kernel via the typed PolydatKernel-controlled
2803    // construction path. Cells from params flow in via the
2804    // cascade — no late-binding step required.
2805    // Build the workload kernel as a subscope of the params
2806    // kernel and share ONE Arc across both consumers (the
2807    // scope tree's canonical reference AND the OpBuilder's
2808    // source kernel). A second materialize_subscope would
2809    // produce a sibling kernel with its own freshly-seeded
2810    // shared cells — disconnected from the canonical, so
2811    // result-binding writes from one chain wouldn't be visible
2812    // to the other. Sharing the Arc keeps the cell handles
2813    // identical end-to-end: detect_dialect's writes reach
2814    // await_index's reads through the same Mutex<Value>.
2815    // SRD-13f Push D: the workload-root kernel still owns the
2816    // canonical workload-scope bindings, but descendant kernels
2817    // (phase kernel, op-template kernel) carry a cascade copy
2818    // of the workload-level Polydat source as local matter — so
2819    // fiber.main_kernel evaluates dynamic workload bindings
2820    // (e.g. cycle-dependent) on its own state per cycle. See
2821    // `compile_from_scope` (and its callers in
2822    // `executor.rs::run_phase`) for the cascade-copy plumbing.
2823    // No eager pull at workload-root construction: that would
2824    // (a) fire side-effecting nodes like `testkit_throw_at` outside the
2825    // phase cascade context, and (b) cache stale values for
2826    // cycle-dependent bindings.
2827    let workload_canonical_kernel: std::sync::Arc<crate::scope_kernel::ScopeKernel> =
2828        std::sync::Arc::new(
2829            build_workload_root_kernel(
2830                &params_kernel,
2831                &all_ops_for_compile,
2832                workload_dir,
2833                polydat_lib_paths.clone(),
2834                strict,
2835                &config_refs,
2836                "outer workload bindings",
2837                cursor_limit,
2838                &workload_params,
2839                workload_level_polydat.as_deref(),
2840            )
2841            .map_err(|e| format!("outer workload bindings: {e}"))?,
2842        );
2843    let kernel = workload_canonical_kernel.clone();
2844
2845    // Strip workload-level adapter and the CLI `driver=` manifest
2846    // selector from op params (adapter is resolved per-phase/per-op,
2847    // not from workload params)
2848    for op in &mut all_ops_for_compile {
2849        op.params.remove("adapter");
2850        op.params.remove("driver");
2851    }
2852    for ops in phase_raw_ops.values_mut() {
2853        for op in ops.iter_mut() {
2854            op.params.remove("adapter");
2855            op.params.remove("driver");
2856        }
2857    }
2858
2859    let builder = Arc::new(OpBuilder::new(kernel));
2860
2861    // Unification — the scenario-tree executor is the sole
2862    // execution path. `Workload::synthesize_default_phase` (called
2863    // at load time) guarantees `phases` is non-empty for any
2864    // workload that has work to do; the empty-ops error fired
2865    // earlier in this fn covers the "literally nothing to run"
2866    // case. The legacy single-activity branch is gone.
2867    {
2868        // --- Phased execution ---
2869        let scenario_name = params
2870            .get("scenario")
2871            .map(|s| s.as_str())
2872            .unwrap_or("default");
2873        let scenario_nodes = resolve_scenario(&scenarios, &phase_order, scenario_name)?;
2874
2875        // Build the canonical scope tree (SRD 18b §"Canonical
2876        // traversal"). Mirrors the scenario tree 1:1 with parent
2877        // pointers, depth, and pragma slots. Today consumed by
2878        // observer pre-mapping and diagnostic display; future
2879        // steps drive execution from this tree directly.
2880        let scope_tree = {
2881            let mut t = crate::scope_tree::ScopeTree::build(scenario_name, &scenario_nodes);
2882            // Populate phase-leaf pragmas from each phase's GK
2883            // source and chain each scope's `PragmaSet` to its
2884            // parent's. SRD 18b §"Pragma chain along the scope
2885            // tree"; SRD 15 §"Pragma Scope".
2886            t.populate_pragmas(&phases);
2887            // Validate iter-var name uniqueness against workload
2888            // params and enclosing iter vars. Aliasing creates an
2889            // unambiguous spec-evaluation case the runtime can't
2890            // disambiguate; reject up-front.
2891            let wp_names: std::collections::HashSet<String> =
2892                workload_params.keys().cloned().collect();
2893            t.validate_iter_var_uniqueness(&wp_names)?;
2894            // SRD-83 follow-up — load-time authoring lints: every
2895            // `errors:` router spec must parse (bad verbs fail the
2896            // load, not the first runtime error), a router without a
2897            // catch-all rule warns, and `metric()` families in
2898            // stop/gate predicates are checked against the instrument
2899            // namespace (an unregistered family reads 0.0 silently).
2900            for w in crate::workload_lint::lint_workload(
2901                &workload.stop_when,
2902                phases.iter().map(|(k, v)| (k.as_str(), v)),
2903            )? {
2904                crate::diag!(crate::observer::LogLevel::Warn, "{w}");
2905            }
2906            // SRD-13d Phase 6 — extend the scope tree with
2907            // op-template children of every Phase node so the
2908            // op tier is visible to the elision classifier
2909            // and downstream diagnostics.
2910            t.extend_with_op_templates(&phases);
2911            // SRD-13d Phase 3 — workload-init scope-elision
2912            // pre-walk. Reads `HasGkMatter` on each AST node
2913            // and marks the corresponding scope-tree node
2914            // `materialised` (own kernel) or elided (binds
2915            // through parent). Conservative predicate today
2916            // (Definitions ⇒ materialise without hash-subset
2917            // refinement); Phase 6 tightens it.
2918            //
2919            // Scoped fields rather than `&workload` because
2920            // `workload.ops` was moved earlier in this fn —
2921            // the classifier reads only bindings + params +
2922            // phases anyway.
2923            let classify_inputs = crate::scope_elision::ClassifyInputs {
2924                bindings: &workload.bindings,
2925                params: &workload.params,
2926                phases: &phases,
2927            };
2928            crate::scope_elision::classify_and_mark(&mut t, &classify_inputs);
2929            std::sync::Arc::new(t)
2930        };
2931
2932        // dryrun=kernels: register the ride-along visitor BEFORE
2933        // the install loop so every install_kernel call (root
2934        // workload kernel + per-scope kernels in DFS pre-order)
2935        // streams its polydat source to stdout. Cleared after
2936        // the install loop runs (see the matching short-circuit
2937        // a few hundred lines below).
2938        if params.get("dryrun").map(|s| s.as_str()) == Some("kernels") {
2939            print_kernel_dump_header();
2940            crate::scope_tree::set_kernel_install_visitor(Some(Box::new(|node, _idx, kernel| {
2941                print_kernel_for_scope(node, kernel);
2942            })));
2943        }
2944
2945        // Install the workload-params module on the session node
2946        // (the workload root's parent) so identity chains
2947        // (`ScopeTree::ancestor_kernels` → the SRD-44/SRD-77
2948        // provenance hashes) include the module whose const
2949        // slots carry every param VALUE. The workload kernel is
2950        // built as a subscope of this module; installing it here
2951        // records that same relationship on the tree. Nearest-
2952        // ancestor kernel lookups are unaffected — the workload
2953        // root always has its own kernel, so walks stop there.
2954        scope_tree.install_kernel(scope_tree.root, std::sync::Arc::new(params_kernel));
2955
2956        // Install the canonical workload kernel (SRD 18b §"Iter
2957        // vars as scope outputs"). After this, intermediate
2958        // scopes (for_each, for_combinations, …) install their
2959        // own kernels in DFS pre-order below — each one's
2960        // synthesis reads its parent's manifest via the standard
2961        // Polydat API on the parent's installed kernel.
2962        scope_tree.install_kernel(scope_tree.workload_root_idx(), workload_canonical_kernel);
2963
2964        // M3.2: install per-scope kernels for for_each /
2965        // for_combinations nodes. Each kernel re-exports its
2966        // iteration variables and any referenced inherited
2967        // values as outputs (`const x := x` passthrough), so
2968        // children's standard `materialize_wiring_from_outer(parent)`
2969        // chains inheritance through arbitrary nesting depth
2970        // — no caller-side scope-tree walking for name
2971        // resolution at runtime.
2972        let workload_dir_owned: Option<std::path::PathBuf> = workload_dir.map(|p| p.to_path_buf());
2973        // M3.4b: scope kinds get categorized for synthesis.
2974        // For-comprehensions (ForEach, ForCombinations,
2975        // ForEachUnion) carry tuple iteration vars; do-loops
2976        // (DoWhile, DoUntil) carry an optional counter +
2977        // condition expression. Both produce installed kernels
2978        // that the unified dispatch_comprehension reads from.
2979        // reason: function-local, short-lived spec list built once per
2980        // install pass; the `OpTemplate`/`ParsedOp` variant dominates the
2981        // size, but boxing it would ripple `Box::new` + deref across every
2982        // construction and destructuring match arm below for no real gain
2983        // on a vector that is consumed immediately.
2984        #[allow(clippy::large_enum_variant)]
2985        enum InstallSpec {
2986            ForComprehension {
2987                idx: crate::scope_tree::ScopeNodeIdx,
2988                iter_vars: Vec<String>,
2989                spec_exprs: Vec<String>,
2990                /// SRD-13f Push E: phase-level `bindings:` folded
2991                /// into the for_each scope kernel when the phase
2992                /// declares both `for_each:` AND `bindings:`. The
2993                /// single install at the phase node materializes
2994                /// one kernel carrying both the iter-var
2995                /// declarations AND the phase-level bindings.
2996                /// Empty for pure-comprehension scope nodes
2997                /// (scenario-level `for_each:`) and for phase
2998                /// nodes without own bindings.
2999                phase_bindings: nmbrs_workload::model::BindingsDef,
3000            },
3001            DoLoop {
3002                idx: crate::scope_tree::ScopeNodeIdx,
3003                counter: Option<String>,
3004                condition: String,
3005            },
3006            /// SRD-13d Phase 9 — install a kernel for an
3007            /// op-template scope that classified as
3008            /// `materialised`. Flattened op-templates
3009            /// (`materialised == false`) get no install spec;
3010            /// their dispensers reach the parent kernel via
3011            /// `nearest_materialised`.
3012            OpTemplate {
3013                idx: crate::scope_tree::ScopeNodeIdx,
3014                op: nmbrs_workload::model::ParsedOp,
3015            },
3016            /// SRD-13d Phase 9 — install a phase-scope kernel
3017            /// for a phase that declares its own `bindings:`
3018            /// block (and no `for_each:` — that case is owned
3019            /// by the for_each install spec at the same node).
3020            /// Phases without bindings AND without for_each
3021            /// emit no install spec; the closure-lifetime
3022            /// kernel reference is the parent's by walker
3023            /// fall-through.
3024            /// Phase-scope kernel install for phases declaring
3025            /// their own `bindings:` block (and no `for_each:` —
3026            /// that case is owned by the for_each install spec
3027            /// at the same node). Also covers scenario-tree
3028            /// `bindings:` nodes (and the `set:` sugar that
3029            /// lowers to them) — the synthesizer is identical
3030            /// for both: parent-cascaded externs + the body's
3031            /// authored matter.
3032            Bindings {
3033                idx: crate::scope_tree::ScopeNodeIdx,
3034                bindings: nmbrs_workload::model::BindingsDef,
3035            },
3036        }
3037        let install_specs: Vec<InstallSpec> = scope_tree
3038            .iter_dfs()
3039            .filter_map(|(idx, node)| match &node.kind {
3040                crate::scope_tree::ScopeKind::Comprehension { comprehension } => {
3041                    // Representative iter_vars + spec_exprs for
3042                    // synthesis: dedup'd by var name. Walks the
3043                    // algebra AST directly via coordinate_specs
3044                    // — same dedup semantics the legacy
3045                    // scalar_bindings/Union-flatten path
3046                    // produced.
3047                    let pairs = comprehension.coordinate_specs();
3048                    let vars: Vec<String> = pairs.iter().map(|(v, _)| v.clone()).collect();
3049                    let specs: Vec<String> = pairs.iter().map(|(_, e)| e.clone()).collect();
3050                    Some(InstallSpec::ForComprehension {
3051                        idx,
3052                        iter_vars: vars,
3053                        spec_exprs: specs,
3054                        // Scope-tree Comprehension nodes (scenario-
3055                        // level `for_each:`) carry no phase-level
3056                        // bindings; the wrapping phase has its own
3057                        // scope-tree node and its own install spec
3058                        // (PhaseBindings or another ForComprehension).
3059                        phase_bindings: nmbrs_workload::model::BindingsDef::default(),
3060                    })
3061                }
3062                crate::scope_tree::ScopeKind::DoWhile { condition, counter } => {
3063                    Some(InstallSpec::DoLoop {
3064                        idx,
3065                        counter: counter.clone(),
3066                        condition: condition.clone(),
3067                    })
3068                }
3069                crate::scope_tree::ScopeKind::DoUntil { condition, counter } => {
3070                    Some(InstallSpec::DoLoop {
3071                        idx,
3072                        counter: counter.clone(),
3073                        condition: condition.clone(),
3074                    })
3075                }
3076                crate::scope_tree::ScopeKind::Phase { name } => {
3077                    // Phase-scope kernel installation, matter-gated
3078                    // per SRD-13d / SRD-67. Three cases:
3079                    //
3080                    //   1. Phase declares `for_each:` — treat as
3081                    //      a single-clause tuple comprehension.
3082                    //      The for_each scope owns the phase
3083                    //      node's kernel; phase `bindings:` (if
3084                    //      also present) need to fold into that
3085                    //      scope's matter (deferred — the legacy
3086                    //      parser-merge path keeps the bindings
3087                    //      reachable via op-bindings until the
3088                    //      for_each-with-bindings synthesizer
3089                    //      lands).
3090                    //
3091                    //   2. Phase declares only `bindings:` — own
3092                    //      subscope from those bindings layered
3093                    //      over the parent kernel.
3094                    //
3095                    //   3. Neither — no install spec; phase
3096                    //      scope's closure inherits the parent's
3097                    //      kernel reference via the walker's
3098                    //      fall-through (the matter-gated
3099                    //      pass-through).
3100                    let phase = phases.get(name.as_str())?;
3101                    if let Some(spec) = phase.for_each.as_ref() {
3102                        if !phase.metrics.is_empty() {
3103                            // Phase-level `metrics:` + phase-level
3104                            // `for_each:` isn't supported in the
3105                            // initial ship: the for_each scope
3106                            // synthesiser doesn't yet thread the
3107                            // metric-binding augmentation through, and
3108                            // the per-iteration completion-pull
3109                            // semantics want their own design pass.
3110                            // Reject loudly rather than silently
3111                            // dropping the metrics.
3112                            crate::diag!(
3113                                crate::observer::LogLevel::Error,
3114                                "phase '{name}': phase-level `metrics:` + phase-level \
3115                                 `for_each:` is not supported yet. Move the for_each to \
3116                                 scenario-tree level (so each iteration is its own phase \
3117                                 activation, each with its own metrics), or drop one. \
3118                                 Phase will be skipped.",
3119                            );
3120                            return None;
3121                        }
3122                        if phase.poll.is_some() {
3123                            // SRD-75: phase-poll + phase-level
3124                            // for_each isn't supported in the
3125                            // initial ship. The for_each scope
3126                            // synthesizer doesn't yet thread the
3127                            // poll augmentation through, and the
3128                            // combination's semantics
3129                            // (iterate-and-synchronize-each-cell?
3130                            // iterate-while-synchronizing?) wants
3131                            // its own design pass. Reject loudly.
3132                            crate::diag!(
3133                                crate::observer::LogLevel::Error,
3134                                "phase '{name}': `poll:` + phase-level `for_each:` is not \
3135                                 supported in the initial ship of SRD-75. Move the for_each \
3136                                 to scenario-tree level (so each iter is its own phase \
3137                                 activation), or drop one of the two. Phase will be skipped.",
3138                            );
3139                            return None;
3140                        }
3141                        // Delegate the for_each grammar to polydat (the
3142                        // single owner): `parse_inline` handles single- AND
3143                        // multi-clause, and `coordinate_specs()` yields the
3144                        // per-clause (var, spec) pairs — identical to the
3145                        // scenario-level path above. A single-clause spec
3146                        // yields exactly one pair, preserving prior behaviour.
3147                        let comp = match polydat::iteration::comprehension::spec::parse_inline(spec)
3148                        {
3149                            Ok(c) => c,
3150                            Err(e) => {
3151                                crate::diag!(
3152                                    crate::observer::LogLevel::Error,
3153                                    "phase '{name}' for_each '{spec}': {e}"
3154                                );
3155                                return None;
3156                            }
3157                        };
3158                        let pairs = comp.coordinate_specs();
3159                        let iter_vars: Vec<String> = pairs.iter().map(|(v, _)| v.clone()).collect();
3160                        let spec_exprs: Vec<String> =
3161                            pairs.iter().map(|(_, e)| e.clone()).collect();
3162                        // SRD-13f Push E: phases declaring both `for_each:`
3163                        // and `bindings:` fold the bindings into the for_each
3164                        // scope kernel (one kernel, one install). Pure-for_each
3165                        // phases pass an empty `BindingsDef` (no-op).
3166                        //
3167                        // Route through the SAME phase-scope synthesis the
3168                        // non-for_each branch uses, so phase-level `metrics:` /
3169                        // `poll:` and an inline `optimize.objective` (SRD-86)
3170                        // are folded into the for_each kernel too — not just the
3171                        // author's raw `bindings:`. The synthesizer returns the
3172                        // raw bindings unchanged when there is nothing to add,
3173                        // so plain for_each phases are unaffected.
3174                        let phase_bindings =
3175                            match crate::scope::synthesize_phase_scope_bindings(phase) {
3176                                Ok(b) => b,
3177                                Err(e) => {
3178                                    crate::diag!(
3179                                        crate::observer::LogLevel::Error,
3180                                        "phase '{name}': phase-scope synthesis: {e}"
3181                                    );
3182                                    return None;
3183                                }
3184                            };
3185                        Some(InstallSpec::ForComprehension {
3186                            idx,
3187                            iter_vars,
3188                            spec_exprs,
3189                            phase_bindings,
3190                        })
3191                    } else {
3192                        // SRD-75: when the phase declares `poll:`,
3193                        // synthesise capture-as-shared-cell
3194                        // declarations + the `__poll_until`
3195                        // predicate binding into the phase scope's
3196                        // bindings, even when the phase has no
3197                        // author-declared `bindings:` of its own.
3198                        // The synthesised bindings flow through the
3199                        // same `build_phase_scope_kernel` path as
3200                        // any other phase-level bindings; phase-
3201                        // poll has no synthesizer-specific code
3202                        // path.
3203                        let synth = match crate::scope::synthesize_phase_scope_bindings(phase) {
3204                            Ok(b) => b,
3205                            Err(e) => {
3206                                crate::diag!(
3207                                    crate::observer::LogLevel::Error,
3208                                    "phase '{name}': SRD-75 phase-poll synthesis: {e}",
3209                                );
3210                                return None;
3211                            }
3212                        };
3213                        if !synth.is_empty() {
3214                            Some(InstallSpec::Bindings {
3215                                idx,
3216                                bindings: synth,
3217                            })
3218                        } else {
3219                            None
3220                        }
3221                    }
3222                }
3223                crate::scope_tree::ScopeKind::OpTemplate { name } => {
3224                    // SRD-13d Phase 9: install a per-op kernel
3225                    // ONLY for materialised op-templates. The
3226                    // scope-elision pre-walk already set the
3227                    // mark; we just gate on it here.
3228                    if node.materialised != Some(true) {
3229                        return None;
3230                    }
3231                    // Find the ParsedOp by walking up to the
3232                    // OWNING phase first, then resolving by name
3233                    // within that phase. Two phases can both
3234                    // declare an op named e.g. `select_ann` with
3235                    // very different bodies; a flat
3236                    // `phases.values().flat_map(|p| p.ops.iter())
3237                    // .find(...)` would pick whichever phase the
3238                    // HashMap iterator yielded first, silently
3239                    // compiling pvs_query's body into ann_query's
3240                    // op-template kernel (and vice versa).
3241                    let owning_phase: Option<&str> = {
3242                        let mut cursor = scope_tree.nodes[idx].parent;
3243                        let mut found: Option<&str> = None;
3244                        while let Some(p) = cursor {
3245                            if let crate::scope_tree::ScopeKind::Phase { name: pname } =
3246                                &scope_tree.nodes[p].kind
3247                            {
3248                                found = Some(pname.as_str());
3249                                break;
3250                            }
3251                            cursor = scope_tree.nodes[p].parent;
3252                        }
3253                        found
3254                    };
3255                    owning_phase
3256                        .and_then(|pname| phases.get(pname))
3257                        .and_then(|phase| phase.ops.iter().find(|op| op.name == *name))
3258                        .cloned()
3259                        .map(|op| InstallSpec::OpTemplate { idx, op })
3260                }
3261                crate::scope_tree::ScopeKind::Bindings { source } => {
3262                    // Scenario-tree `bindings:` block (also the
3263                    // canonical lowered form of `set:` sugar)
3264                    // installs through the same synthesizer
3265                    // phases use for their own `bindings:`. The
3266                    // body source compiles into a scope kernel
3267                    // that publishes its `final`/`init`/cycle
3268                    // bindings as outputs; descendants read
3269                    // those through the canonical scope chain
3270                    // (no HashMap merges, no side-channel
3271                    // resolvers). Shadowing of upstream names is
3272                    // enforced by the local-final transit-
3273                    // suppression rule in
3274                    // `materialize_wiring_from_outer` — uniform
3275                    // with every other scope.
3276                    Some(InstallSpec::Bindings {
3277                        idx,
3278                        bindings: nmbrs_workload::model::BindingsDef::PolydatSource(source.clone()),
3279                    })
3280                }
3281                _ => None,
3282            })
3283            .collect();
3284
3285        for install_spec in install_specs {
3286            let idx = match &install_spec {
3287                InstallSpec::ForComprehension { idx, .. } => *idx,
3288                InstallSpec::DoLoop { idx, .. } => *idx,
3289                InstallSpec::OpTemplate { idx, .. } => *idx,
3290                InstallSpec::Bindings { idx, .. } => *idx,
3291            };
3292            // Nearest installed ancestor — skips Scenario /
3293            // IncludedScenario nodes that don't install kernels
3294            // (those are pass-through structural).
3295            let parent_kernel = {
3296                let mut cursor = scope_tree.nodes[idx].parent;
3297                let mut found: Option<std::sync::Arc<crate::scope_kernel::ScopeKernel>> = None;
3298                while let Some(p) = cursor {
3299                    if let Some(k) = scope_tree.nodes[p].cached_kernel.get() {
3300                        found = Some(k.clone());
3301                        break;
3302                    }
3303                    cursor = scope_tree.nodes[p].parent;
3304                }
3305                found.expect("workload root always has an installed kernel")
3306            };
3307            let parent_manifest = extract_manifest(parent_kernel.program());
3308            let context = format!("scope idx {idx} ({})", scope_tree.nodes[idx].kind.label(),);
3309
3310            let result = match install_spec {
3311                InstallSpec::ForComprehension {
3312                    iter_vars,
3313                    spec_exprs,
3314                    phase_bindings,
3315                    ..
3316                } => {
3317                    let bindings: Vec<(String, String)> = iter_vars
3318                        .iter()
3319                        .cloned()
3320                        .zip(spec_exprs.iter().cloned())
3321                        .collect();
3322                    // SRD-13f Push E: translate phase-level
3323                    // `bindings:` into the Polydat source the
3324                    // for_each synthesiser folds in. PolydatSource
3325                    // form passes verbatim; Map form serialises
3326                    // to `name := expr\n` lines.
3327                    let phase_bindings_source = match phase_bindings {
3328                        nmbrs_workload::model::BindingsDef::PolydatSource(s)
3329                            if !s.trim().is_empty() =>
3330                        {
3331                            Some(s)
3332                        }
3333                        nmbrs_workload::model::BindingsDef::Map(m) if !m.is_empty() => {
3334                            let mut out = String::new();
3335                            for (name, expr) in &m {
3336                                out.push_str(&format!("{name} := {expr}\n"));
3337                            }
3338                            Some(out)
3339                        }
3340                        _ => None,
3341                    };
3342                    crate::scope_synth::build_for_each_scope_kernel(
3343                        &bindings,
3344                        &parent_manifest,
3345                        &parent_kernel,
3346                        &workload_params,
3347                        polydat_lib_paths.clone(),
3348                        workload_dir_owned.as_deref(),
3349                        strict,
3350                        &context,
3351                        phase_bindings_source.as_deref(),
3352                    )
3353                }
3354                InstallSpec::DoLoop {
3355                    counter, condition, ..
3356                } => crate::scope::build_do_loop_scope_kernel(
3357                    counter.as_deref(),
3358                    &condition,
3359                    &parent_manifest,
3360                    &parent_kernel,
3361                    &workload_params,
3362                    polydat_lib_paths.clone(),
3363                    workload_dir_owned.as_deref(),
3364                    strict,
3365                    &context,
3366                ),
3367                InstallSpec::OpTemplate { op, .. } => {
3368                    // SRD-13d Phase 9 — synthesize the op-
3369                    // template kernel layered over the parent.
3370                    // Includes op-level bindings + cascaded
3371                    // parent externs; materialize_wiring_from_outer chains
3372                    // values in at runtime.
3373                    // The scope module stays on the node for the fiber
3374                    // engine's per-op images (`crate::fiber_engine`).
3375                    crate::scope::build_op_template_scope_kernel(
3376                        &op,
3377                        &parent_manifest,
3378                        &parent_kernel,
3379                        &workload_params,
3380                        polydat_lib_paths.clone(),
3381                        workload_dir_owned.as_deref(),
3382                        strict,
3383                        kernel_opt,
3384                        &context,
3385                    )
3386                }
3387                InstallSpec::Bindings { bindings, .. } => {
3388                    // Single install path for both phase-level
3389                    // `bindings:` and scenario-tree-level
3390                    // `bindings:` (including the `set:` sugar
3391                    // form that lowers to it). The synthesizer
3392                    // cascades workload params + parent
3393                    // outputs/inputs as externs and appends the
3394                    // body verbatim; Polydat handles workload-param
3395                    // interpolation and expression evaluation
3396                    // at compile time. Lexical shadowing of an
3397                    // upstream `final NAME` by the body's own
3398                    // `const NAME := …` is enforced by the
3399                    // local-final transit-suppression rule in
3400                    // `materialize_wiring_from_outer`.
3401                    crate::scope::build_phase_scope_kernel(
3402                        &bindings,
3403                        &parent_manifest,
3404                        &parent_kernel,
3405                        &workload_params,
3406                        polydat_lib_paths.clone(),
3407                        workload_dir_owned.as_deref(),
3408                        strict,
3409                        &context,
3410                    )
3411                }
3412            };
3413
3414            match result {
3415                Ok(kernel) => {
3416                    let _ = scope_tree.install_kernel(idx, std::sync::Arc::new(kernel));
3417                }
3418                Err(e) => {
3419                    // Kernel synthesis failure is a hard error
3420                    // regardless of strict mode: a phase whose GK
3421                    // source doesn't compile literally cannot run.
3422                    // Letting the walk continue past the failure
3423                    // only delays the bad news — the phase will
3424                    // fail mid-run with a less helpful diagnostic
3425                    // (or, worse, run with stale / partial
3426                    // kernels installed for sibling scopes). The
3427                    // earlier "warn-and-continue" behavior dates
3428                    // from before strict mode existed; with the
3429                    // strict-mode behavior being the only sane
3430                    // default, the non-strict branch was
3431                    // effectively a footgun that turned compile
3432                    // errors into silent partial runs.
3433                    return Err(format!("scope kernel synthesis failed: {e}"));
3434                }
3435            }
3436        }
3437
3438        crate::diag!(
3439            crate::observer::LogLevel::Info,
3440            "scenario '{scenario_name}':\n{}",
3441            format_scenario_tree(&scenario_nodes, &phases)
3442        );
3443
3444        // Observer is passed from the caller (default: StderrObserver).
3445
3446        // ─── Unified walker: structural pre-map pass ─────────────────
3447        //
3448        // Per SRD 18b §"Single Walker Contract", there is ONE walker
3449        // function (`crate::executor::execute_tree`). It runs twice
3450        // here: first at depth=Phase to populate the scene tree (so
3451        // resume_plan / declare_scene_tree_phases / pre_map_pending_uses
3452        // can read the populated tree), then again at the configured
3453        // depth to actually execute. SceneTree::push is idempotent
3454        // by `(parent, kind, name)` so the second pass re-encounters
3455        // every node from the first without duplicating.
3456        //
3457        // The pre-map ExecCtx uses stub post-pre-map fields
3458        // (checkpoint_writer = None, fresh resume_plan, fresh
3459        // resource_pool); they're updated to the real values after
3460        // pre-map produces the tree.
3461        let schedule_spec = std::sync::Arc::new(match params.get("schedule") {
3462            Some(s) => crate::scheduler::ScheduleSpec::parse(s)
3463                .map_err(|e| format!("schedule= param: {e}"))?,
3464            None => crate::scheduler::ScheduleSpec::default_serial(),
3465        });
3466        // `&str` → `&'static str` so the activity config can
3467        // carry the mode label across thread boundaries
3468        // without lifetime gymnastics. Every mode the resolver
3469        // above produces must appear here, otherwise the
3470        // wrapper-install path silently sees `None` and
3471        // DRYRUN never installs.
3472        let dry_run_static: Option<&'static str> = match dry_run {
3473            Some("silent") => Some("silent"),
3474            Some("fields") => Some("fields"),
3475            Some("cycle") => Some("cycle"),
3476            Some("op") => Some("op"),
3477            _ => None,
3478        };
3479
3480        // phases=<pattern> filter (bareword / glob / regex). When
3481        // unset, every phase runs. When set, the planner's
3482        // scenario-tree walker skips phase activations whose name
3483        // doesn't match AND elides scope subtrees with no
3484        // matching descendant.
3485        let phase_filter: Option<Arc<crate::phase_filter::PhasePattern>> = match params
3486            .get("phases")
3487            .map(|s| s.as_str())
3488            .filter(|s| !s.is_empty())
3489        {
3490            None => None,
3491            Some(src) => {
3492                let pat = crate::phase_filter::PhasePattern::parse(src)
3493                    .map_err(|e| format!("phases= param: {e}"))?;
3494                crate::diag!(
3495                    crate::observer::LogLevel::Info,
3496                    "phases=<filter>: pattern '{src}' ({}{})",
3497                    if pat.negated() { "negated " } else { "" },
3498                    pat.dialect().as_str()
3499                );
3500                Some(Arc::new(pat))
3501            }
3502        };
3503        let resource_pool = Arc::new(crate::resource_pool::ResourcePool::new());
3504        // SRD-104 — point the resource bridge every kernel tree resolves
3505        // through at this session's pool, so kernel nodes can reach a live
3506        // pool-owned resource (e.g. a CQL session handle) by fingerprint via
3507        // their tree's resource scope. The pool stays the definitive owner.
3508        crate::resource_pool::install_accessor(&resource_pool);
3509        let initial_scene_tree_path = vec![crate::checkpoint::PathSegment::Scenario(
3510            scenario_name.to_string(),
3511        )];
3512        // SRD-82 — the session root error policy. Every shell resolves
3513        // its own from this (inherit or derive); equal configs share
3514        // one instance, parsed once per session.
3515        let root_error_policy = crate::error_policy::ErrorPolicy::root(
3516            crate::error_policy::PolicyConfig::new(error_spec.clone(), error_rate_max),
3517        );
3518        // SRD-83 — build the workload execution shell (SRD-82's
3519        // outermost shell). Its stop conditions are the workload's
3520        // `stop_when:` declarations whose `each:` names the workload
3521        // itself (`self`/`workload`), compiled once against the
3522        // workload root's cached kernel — the same native-scope binding
3523        // every other shell uses, never a conjured root. The remaining
3524        // `each: phase` declarations fan out to the per-phase activity
3525        // build (see `executor.rs`); the unfiltered list rides on
3526        // `ExecCtx.workload_stop_when` for that gathering.
3527        //
3528        // The error-rate breach stays a per-phase concern (each phase
3529        // already trips on its own `error_rate_max`), so no default
3530        // error-rate condition is installed at the workload aggregate.
3531        let workload_shell = {
3532            use nmbrs_workload::model::ScopeLevel;
3533            // SRD-82 Part 3/6 — the scenario-graph default `*Failed:stop`:
3534            // any child phase whose outcome is Failed halts the remaining
3535            // walk and records `Interrupted + Failed` (a fault). Expressed
3536            // as the SRD-83 stop condition `children_failed > 0` with a
3537            // `fail` effect, so it rides the same workload-shell mechanism
3538            // as declared conditions and reaches concurrent / cross-subtree
3539            // siblings the local `Err` cascade can't. First in the list →
3540            // a failed child trips it before any declared graceful rule.
3541            let mut conditions: Vec<crate::stop_conditions::StopConditionDecl> =
3542                vec![crate::stop_conditions::StopConditionDecl {
3543                    when: "children_failed > 0".to_string(),
3544                    effect: crate::phase_outcome::Outcome::failed(),
3545                    reason: None,
3546                    target: crate::stop_conditions::StopScope::Workload,
3547                    // The default stop-on-error drains cooperatively.
3548                    cancel_ops: false,
3549                }];
3550            // Declared workload-level conditions (`each ∋ self|workload`).
3551            // A declared trip defaults to a graceful `stop`
3552            // (Interrupted+Succeeded): nothing failed, later phases are
3553            // deliberately skipped.
3554            conditions.extend(
3555                workload
3556                    .stop_when
3557                    .iter()
3558                    .filter(|c| {
3559                        c.each
3560                            .iter()
3561                            .any(|l| matches!(l, ScopeLevel::SelfScope | ScopeLevel::Workload))
3562                    })
3563                    .map(|c| crate::stop_conditions::StopConditionDecl {
3564                        // Same `{param}` interpolation as phase-level stop_when
3565                        // (executor build_activity_config_for_phase) so a workload
3566                        // breaker threshold can be a modular workload param.
3567                        when: expand_workload_params(&c.when, &workload_params),
3568                        effect: crate::stop_conditions::StopConditionDecl::effect_from_str(
3569                            c.effect.as_deref(),
3570                            crate::phase_outcome::Outcome::interrupted(),
3571                        ),
3572                        reason: None,
3573                        // Detected at the workload shell; `at:` (default =
3574                        // innermost of `per:`/`each:`, here `workload`) selects
3575                        // the action scope.
3576                        target: crate::executor::resolve_stop_scope(c.at, &c.each),
3577                        // `action: abort` → cancel in-flight ops at the trip site.
3578                        cancel_ops: crate::stop_conditions::StopConditionDecl::action_cancels_ops(
3579                            c.effect.as_deref(),
3580                        ),
3581                    }),
3582            );
3583            let set = match scope_tree.nodes[scope_tree.workload_root_idx()]
3584                .cached_kernel
3585                .get()
3586            {
3587                Some(root_kernel) => crate::stop_conditions::StopConditionSet::build_for_phase(
3588                    root_kernel,
3589                    &conditions,
3590                )
3591                .unwrap_or_else(|e| {
3592                    crate::diag!(
3593                        crate::observer::LogLevel::Error,
3594                        "workload stop-condition compile failed: {e}"
3595                    );
3596                    crate::stop_conditions::StopConditionSet::empty()
3597                }),
3598                _ => crate::stop_conditions::StopConditionSet::empty(),
3599            };
3600            std::sync::Arc::new(crate::workload_shell::WorkloadShell::new(set))
3601        };
3602
3603        // SRD-71 P3 — phase-scoped CLI parameter overrides
3604        // (`<phase-pattern>.<param>=<value>`). Parsed from the raw
3605        // args (parse_params skips dotted keys), validated against
3606        // the declared phase names so a never-matching pattern is
3607        // a startup error instead of a silent no-op.
3608        let phase_param_overrides =
3609            std::sync::Arc::new(crate::phase_params::parse_overrides(&args)?);
3610        crate::phase_params::validate_against_phases(
3611            &phase_param_overrides,
3612            phases.keys().map(|s| s.as_str()),
3613        )?;
3614
3615        let mut exec_ctx = crate::executor::ExecCtx {
3616            phases: phases.clone(),
3617            optimize_objective: None,
3618            optimize_objective_value: None,
3619            optimize_servo: None,
3620            phase_param_overrides,
3621            workload_shell,
3622            workload_stop_when: workload.stop_when.clone(),
3623            daemon_stop: None,
3624            workload_readouts: workload_readouts.clone(),
3625            cli_readout_override: cli_readout_override.clone(),
3626            workload_params: workload_params.clone(),
3627            wrappers_override: workload_wrappers_override.clone(),
3628            wrap_default_order: cli_wrap_default_order.clone(),
3629            workload_scope: builder.source_kernel().clone(),
3630            polydat_lib_paths: polydat_lib_paths.clone(),
3631            workload_dir: workload_dir.map(|p| p.to_path_buf()),
3632            strict,
3633            driver: driver.clone(),
3634            merged_params: merged_params.clone(),
3635            dry_run: dry_run_static,
3636            phase_filter: phase_filter.clone(),
3637            refine_plan: refine_plan.clone(),
3638            diag: {
3639                let mut d = diag.clone();
3640                d.depth = ExecDepth::Phase;
3641                d
3642            },
3643            // The pre-map pass walks at depth=Phase but is NOT
3644            // execution: the structural-only sentinel that fires
3645            // `set_phase_running` + `_completed` in the walker
3646            // (intended for the dryrun=phase summary) is
3647            // suppressed via this flag so the TUI's scene tree
3648            // doesn't start life with every phase already
3649            // Completed. Flipped back to false at line ~2675
3650            // before the real execution pass.
3651            pre_map_only: true,
3652            seq_type,
3653            concurrency,
3654            rate,
3655            error_spec: error_spec.clone(),
3656            tries,
3657            error_rate_max,
3658            error_policy: root_error_policy,
3659            session_id: session_id.clone(),
3660            exec_id,
3661            workload_name: execution.workload.clone(),
3662            label_stack: Vec::new(),
3663            // SRD-88 §2 — phase/activity components attach under the
3664            // EXECUTION component (which declares `exec_id` +
3665            // `workload`), not the session root. The session root
3666            // is the shared `session=<id>` ancestor above it.
3667            session_component: execution.component.clone(),
3668            cadence_reporter: cadence_reporter.clone(),
3669            stop_handle: stop_handle.clone(),
3670            observer: observer.clone(),
3671            scope_tree: scope_tree.clone(),
3672            schedule_spec: schedule_spec.clone(),
3673            current_parent_kernel: scope_tree.nodes[scope_tree.workload_root_idx()]
3674                .cached_kernel
3675                .get()
3676                .cloned(),
3677            workload_source: workload_file.as_ref().and_then(|path| {
3678                workload_source_text.as_ref().map(|text| {
3679                    std::sync::Arc::new(crate::executor::WorkloadSource {
3680                        path: path.clone(),
3681                        text: text.clone(),
3682                    })
3683                })
3684            }),
3685            // Stub post-pre-map fields: replaced after the pre-map
3686            // walk populates the scene tree. Pre-map walks at depth
3687            // Phase, so no run_phase / run_do_loop / checkpoint
3688            // events fire — the stubs are not consulted.
3689            checkpoint_writer: None,
3690            resume_plan: std::sync::Arc::new(crate::checkpoint::ResumePlan::fresh()),
3691            sqlite_reporter: sqlite_reporter.clone(),
3692            resource_pool: resource_pool.clone(),
3693            scene_tree_parent_id: 0,
3694            scene_tree_path: initial_scene_tree_path.clone(),
3695            current_scope_idx: 0,
3696        };
3697
3698        // One Walker: seed the scope cursor at the scenario layer (the single
3699        // child of the workload root) so the top-level scenario nodes resolve
3700        // positionally against its children, not by AST match.
3701        exec_ctx.current_scope_idx = exec_ctx.scope_tree.scenario_root_idx();
3702
3703        // Install empty SceneTree global; the walker populates it.
3704        crate::scene_tree::install_global(crate::scene_tree::SceneTree::new());
3705
3706        // Pre-map structural pass. Errors propagate in strict mode
3707        // (SRD-15 §"Empty Iteration Sources"); otherwise the walker
3708        // logs and continues — downstream code handles the partial
3709        // / empty tree.
3710        let pre_map_result = crate::executor::execute_tree(&mut exec_ctx, &scenario_nodes).await;
3711        let pre_mapped_tree = match pre_map_result {
3712            Ok(()) => {
3713                let tree = crate::scene_tree::current();
3714                if let Some(ref t) = tree {
3715                    observer.scenario_pre_mapped(t);
3716                }
3717                tree
3718            }
3719            Err(e) if strict => return Err(e),
3720            Err(e) => {
3721                crate::diag!(
3722                    crate::observer::LogLevel::Warn,
3723                    "pre-map walker failed (scope hierarchy will be flat in summaries / TUI): {e}"
3724                );
3725                None
3726            }
3727        };
3728
3729        // dryrun=kernels short-circuit: pre-map already ran;
3730        // the install-kernel visitor (registered above before
3731        // execute_tree) streamed each scope's polydat source
3732        // to stdout as the walk encountered it. Print the
3733        // legend + exit cleanly.
3734        if params.get("dryrun").map(|s| s.as_str()) == Some("kernels") {
3735            print_kernel_dump_legend();
3736            crate::scope_tree::set_kernel_install_visitor(None);
3737            return Ok(());
3738        }
3739
3740        // --- Checkpoint writer + resume plan (SRD-44 / SRD-44a) ---
3741        //
3742        // The writer file lives at `<session-dir>/checkpoint.jsonl`
3743        // — an append-only JSONL event log per SRD-44a. Resume from
3744        // an explicit prior session is wired through the
3745        // `--resume <session>` / `--resume-latest` CLI surface
3746        // (see runner CLI parsing); for a fresh session the writer
3747        // starts empty and the plan reruns everything.
3748        // SRD-88 — the writer + resume doc are SESSION-tier (created
3749        // once in `SessionHost::setup`, holding the single resume lock).
3750        // This execution shares them; it derives its own resume plan
3751        // below from `saved_doc` + its pre-map.
3752        let checkpoint_writer = host.checkpoint_writer.clone();
3753        let saved_doc = host.saved_doc.clone();
3754        let invocation = saved_doc.as_ref().map(|d| d.invocation + 1).unwrap_or(1);
3755
3756        // End-of-run notices: drops on success OR error path.
3757        //
3758        //  - Resume hint: when checkpoint state shows
3759        //    incomplete idempotent phases (SRD-44), advise the
3760        //    operator how to resume.
3761        //  - Keep-purge forecast: when the next new session
3762        //    would auto-purge sessions under the keep cap
3763        //    (SRD-45), let the operator know how many and how
3764        //    to disable.
3765        let parent_for_keep_check = if let Some(p) = session.output_dir.parent() {
3766            p.to_path_buf()
3767        } else {
3768            crate::session::default_sessions_root()
3769        };
3770        let session_keep = crate::session::resolve_session_dir(&args).session_keep;
3771        struct EndOfRunNoticeGuard {
3772            writer: std::sync::Arc<crate::checkpoint::CheckpointWriter>,
3773            parent: std::path::PathBuf,
3774            keep_cap: usize,
3775        }
3776        impl Drop for EndOfRunNoticeGuard {
3777            fn drop(&mut self) {
3778                if let Some(hint) = self.writer.resume_hint() {
3779                    // Through the observer, one line per log call —
3780                    // NOT a raw eprintln!: this drop can fire while
3781                    // the TUI still holds the terminal in raw mode,
3782                    // where a bare `\n` does not return the carriage
3783                    // and a stderr write bypasses the render sink —
3784                    // each line then starts at the previous line's
3785                    // end column (the end-of-session staircase,
3786                    // observed 2026-08-05). The log path is owned by
3787                    // the surface channel (SRD-87) in both TUI and
3788                    // plain modes, so it renders correctly in each.
3789                    for line in hint.lines() {
3790                        crate::diag!(crate::observer::LogLevel::Info, "{line}");
3791                    }
3792                }
3793                let n = crate::session::forecast_keep_purge(&self.parent, self.keep_cap);
3794                if n > 0 {
3795                    crate::diag!(
3796                        crate::observer::LogLevel::Info,
3797                        "the next new nmbrs session will auto-purge {n} prior session \
3798                         director{plural} under {} due to --session-keep={cap}. \
3799                         To disable: --session-keep=0 (or NMBRS_SESSION_KEEP=0). \
3800                         To raise the cap: --session-keep=<bigger>.",
3801                        self.parent.display(),
3802                        plural = if n == 1 { "y" } else { "ies" },
3803                        cap = self.keep_cap,
3804                    );
3805                }
3806            }
3807        }
3808        let _eor_notice_guard = EndOfRunNoticeGuard {
3809            writer: checkpoint_writer.clone(),
3810            parent: parent_for_keep_check,
3811            keep_cap: session_keep,
3812        };
3813        let resume_plan =
3814            if let (Some(saved), Some(tree)) = (saved_doc.as_ref(), pre_mapped_tree.as_ref()) {
3815                let candidates =
3816                    crate::checkpoint::scene_tree_resume_candidates(tree, &scope_tree, &phases);
3817                std::sync::Arc::new(crate::checkpoint::ResumePlan::from_checkpoint(
3818                    saved,
3819                    &candidates,
3820                    &workload_params,
3821                ))
3822            } else {
3823                std::sync::Arc::new(crate::checkpoint::ResumePlan::fresh())
3824            };
3825
3826        // Declare every pre-mapped phase into the writer so a
3827        // future resume can tell "didn't run yet" from "wasn't
3828        // planned". Idempotent — re-declaring an entry the
3829        // writer already restored from disk is a no-op.
3830        if let Some(tree) = pre_mapped_tree.as_ref() {
3831            crate::checkpoint::declare_scene_tree_phases(&checkpoint_writer, tree, &phases);
3832        }
3833
3834        if resume_plan.is_resume {
3835            let skip = resume_plan.skip_count();
3836            let mismatch = resume_plan.mismatch_count();
3837            let cursor = resume_plan.cursor_resume_count();
3838            crate::diag!(
3839                crate::observer::LogLevel::Info,
3840                "resume: invocation #{invocation} — \
3841                 {skip} skip, {mismatch} mismatched, {cursor} cursor-resume"
3842            );
3843        }
3844
3845        // SRD-35 Push D: seed the resource pool's per-key
3846        // `pending_uses` counter before any phase runs. The
3847        // walker is a pure read of the pre-mapped tree +
3848        // session-level params; it doesn't instantiate any
3849        // adapter or open any resource. After this, the pool
3850        // can close `Shared`/`PerScenario` entries the moment
3851        // their last predicted phase detaches, instead of
3852        // holding them until session end.
3853        if let Some(tree) = pre_mapped_tree.as_ref() {
3854            crate::resource_pool::pre_map_pending_uses(
3855                &resource_pool,
3856                tree,
3857                &phases,
3858                &driver,
3859                &merged_params,
3860            )?;
3861            // SRD-117 §9.1 — show each adapter that asks every op the
3862            // scenario will reach, so a shared resource can know its
3863            // whole configuration, and exist, before the first phase.
3864            let positions: Arc<dyn crate::adapter::AdapterPositions> =
3865                Arc::new(crate::checkpoint::SessionPositions::new(
3866                    checkpoint_writer.clone(),
3867                    resume_plan.is_resume,
3868                ));
3869            crate::resource_pool::pre_map_adapter_ops(
3870                tree,
3871                &phases,
3872                &driver,
3873                &crate::adapter::PreMapContext {
3874                    pool: &resource_pool,
3875                    params: &merged_params,
3876                    dry_run: dry_run.is_some() || diag.depth < ExecDepth::Cycle,
3877                    session_dir: checkpoint_writer.path().parent(),
3878                    positions: Some(positions),
3879                },
3880            )?;
3881        }
3882
3883        // ─── Unified walker: execution pass ──────────────────────────
3884        //
3885        // Update the post-pre-map fields on the same `exec_ctx`
3886        // used for the pre-map pass: real `checkpoint_writer`,
3887        // resolved `resume_plan`, restored execution depth. Per
3888        // SRD 18b §"Single Walker Contract" point 1, this is the
3889        // SAME walker function — `execute_tree` — invoked again at
3890        // the configured depth. SceneTree::push is idempotent so
3891        // every node the pre-map pass pushed is reused.
3892        exec_ctx.checkpoint_writer = Some(checkpoint_writer.clone());
3893        exec_ctx.resume_plan = resume_plan.clone();
3894        exec_ctx.diag = diag.clone();
3895        exec_ctx.scene_tree_parent_id = 0;
3896        exec_ctx.scene_tree_path = initial_scene_tree_path.clone();
3897        // One Walker: seed at the scenario layer (see the pre-map seed above).
3898        exec_ctx.current_scope_idx = exec_ctx.scope_tree.scenario_root_idx();
3899        // Pre-map pass is done — the real execution starts now.
3900        // dryrun=phase still walks at depth=Phase but with this
3901        // flag false, so the sentinel set_phase_completed in the
3902        // walker fires as the dryrun=phase summary needs.
3903        exec_ctx.pre_map_only = false;
3904
3905        let scheduler = crate::scheduler::build(&schedule_spec);
3906        let scheduler_result = scheduler.run(&mut exec_ctx, &scenario_nodes).await;
3907
3908        // SRD-35: drain the resource pool at session end.
3909        // `Shared`/`PerScenario` entries intentionally stay alive
3910        // across phases (the whole reason the pool exists), so
3911        // this is the close trigger that releases their network
3912        // resources. Runs even if the scenario errored out —
3913        // half-open clusters would otherwise leak FDs into the
3914        // next session in TUI / `metrics watch` host processes.
3915        exec_ctx.resource_pool.shutdown().await;
3916        // SRD-93 stage 6 — a ladder-driven interrupt (level 1/2)
3917        // unwinds the walk as an `Err`, which the `?` below would
3918        // propagate PAST the SRD-77 row close-out at the end of this
3919        // function — leaving `disposition` NULL, the marker reserved
3920        // for genuinely unclean exits (force-exit, panic, SIGKILL). A
3921        // cooperative drain IS a clean shutdown: stamp the row with
3922        // the scene tree's computed disposition (interrupted / failed
3923        // / …) before the error propagates. `update_execution_end`
3924        // keys on `ended_at_nanos IS NULL`, so the normal-completion
3925        // stamp below stays a no-op after this one.
3926        if scheduler_result.is_err() {
3927            close_execution_row(&sqlite_reporter, &session_id, exec_id);
3928        }
3929        scheduler_result?;
3930
3931        // Workload-end lifecycle boundary: every phase in the
3932        // scenario has completed. Individual phase paths already
3933        // closed themselves at phase-end, but any workload-level
3934        // ingests (e.g. aggregate metrics the tree code emits at
3935        // scope scope rather than phase scope) still need a flush.
3936        // In phased mode the workload's label set is the session
3937        // root — there's no intermediate `activity=...` label —
3938        // so we close at the session root.
3939        cadence_reporter.close_path(&Labels::of("session", &session.id));
3940
3941        // SRD-13d Phase 7 — `dryrun=dispenser` scope-elision
3942        // summary. Phase walk has just completed; scope tree
3943        // carries final `materialised` / `logical_name` marks
3944        // (set by the workload-load classifier). Dump now so the
3945        // diagnostic surfaces phase-init artifacts (registered
3946        // metrics, adapter map_op calls) in the same run. Used
3947        // to fire for `Op` depth; since the auto-bump now lifts
3948        // `dryrun=op` to `Cycle` (full cycle execution with
3949        // wrapper short-circuit), the scope-elision surface
3950        // moved to `dryrun=dispenser` — the explicit "build
3951        // every dispenser but don't run cycles" mode.
3952        if diag.depth == ExecDepth::Dispenser {
3953            let mut out = std::io::stdout();
3954            if let Err(e) = render_scope_elision_summary(&scope_tree, &mut out) {
3955                crate::diag!(
3956                    crate::observer::LogLevel::Warn,
3957                    "warning: rendering scope-elision summary: {e}"
3958                );
3959            }
3960        }
3961
3962        // The run reached its end boundary: every fallible step is
3963        // behind us (the epilogue after this block is teardown
3964        // only). Tell the checkpoint writer HERE, as the block's
3965        // last statement — `_eor_notice_guard` drops when this
3966        // block closes, and its resume_hint must read
3967        // declared-but-never-started phases as excluded-by-
3968        // predicate rather than left-behind (SRD-44a; see
3969        // resume_hint). Error `?` returns above skip this, so a
3970        // cut-short run still advises resuming pending phases.
3971        checkpoint_writer.mark_run_reached_end();
3972    }
3973
3974    // Session-end lifecycle boundary. Close the session root path
3975    // for any aggregate windows that were ingested at session level
3976    // (rare today, but the boundary must be explicit — otherwise
3977    // session-level aggregates would only flush during
3978    // `shutdown_flush` at the very end, after all the per-subscriber
3979    // teardown logic had already started).
3980    cadence_reporter.close_path(&Labels::of("session", &session.id));
3981
3982    // SRD-88 — flush THIS execution's windows into the store so the
3983    // summaries below see complete data, without tearing down the
3984    // session-shared cadence reporter.
3985    cadence_reporter
3986        .quiesce(std::time::Duration::from_secs(30))
3987        .await;
3988
3989    // SRD-63 Push 9a: fire `EventType::SessionEnd` once after
3990    // the cadence shutdown but before `run_finished()`.
3991    // Both branches (phased + single-activity) converge
3992    // here, so a single fire covers every run shape.
3993    {
3994        let session_ctx = crate::readout_context::LifecycleContext {
3995            event: crate::lifecycle::EventType::SessionEnd,
3996            subject_name: session.id.clone(),
3997            subject_labels: String::new(),
3998            depth_indent: String::new(),
3999            use_color: crate::observer::use_color(),
4000            stick_reattached: String::new(),
4001        };
4002        crate::readout_context::fire_lifecycle(
4003            crate::lifecycle::EventType::SessionEnd,
4004            &workload_readouts,
4005            None,
4006            &session_ctx,
4007            Some(&sqlite_reporter),
4008        );
4009    }
4010
4011    observer.run_finished();
4012
4013    if dry_run.is_some() {
4014        crate::diag!(crate::observer::LogLevel::Info, "dry-run complete.");
4015    } else {
4016        crate::diag!(crate::observer::LogLevel::Info, "done.");
4017    }
4018
4019    // Build the active set of named summaries.
4020    //
4021    // Precedence:
4022    //   - CLI `summary=<spec>` wins outright — produces a single
4023    //     ad-hoc summary under the synthetic name `default`,
4024    //     overriding any workload-declared map. Matches prior
4025    //     CLI behavior.
4026    //   - Otherwise the workload's `summary:` map (and the
4027    //     `summary.yaml` sidecar fallback already merged into
4028    //     `workload_summaries` above) is used as-is.
4029    //
4030    // An empty map means "no summary at end of run" — same as
4031    // the legacy "no `summary:` field" case.
4032    let active_summaries: HashMap<String, nmbrs_workload::model::SummaryConfig> =
4033        if let Some(cli_summary) = merged_params.get("summary") {
4034            let mut m = HashMap::new();
4035            m.insert(
4036                "default".into(),
4037                nmbrs_workload::model::SummaryConfig::parse(cli_summary),
4038            );
4039            m
4040        } else {
4041            workload_summaries.clone()
4042        };
4043
4044    // SRD-46 output routing for the in-run summary, by item name.
4045    //
4046    // A CLI `summary=<spec>` is an explicit operator request —
4047    // they typed it, so it still echoes to the terminal. A
4048    // workload-declared table goes where its `to:` says, and one
4049    // that declared nothing goes to the session directory ONLY.
4050    // stdout is never implied for automatic rendering: a run's
4051    // stdout is its op output, and a summary carries wall-clock
4052    // values that would make that output differ run to run.
4053    let summary_destinations: HashMap<String, Vec<nmbrs_workload::report::Destination>> = {
4054        use nmbrs_workload::report::Destination as D;
4055        if merged_params.contains_key("summary") {
4056            let mut m = HashMap::new();
4057            m.insert("default".to_string(), vec![D::SessionDir, D::Stdout]);
4058            m
4059        } else {
4060            workload_report
4061                .items()
4062                .filter(|i| matches!(i.kind, nmbrs_workload::report::Kind::Table))
4063                .map(|i| {
4064                    (
4065                        i.name.clone(),
4066                        i.style
4067                            .destinations
4068                            .clone()
4069                            .unwrap_or_else(|| vec![D::SessionDir]),
4070                    )
4071                })
4072                .collect()
4073        }
4074    };
4075
4076    // SRD-46 Details auto-injection: persist run-wide context
4077    // (end time, phase + scenario counts, adapter, …) into
4078    // session_metadata regardless of whether the workload
4079    // declared a `report:` block. Post-run hooks read this to
4080    // build the auto-injected Details section that lands at
4081    // the top of every output markdown file.
4082    if let Ok(mut guard) = sqlite_reporter.lock()
4083        && let Some(ref mut reporter) = *guard
4084    {
4085        let end_time = std::time::SystemTime::now()
4086            .duration_since(std::time::UNIX_EPOCH)
4087            .map(|d| d.as_secs())
4088            .unwrap_or(0);
4089        let sid = session.id.clone();
4090        let exec_id = execution.exec_id;
4091        reporter.set_execution_metadata(&sid, exec_id, "end_time", &end_time.to_string());
4092        reporter.set_execution_metadata(&sid, exec_id, "phase_count", &phases.len().to_string());
4093        reporter.set_execution_metadata(
4094            &sid,
4095            exec_id,
4096            "scenario_count",
4097            &scenarios.len().to_string(),
4098        );
4099        if let Some(wf) = workload_file.as_deref() {
4100            reporter.set_execution_metadata(&sid, exec_id, "workload_file", wf);
4101        }
4102        reporter.set_execution_metadata(&sid, exec_id, "adapter", &driver);
4103    }
4104
4105    if !active_summaries.is_empty() {
4106        // Summary report always comes from SQLite — the
4107        // durable record. The in-memory store exists for GK
4108        // access and reactive control, not for reporting.
4109        if let Ok(mut guard) = sqlite_reporter.lock()
4110            && let Some(ref mut reporter) = *guard
4111        {
4112            // Persist every report item (SRD-46) under
4113            // `report.<name>` keys. Value carries the kind
4114            // keyword (`plot ...` / `table ...`) followed
4115            // by an optional `label "..."` line and then
4116            // the spec body — same shape the report parser
4117            // ingests, so the db-fallback path in
4118            // `nmbrs report` round-trips through the same
4119            // parser the workload uses.
4120            let sid = session.id.clone();
4121            let exec_id = execution.exec_id;
4122            for item in workload_report.items() {
4123                // Single emission point: the workload-side
4124                // serializer. The db-fallback path in
4125                // `nmbrs report` parses this value back
4126                // through `parse_persisted_item`, which
4127                // uses the same grammar — round-trip safe.
4128                let value = item.to_yaml_directive_string();
4129                reporter.set_execution_metadata(
4130                    &sid,
4131                    exec_id,
4132                    &format!("report.{}", item.name),
4133                    &value,
4134                );
4135            }
4136
4137            // Stable ordering for consistent output across
4138            // runs (HashMap iteration is non-deterministic).
4139            let mut names: Vec<&String> = active_summaries.keys().collect();
4140            names.sort();
4141            for name in names {
4142                let cfg = &active_summaries[name];
4143                let (basename, format) =
4144                    nmbrs_metrics::reporters::sqlite::derive_name_and_format(name);
4145                // SRD-77 — the in-run summary is naturally
4146                // scoped to the current execution; qualifier
4147                // narrows to this run's exec_id so a refine
4148                // doesn't render rows from prior runs.
4149                let report_config = report_config_from_summary(cfg, Some(exec_id));
4150                let rendered = reporter.format_summary_with_format(&report_config, &format);
4151                if rendered.is_empty() {
4152                    continue;
4153                }
4154                // SRD-46 routing for this item. Undeclared ⇒
4155                // session directory only.
4156                let dests = summary_destinations
4157                    .get(name.as_str())
4158                    .cloned()
4159                    .unwrap_or_else(|| vec![nmbrs_workload::report::Destination::SessionDir]);
4160                let to_session = dests.contains(&nmbrs_workload::report::Destination::SessionDir);
4161                let to_stdout = dests.contains(&nmbrs_workload::report::Destination::Stdout);
4162                let to_stderr = dests.contains(&nmbrs_workload::report::Destination::Stderr);
4163
4164                let filename = format!("{basename}_summary.{format}");
4165                let summary_path = session.output_dir.join(&filename);
4166                if to_session {
4167                    if let Err(e) = std::fs::write(&summary_path, &rendered) {
4168                        crate::diag!(
4169                            crate::observer::LogLevel::Warn,
4170                            "warning: failed to write summary to {}: {e}",
4171                            summary_path.display()
4172                        );
4173                    } else {
4174                        crate::diag!(
4175                            crate::observer::LogLevel::Info,
4176                            "summary: {}",
4177                            summary_path.display()
4178                        );
4179                    }
4180                }
4181                // Inline print only when the observer is
4182                // not suppressing stderr — i.e. we're in
4183                // tui=off mode and the user can see stdout
4184                // right now. In TUI mode the alternate
4185                // screen is up, so `print!()` here would
4186                // get buffered behind the TUI rendering and
4187                // discarded on teardown. The persona reads
4188                // the *_summary.* files and prints them
4189                // post-shutdown (see `crates/nmbrs/src/run.rs`).
4190                if to_stderr {
4191                    eprint!("{rendered}");
4192                }
4193                if to_stdout {
4194                    // In TUI mode the alternate screen is up, so an
4195                    // inline `print!` would be buffered behind the
4196                    // TUI rendering and discarded on teardown.
4197                    // Defer it to a file the post-run printer
4198                    // flushes once the terminal is back in cooked
4199                    // mode. Routing is decided HERE either way —
4200                    // the post-run printer no longer infers "goes
4201                    // to stdout" from the presence of an artifact.
4202                    if observer.suppresses_stderr() {
4203                        let deferred = session.output_dir.join(DEFERRED_STDOUT_FILE);
4204                        if let Err(e) = std::fs::OpenOptions::new()
4205                            .create(true)
4206                            .append(true)
4207                            .open(&deferred)
4208                            .and_then(|mut f| {
4209                                std::io::Write::write_all(&mut f, rendered.as_bytes())
4210                            })
4211                        {
4212                            crate::diag!(
4213                                crate::observer::LogLevel::Warn,
4214                                "warning: failed to defer summary stdout to {}: {e}",
4215                                deferred.display()
4216                            );
4217                        }
4218                    } else {
4219                        print!("{rendered}");
4220                    }
4221                }
4222            }
4223        }
4224    }
4225
4226    // Refresh convenience symlinks at the logs/ root so
4227    //   logs/metrics.db, logs/summary.md, logs/session.log
4228    // always resolve to this session's artifacts. `logs/latest` (a
4229    // symlink to the whole session dir) is created by Session::new;
4230    // these are per-file counterparts for direct tool access like
4231    // `sqlite3 logs/metrics.db` or `tail -f logs/session.log`.
4232    refresh_latest_file_links(session);
4233
4234    // dryrun=controls: every phase has now been constructed (at
4235    // depth=Phase the executor stops before cycles but still
4236    // attaches components and declares controls). Walk the
4237    // session tree and dump the catalog.
4238    if diag.list_controls {
4239        let mut out = std::io::stdout();
4240        if let Err(e) = render_controls_tree(&session.component, &mut out) {
4241            crate::diag!(
4242                crate::observer::LogLevel::Warn,
4243                "warning: rendering controls: {e}"
4244            );
4245        }
4246    }
4247
4248    // SRD-77 / SRD-93 stage 6 — close out the executions row with
4249    // the computed disposition + end timestamp. Both clean-exit
4250    // paths stamp it: normal completion here, and a ladder-driven
4251    // interrupt at the walk-error site above (which then propagates
4252    // out before reaching this line). Only genuinely unclean exits
4253    // (force-exit, panic, SIGKILL) leave `ended_at_nanos` NULL,
4254    // which the read side surfaces as "execution in flight /
4255    // unclean exit" distinct from a recorded outcome.
4256    close_execution_row(&sqlite_reporter, &session_id, exec_id);
4257
4258    // WAL consolidation runs from the RAII shutdown guard
4259    // bound at the top of this function (`_sqlite_shutdown_guard`).
4260    // The guard's Drop fires reliably across normal return,
4261    // `?` error propagation, and first-Ctrl-C cooperative
4262    // shutdown — every path Rust unwinds through. Second
4263    // Ctrl-C → `process::exit` is the only skip path,
4264    // matching the documented force-exit semantic in
4265    // `session_signals`.
4266
4267    Ok(())
4268}
4269
4270/// SRD-77 / SRD-93 stage 6 — close the in-flight executions row with
4271/// the scene tree's session disposition + an end timestamp. Idempotent
4272/// (`update_execution_end` keys on `ended_at_nanos IS NULL`), so the
4273/// interrupt-path caller and the normal-completion caller compose:
4274/// whichever runs first wins, the other is a no-op.
4275fn close_execution_row(
4276    sqlite_reporter: &std::sync::Arc<
4277        std::sync::Mutex<Option<nmbrs_metrics::reporters::sqlite::SqliteReporter>>,
4278    >,
4279    session_id: &str,
4280    exec_id: u64,
4281) {
4282    let disposition =
4283        crate::scene_tree::with_global(|t| t.session_disposition().label()).unwrap_or("UNKNOWN");
4284    let ended_at_nanos = std::time::SystemTime::now()
4285        .duration_since(std::time::UNIX_EPOCH)
4286        .map(|d| d.as_nanos() as i64)
4287        .unwrap_or(0);
4288    if let Ok(mut g) = sqlite_reporter.lock()
4289        && let Some(r) = g.as_mut()
4290    {
4291        r.update_execution_end(session_id, exec_id, ended_at_nanos, disposition);
4292    }
4293}
4294
4295/// Core runner: set up the shared session host, run one execution, tear down.
4296/// Diagnostic mode is controlled by the `dryrun=` param.
4297async fn run_impl(
4298    args: &[String],
4299    observer: Arc<dyn crate::observer::RunObserver>,
4300) -> Result<(), String> {
4301    let host = SessionHost::setup(args, observer.clone())?;
4302    let result = run_execution(&host, args, observer).await;
4303    host.shutdown().await;
4304    result
4305}
4306
4307/// SRD-88 — one execution's spec for [`run_executions`]: the workload
4308/// CLI args, the observer that captures its lifecycle/log, and an optional
4309/// per-execution output channel (SRD-87 buckets). `channel = None` falls back
4310/// to the process-global channel; in-process example verification passes a
4311/// `CaptureChannel` so each execution's op stdout is captured separately.
4312pub struct ExecutionSpec {
4313    pub args: Vec<String>,
4314    pub observer: Arc<dyn crate::observer::RunObserver>,
4315    pub channel: Option<Arc<dyn crate::output_channel::OutputChannel>>,
4316}
4317
4318/// SRD-88 — run N executions CONCURRENTLY in one process, all sharing
4319/// ONE session, at most `max_concurrent` in flight. The session
4320/// (`SessionHost`: dir / stores / cadence + scheduler services) is set
4321/// up ONCE and torn down ONCE, after every execution. Each execution
4322/// loads + runs its own workload, derives its own `Execution`
4323/// (distinct allocated `exec_id`) under the shared session component,
4324/// flushes its metrics into the shared store via
4325/// [`CadenceReporter::quiesce`](nmbrs_metrics::cadence_reporter::CadenceReporter::quiesce)
4326/// without tearing the reporter down, and routes its lifecycle/log
4327/// through its own observer (a scoped
4328/// [`ExecutionContext`](crate::execution_context::ExecutionContext)). Results
4329/// come back in input order.
4330///
4331/// `max_concurrent == 1` is the sequential case — the SAME harness, no
4332/// separate path (SRD-02 "One Concurrency Path").
4333pub async fn run_executions(
4334    session_args: &[String],
4335    session_observer: Arc<dyn crate::observer::RunObserver>,
4336    specs: Vec<ExecutionSpec>,
4337    max_concurrent: usize,
4338) -> Result<Vec<Result<(), String>>, String> {
4339    let host = std::sync::Arc::new(SessionHost::setup(session_args, session_observer)?);
4340    let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(max_concurrent.max(1)));
4341    let futs = specs.into_iter().map(|spec| {
4342        let host = host.clone();
4343        let sem = sem.clone();
4344        async move {
4345            // Bound in-flight executions; permit held for the whole run.
4346            let _permit = sem.acquire().await.expect("semaphore not closed");
4347            // Scope this execution's context — a distinct allocated
4348            // `exec_id` + its own observer (+ optional output channel) — so
4349            // deeply-nested fibers, op-output routing, and `run_execution`'s
4350            // exec-identity all resolve to THIS execution.
4351            let ctx = match spec.channel.clone() {
4352                Some(ch) => crate::execution_context::ExecutionContext::with_observer_and_channel(
4353                    spec.observer.clone(),
4354                    ch,
4355                ),
4356                None => {
4357                    crate::execution_context::ExecutionContext::with_observer(spec.observer.clone())
4358                }
4359            };
4360            crate::execution_context::scope(ctx, run_execution(&host, &spec.args, spec.observer))
4361                .await
4362        }
4363    });
4364    let results = futures::future::join_all(futs).await;
4365    // Session teardown — once, after every execution completed (so the
4366    // host is now the sole owner).
4367    match std::sync::Arc::try_unwrap(host) {
4368        Ok(h) => h.shutdown().await,
4369        Err(_) => crate::diag!(
4370            crate::observer::LogLevel::Warn,
4371            "run_executions: session host still referenced at teardown; \
4372             scheduler/WAL will close on drop"
4373        ),
4374    }
4375    Ok(results)
4376}
4377
4378/// Point per-file symlinks under `logs/` at the latest session's
4379/// artifacts. Silently skips files that don't exist (e.g. summary.md
4380/// when no `summary:` was declared). Replaces any existing symlink.
4381///
4382/// Targets route through `logs/latest` (which `Session::new` points
4383/// at the actual session dir) so the convenience links stay
4384/// consistent with `latest`. Skipped entirely when the session
4385/// lives outside `logs/` — `--session-path /tmp/x` is an explicit
4386/// redirect and shouldn't hijack the user's `logs/` symlinks.
4387fn refresh_latest_file_links(session: &crate::session::Session) {
4388    let logs_dir = std::path::Path::new("logs");
4389    // Mirror the gate in `Session::new` — keep these convenience
4390    // links and `logs/latest` synchronized: either both update or
4391    // neither does.
4392    if !crate::session::target_is_under(logs_dir, &session.output_dir) {
4393        return;
4394    }
4395    for file in ["metrics.db", "summary.md", "session.log"] {
4396        let target = session.output_dir.join(file);
4397        if !target.exists() {
4398            continue;
4399        }
4400        let link = logs_dir.join(file);
4401        // Remove any existing entry (symlink or regular file) so we can
4402        // recreate the link. If this fails because nothing's there,
4403        // that's fine.
4404        let _ = std::fs::remove_file(&link);
4405        let rel_target = std::path::Path::new("latest").join(file);
4406        if let Err(e) = crate::session::symlink_any(&rel_target, &link) {
4407            crate::diag!(
4408                crate::observer::LogLevel::Warn,
4409                "warning: failed to link {} → {}: {e}",
4410                link.display(),
4411                rel_target.display()
4412            );
4413        }
4414    }
4415}
4416
4417/// Create an adapter from inventory registrations.
4418///
4419/// `dryrun=cycle` does NOT substitute the adapter here — it means
4420/// "construct a fully-executable cycle path, then suppress only
4421/// the outbound `execute()` at cycle time." The real adapter is
4422/// always created (connecting, preparing statements, gathering
4423/// metadata); the outermost `DryRunWrapper` handles the runtime
4424/// short-circuit. See `nmbrs_runtime::wrappers::DryRunWrapper`.
4425pub async fn create_adapter(
4426    driver: &str,
4427    params: &HashMap<String, String>,
4428) -> Result<Arc<dyn crate::adapter::DriverAdapter>, String> {
4429    let reg = find_adapter_registration(driver)
4430        .ok_or_else(|| crate::adapter::unknown_adapter_error(driver))?;
4431    (reg.create)(params.clone()).await
4432}
4433
4434/// Run an activity without its own capture thread.
4435///
4436/// All metrics flow through the session-level scheduler →
4437/// `CadenceReporter` → `MetricsQuery`. This function just runs the
4438/// activity to completion; lifecycle flush (final delta +
4439/// validation metrics) is handled by the caller (executor).
4440/// Streaming print: one header line for the `dryrun=kernels`
4441/// dump, fired before any kernel installs.
4442fn print_kernel_dump_header() {
4443    let is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
4444    let (bold, reset) = if is_tty {
4445        ("\x1b[1m", "\x1b[0m")
4446    } else {
4447        ("", "")
4448    };
4449    println!();
4450    println!("{bold}Polydat Scope Kernels{reset}");
4451    println!("{bold}═════════════════════{reset}");
4452    println!();
4453}
4454
4455/// Streaming per-scope visitor callback. Prints the scope's
4456/// logical name + the polydat source the kernel was compiled
4457/// from, indented by the scope's depth.
4458fn print_kernel_for_scope(
4459    node: &crate::scope_tree::ScopeNode,
4460    kernel: &crate::scope_kernel::ScopeKernel,
4461) {
4462    let is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
4463    let (bold, dim, reset, cyan, magenta, green) = if is_tty {
4464        (
4465            "\x1b[1m", "\x1b[2m", "\x1b[0m", "\x1b[36m", "\x1b[35m", "\x1b[32m",
4466        )
4467    } else {
4468        ("", "", "", "", "", "")
4469    };
4470
4471    let logical = if node.logical_name.is_empty() {
4472        "<unnamed scope>".to_string()
4473    } else {
4474        node.logical_name.clone()
4475    };
4476    let depth_indent = " ".repeat(node.depth);
4477    println!(
4478        "{depth_indent}{green}●{reset} {bold}{cyan}{logical}{reset} \
4479              {dim}(depth={}, kind={:?}){reset}",
4480        node.depth, node.kind
4481    );
4482    let source = kernel.program().source().trim_end();
4483    if source.is_empty() {
4484        println!("{depth_indent}  {dim}(empty kernel — no own bindings){reset}");
4485    } else {
4486        for line in source.lines() {
4487            println!("{depth_indent}  {magenta}│{reset} {line}");
4488        }
4489    }
4490    println!();
4491}
4492
4493/// Footer for the `dryrun=kernels` dump (legend + spacing).
4494fn print_kernel_dump_legend() {
4495    let is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
4496    let (dim, reset, green) = if is_tty {
4497        ("\x1b[2m", "\x1b[0m", "\x1b[32m")
4498    } else {
4499        ("", "", "")
4500    };
4501    println!(
4502        "  {dim}Legend: {green}●{reset}{dim} kernel installed at this scope. \
4503              Flattened scopes (those that inherit a parent's kernel) emit no entry.{reset}"
4504    );
4505    println!();
4506}
4507
4508pub async fn run_activity_simple(
4509    activity: Activity,
4510    adapters: std::collections::HashMap<String, Arc<dyn crate::adapter::DriverAdapter>>,
4511    default_adapter: &str,
4512    op_builder: Arc<crate::synthesis::OpBuilder>,
4513) -> bool {
4514    activity
4515        .run_with_adapters(adapters, default_adapter, op_builder)
4516        .await
4517}
4518
4519/// Adapter that delegates to an `Arc<Mutex<Option<SqliteReporter>>>`.
4520///
4521/// Allows the SQLite reporter to be registered on the scheduler while
4522/// also being accessible for summary queries after the scheduler stops.
4523struct MutexReporter(
4524    std::sync::Arc<std::sync::Mutex<Option<nmbrs_metrics::reporters::sqlite::SqliteReporter>>>,
4525);
4526
4527impl Reporter for MutexReporter {
4528    fn report(&mut self, snapshot: &nmbrs_metrics::snapshot::MetricSet) {
4529        if let Ok(mut guard) = self.0.lock()
4530            && let Some(ref mut r) = *guard
4531        {
4532            Reporter::report(r, snapshot);
4533        }
4534    }
4535
4536    fn flush(&mut self) {
4537        if let Ok(mut guard) = self.0.lock()
4538            && let Some(ref mut r) = *guard
4539        {
4540            Reporter::flush(r);
4541        }
4542    }
4543}
4544
4545/// Wrapper to make `Box<dyn Reporter>` usable with `add_reporter(impl Reporter)`.
4546struct BoxedReporter(Box<dyn Reporter>);
4547impl Reporter for BoxedReporter {
4548    fn report(&mut self, snapshot: &nmbrs_metrics::snapshot::MetricSet) {
4549        self.0.report(snapshot);
4550    }
4551    fn flush(&mut self) {
4552        self.0.flush();
4553    }
4554}
4555
4556// =========================================================================
4557// Helpers
4558// =========================================================================
4559
4560/// Expand `{key}` workload param placeholders in a string.
4561pub fn expand_workload_params(s: &str, params: &HashMap<String, String>) -> String {
4562    let mut result = s.to_string();
4563    for (key, value) in params {
4564        let placeholder = format!("{{{key}}}");
4565        if result.contains(&placeholder) {
4566            result = result.replace(&placeholder, value);
4567        }
4568    }
4569    result
4570}
4571
4572/// Collected param references from a workload, separating direct
4573/// `{name}` references from composite-name templates like
4574/// `{k_{k}_limits}` whose ground form depends on a runtime
4575/// substitution.
4576///
4577/// Used by the workload param validator to recognize that a
4578/// declared param like `k_1_limits` is genuinely referenced
4579/// when the workload uses `{k_{k}_limits}` and `k` ranges over
4580/// values including `1`.
4581#[derive(Default)]
4582struct ParamRefs {
4583    /// Names that appeared as `{name}` curly-brace placeholders.
4584    /// These MUST resolve to a declared param, runner-known
4585    /// param, adapter-registered param, or scenario-tree
4586    /// iter-var — anything else is a typo or missing
4587    /// declaration and the validator surfaces it as an error.
4588    placeholders: std::collections::HashSet<String>,
4589    /// Placeholders that appeared in scenario-tree `for_each` /
4590    /// `for_combinations` / DoWhile-condition text. These get
4591    /// resolved at runtime by the comprehension interpolator
4592    /// (which emits a `<path>:<line>:<col>:` error on failure);
4593    /// the strict "must-resolve-now" validator skips them so the
4594    /// more-specific runtime diagnostic wins. They still count
4595    /// as references for the "declared but unreferenced" check
4596    /// — a workload param used only in a `for_each` spec is
4597    /// genuinely consumed by the workload, just at runtime.
4598    runtime_only_placeholders: std::collections::HashSet<String>,
4599    /// Bare identifiers harvested from `if:` / `delay:`
4600    /// expression bodies. These may be wire names (referencing
4601    /// values bound via Polydat source) rather than workload params,
4602    /// so they participate in the "declared but unreferenced"
4603    /// check (as references) but NOT in the "referenced but
4604    /// undeclared" check (since wire names legitimately live
4605    /// outside the workload's param surface).
4606    expression_idents: std::collections::HashSet<String>,
4607    /// Composite templates: the literal body of a `{...}` whose
4608    /// inner content contained nested `{...}`. Stored verbatim
4609    /// (e.g. `"k_{k}_limits"`); validation checks each declared
4610    /// param name against these templates by replacing each
4611    /// inner `{NAME}` with a word-character wildcard.
4612    templates: Vec<String>,
4613}
4614
4615impl ParamRefs {
4616    /// Does `param` appear as a reference anywhere — placeholder,
4617    /// runtime-only placeholder, expression ident, or composite
4618    /// template? Used by the existing "declared but unreferenced"
4619    /// validator.
4620    fn contains(&self, param: &str) -> bool {
4621        if self.placeholders.contains(param) {
4622            return true;
4623        }
4624        if self.runtime_only_placeholders.contains(param) {
4625            return true;
4626        }
4627        if self.expression_idents.contains(param) {
4628            return true;
4629        }
4630        self.templates
4631            .iter()
4632            .any(|tpl| template_matches(tpl, param))
4633    }
4634}
4635
4636/// Match a declared param name against a composite-name template.
4637///
4638/// `template` is the body of a `{...}` reference whose content
4639/// included nested `{...}` substitutions — e.g. `k_{k}_limits`.
4640/// Each inner `{NAME}` matches one or more word characters
4641/// (`[A-Za-z0-9_]+`); the surrounding literal chars must match
4642/// exactly. Returns `true` iff `param` exactly matches the
4643/// template's ground form for some substitution of the inner
4644/// names.
4645fn template_matches(template: &str, param: &str) -> bool {
4646    let t = template.as_bytes();
4647    let p = param.as_bytes();
4648    let mut ti = 0;
4649    let mut pi = 0;
4650    while ti < t.len() {
4651        if t[ti] == b'{' {
4652            // Skip past the inner {...}. The template body
4653            // doesn't nest deeper than one level in practice
4654            // (composed names like `{k_{k}_limits}` don't
4655            // contain `{a_{b}_c}` recursively); a simple
4656            // first-`}` lookup suffices.
4657            let close = match template[ti + 1..].find('}') {
4658                Some(n) => ti + 1 + n,
4659                None => return false, // malformed template
4660            };
4661            // Determine where the template's literal context
4662            // resumes after the inner placeholder.
4663            let next_lit = close + 1;
4664            // The next literal char (or end-of-template) bounds
4665            // how far the wildcard can consume.
4666            if next_lit >= t.len() {
4667                // Wildcard must consume the rest of `param`,
4668                // and that suffix must be at least one word char.
4669                if pi >= p.len() {
4670                    return false;
4671                }
4672                return p[pi..]
4673                    .iter()
4674                    .all(|b| b.is_ascii_alphanumeric() || *b == b'_');
4675            }
4676            let stop = t[next_lit];
4677            // Greedy-match word chars in param up to the next
4678            // literal in template.
4679            let mut consumed = 0;
4680            while pi + consumed < p.len() && p[pi + consumed] != stop {
4681                let b = p[pi + consumed];
4682                if !(b.is_ascii_alphanumeric() || b == b'_') {
4683                    return false;
4684                }
4685                consumed += 1;
4686            }
4687            if consumed == 0 {
4688                return false;
4689            } // wildcard requires ≥1 char
4690            pi += consumed;
4691            ti = next_lit;
4692        } else {
4693            // Literal char: must match.
4694            if pi >= p.len() || p[pi] != t[ti] {
4695                return false;
4696            }
4697            ti += 1;
4698            pi += 1;
4699        }
4700    }
4701    pi == p.len()
4702}
4703
4704/// Scan a string for `{name}` references and `{composite_{x}_name}`
4705/// templates, accumulating into `refs`.
4706///
4707/// Plain `{name}` placeholders (where the body is a single
4708/// identifier — alphanumerics + underscore, leading non-digit)
4709/// are recorded as direct references. A `{...}` whose body
4710/// contains nested `{...}` is recorded as a template; the inner
4711/// leaf names are also recorded as direct references because
4712/// they're the substitution inputs (e.g. `{k_{k}_limits}`
4713/// records the template `k_{k}_limits` AND the direct ref `k`).
4714/// Walk a `serde_json::Value` and call [`scan_param_refs`] on
4715/// every string leaf. Used by [`collect_param_references`] to
4716/// reach `{name}` references nested inside structured
4717/// `params:` blocks (e.g. `relevancy: { expected: "{ground_truth}" }`).
4718fn scan_json_for_refs(v: &serde_json::Value, refs: &mut ParamRefs) {
4719    match v {
4720        serde_json::Value::String(s) => scan_param_refs(s, refs),
4721        serde_json::Value::Array(a) => {
4722            for item in a {
4723                scan_json_for_refs(item, refs);
4724            }
4725        }
4726        serde_json::Value::Object(m) => {
4727            for item in m.values() {
4728                scan_json_for_refs(item, refs);
4729            }
4730        }
4731        _ => {} // numbers, booleans, null — no string content
4732    }
4733}
4734
4735fn scan_param_refs(text: &str, refs: &mut ParamRefs) {
4736    let bytes = text.as_bytes();
4737    let mut i = 0;
4738    // `\{` and `\}` are literal braces (`nmbrs_workload::op_text`).
4739    let escaped =
4740        |at: usize| bytes[at] == b'\\' && matches!(bytes.get(at + 1), Some(b'{') | Some(b'}'));
4741    while i < bytes.len() {
4742        if escaped(i) {
4743            i += 2;
4744            continue;
4745        }
4746        if bytes[i] != b'{' {
4747            i += 1;
4748            continue;
4749        }
4750        // Find the matching `}`, balancing nested `{`s.
4751        let body_start = i + 1;
4752        let mut depth = 1;
4753        let mut j = body_start;
4754        while j < bytes.len() && depth > 0 {
4755            if escaped(j) {
4756                j += 2;
4757                continue;
4758            }
4759            match bytes[j] {
4760                b'{' => depth += 1,
4761                b'}' => depth -= 1,
4762                _ => {}
4763            }
4764            if depth == 0 {
4765                break;
4766            }
4767            j += 1;
4768        }
4769        if depth != 0 {
4770            // Unmatched `{` — bail, treat as literal.
4771            break;
4772        }
4773        let body = &text[body_start..j];
4774        if body.contains('{') {
4775            // Composite template (e.g. `k_{k}_limits`).
4776            refs.templates.push(body.to_string());
4777            // Recurse into the body to pick up the inner leaf
4778            // names as direct references.
4779            scan_param_refs(body, refs);
4780        } else if !body.is_empty()
4781            && body.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
4782            && !body.bytes().next().unwrap().is_ascii_digit()
4783        {
4784            // Plain `{name}` — curly-brace placeholder. MUST
4785            // resolve to a declared / known / iter-var name;
4786            // the new validator surfaces an error if it doesn't.
4787            refs.placeholders.insert(body.to_string());
4788        } else {
4789            // Inline Polydat expression body, e.g.
4790            // `{is_one_of(cassandra_dialect, "vendor")}` or
4791            // `{:=mod(hash(cycle), 100):=}`. Walk the body,
4792            // collect identifier-shaped tokens that aren't
4793            // inside string literals — those are Polydat name
4794            // references which may resolve to workload params.
4795            // Over-collecting (function names, Polydat stdlib
4796            // identifiers) is harmless — the validator's
4797            // membership test below uses the workload's own
4798            // declared params as the universe of interest.
4799            //
4800            // These land in `expression_idents` (not
4801            // `placeholders`) because they may legitimately
4802            // resolve to Polydat wire names rather than workload
4803            // params; the "declared but unreferenced" check
4804            // still consults them via `ParamRefs::contains`,
4805            // but the new "referenced but undeclared" check
4806            // only scrutinises `placeholders`.
4807            scan_expression_idents(body, &mut refs.expression_idents);
4808        }
4809        i = j + 1;
4810    }
4811}
4812
4813/// Walk a GK-expression body (no surrounding `{}`) and add any
4814/// identifier-shaped tokens to `out`. Skips identifiers nested
4815/// inside `"..."` or `'...'` string literals — those are CQL /
4816/// regex / display strings, not name references. Recognises
4817/// backslash escapes inside string literals.
4818///
4819/// This is best-effort: it doesn't honor Polydat lexer subtleties
4820/// (numeric suffixes, raw strings, etc.). For the unused-param
4821/// check in `runner.rs::collect_param_references` the goal is
4822/// "does the param name appear anywhere we'd evaluate it" — a
4823/// loose match is correct because false positives only mean
4824/// "param is considered used when it might not have been",
4825/// which is the safer failure mode.
4826fn scan_expression_idents(body: &str, out: &mut std::collections::HashSet<String>) {
4827    let bytes = body.as_bytes();
4828    let mut i = 0;
4829    while i < bytes.len() {
4830        let b = bytes[i];
4831        // Skip `//` line comments — checked BEFORE the string-literal
4832        // scan below, because an apostrophe in comment prose (`hasn't`,
4833        // `don't`) would otherwise be read as an unterminated string
4834        // delimiter and swallow every identifier to end-of-input,
4835        // falsely flagging a later-referenced param as unused.
4836        if b == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
4837            i += 2;
4838            while i < bytes.len() && bytes[i] != b'\n' {
4839                i += 1;
4840            }
4841            continue;
4842        }
4843        // Skip string literals.
4844        if b == b'"' || b == b'\'' {
4845            let quote = b;
4846            i += 1;
4847            while i < bytes.len() {
4848                if bytes[i] == b'\\' && i + 1 < bytes.len() {
4849                    i += 2;
4850                    continue;
4851                }
4852                if bytes[i] == quote {
4853                    i += 1;
4854                    break;
4855                }
4856                i += 1;
4857            }
4858            continue;
4859        }
4860        // Identifier start: ASCII letter or underscore.
4861        if b.is_ascii_alphabetic() || b == b'_' {
4862            let start = i;
4863            while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
4864                i += 1;
4865            }
4866            let ident = &body[start..i];
4867            // Skip the few literals the Polydat lexer also recognises
4868            // — they're definitely not param names.
4869            if ident != "true" && ident != "false" {
4870                out.insert(ident.to_string());
4871            }
4872            continue;
4873        }
4874        i += 1;
4875    }
4876}
4877
4878/// Collect all `{name}` param references from a workload's ops,
4879/// phases, bindings, and scenario tree. Returns both direct
4880/// refs and composite templates so the validator can recognize
4881/// dynamic-name-composition references like `{k_{k}_limits}`.
4882/// The param a workload reads for the directory its own file is in.
4883pub const WORKLOAD_DIR_PARAM: &str = "workload_dir";
4884
4885fn collect_param_references(workload: &nmbrs_workload::model::Workload) -> ParamRefs {
4886    let mut refs = ParamRefs::default();
4887
4888    // Local helper so every op-bearing scope (top-level + per-
4889    // phase) hits the same set of fields. Critically this
4890    // includes the *core* fields the parser hoists out of the
4891    // op map — `if:` (condition), `delay:`, and the
4892    // serde_json values inside `params:`. Missing any of those
4893    // produced false positives on the unused-param check
4894    // (e.g. `if: '{is_one_of(cassandra_dialect, "vendor")}'`
4895    // landed in `condition` rather than `op.op`, so the
4896    // workload param `cassandra_dialect` looked unreferenced).
4897    fn scan_op(op: &nmbrs_workload::model::ParsedOp, refs: &mut ParamRefs) {
4898        // An op field may be a mapping or a list (the logfile
4899        // adapter's `rules:` and `file:`), and a param read inside one
4900        // is as much a reference as one in a string field.
4901        for value in op.op.values() {
4902            scan_json_for_refs(value, refs);
4903        }
4904        // `if:` and `delay:` accept either `{name}` placeholders
4905        // (caught by `scan_param_refs`) or bare wire names like
4906        // `delay: think_time`. Walk both shapes — the bare-ident
4907        // pass mirrors what `scope.rs` Step 3/6 do for the same
4908        // fields, so a workload param consumed only via a bare
4909        // delay/condition reference doesn't trip the unused-param
4910        // validator.
4911        if let Some(s) = &op.condition {
4912            scan_param_refs(s, refs);
4913            scan_expression_idents(s, &mut refs.expression_idents);
4914        }
4915        if let Some(spec) = &op.delay {
4916            for name in spec.names() {
4917                scan_param_refs(name, refs);
4918                scan_expression_idents(name, &mut refs.expression_idents);
4919            }
4920        }
4921        // `params:` values can be strings, numbers, nested
4922        // maps (e.g. `relevancy: { actual: key, expected: …}`).
4923        // Walk the JSON recursively so anything stringy gets
4924        // scanned regardless of nesting depth.
4925        //
4926        // `gutter:` is exempt: its templates resolve at RUNTIME
4927        // (wires first, then status-metric aggregates like
4928        // `{recall}` / `{latency_p50}` which have no workload
4929        // declaration), and an unresolved name degrades to
4930        // visible literal text in the cell — never a silent
4931        // failure this validator needs to preempt.
4932        for (k, v) in op.params.iter() {
4933            if k == "gutter" {
4934                continue;
4935            }
4936            scan_json_for_refs(v, refs);
4937        }
4938        // Evaluation blocks reference WIRES by bare identifier
4939        // (`relevancy: { k: suite_k, expected: ground_truth }`) —
4940        // the same shapes `scope.rs` resolves at wrap-time
4941        // through the op-template kernel. Harvest them as
4942        // expression idents so a param consumed only as an
4943        // evaluation bound doesn't trip the unused-param check.
4944        // (Before this, such workloads only validated by ACCIDENT:
4945        // any `{{…}}` inline expression elsewhere in the merged
4946        // doc registered a composite template that wildcard-
4947        // matched every declared param.)
4948        let evaluation_wire_refs = [
4949            (
4950                "relevancy",
4951                &["actual", "expected", "k", "r", "admitted"][..],
4952            ),
4953            (crate::admission::PARAM, crate::admission::WIRE_KEYS),
4954        ];
4955        for (block, keys) in evaluation_wire_refs {
4956            if let Some(rel) = op.params.get(block).and_then(|v| v.as_object()) {
4957                for key in keys {
4958                    if let Some(s) = rel.get(*key).and_then(|v| v.as_str()) {
4959                        scan_expression_idents(s, &mut refs.expression_idents);
4960                    }
4961                }
4962            }
4963        }
4964        match &op.bindings {
4965            nmbrs_workload::model::BindingsDef::PolydatSource(s) => {
4966                // Two reference shapes inside Polydat source:
4967                //   - `{name}` placeholders inside string literals
4968                //     (resolved by Polydat string-interpolation against
4969                //     `const` bindings),
4970                //   - bare identifier references in Polydat expressions
4971                //     (e.g. `row := char_buf(..., cols)` — `cols`
4972                //     resolves directly to its `const` binding).
4973                // The unused-param validator must recognise both
4974                // or it falsely flags params that the workload
4975                // legitimately consumes via the bare path.
4976                scan_param_refs(s, refs);
4977                scan_expression_idents(s, &mut refs.expression_idents);
4978            }
4979            nmbrs_workload::model::BindingsDef::Map(m) => {
4980                for v in m.values() {
4981                    scan_param_refs(v, refs);
4982                }
4983            }
4984        }
4985    }
4986
4987    // Scan top-level ops
4988    for op in &workload.ops {
4989        scan_op(op, &mut refs);
4990    }
4991
4992    // SRD-13f Push D: workload-level `bindings:` are no longer
4993    // folded into ops at YAML parse time — they live on
4994    // `workload.bindings` and reach descendants via the GK
4995    // kernel chain. The unused-param validator must scan them
4996    // directly here, otherwise a workload param consumed only
4997    // from workload-level bindings (`row := char_buf(..., cols)`)
4998    // looks unreferenced.
4999    match &workload.bindings {
5000        nmbrs_workload::model::BindingsDef::PolydatSource(s) => {
5001            scan_param_refs(s, &mut refs);
5002            scan_expression_idents(s, &mut refs.expression_idents);
5003        }
5004        nmbrs_workload::model::BindingsDef::Map(m) => {
5005            for v in m.values() {
5006                scan_param_refs(v, &mut refs);
5007            }
5008        }
5009    }
5010
5011    // SRD-83 — workload-level `stop_when:` predicates: `{param}` interpolation
5012    // only (same as phase-level), so a param used only by a workload breaker
5013    // counts as referenced.
5014    for c in &workload.stop_when {
5015        scan_param_refs(&c.when, &mut refs);
5016    }
5017
5018    // Scan phases
5019    for phase in workload.phases.values() {
5020        if let Some(s) = &phase.cycles {
5021            scan_param_refs(s, &mut refs);
5022        }
5023        // SRD-83 (C3) governance `timeout:` and SRD-75 `interval:`
5024        // resolve `{param}` at phase setup — documented reference
5025        // sites the collector must count (before this, workloads
5026        // using them only validated via the accidental composite-
5027        // template wildcard).
5028        if let Some(s) = &phase.timeout {
5029            scan_param_refs(s, &mut refs);
5030        }
5031        if let Some(s) = &phase.interval {
5032            scan_param_refs(s, &mut refs);
5033        }
5034        if let Some(s) = &phase.concurrency {
5035            scan_param_refs(s, &mut refs);
5036        }
5037        if let Some(s) = &phase.for_each {
5038            scan_param_refs(s, &mut refs);
5039        }
5040        // Phase `rate:` and the SRD-75 poll bounds carry `{param}`
5041        // references resolved at the phase gather (the `timeout:`
5042        // discipline) — documented reference sites the collector
5043        // must count. The poll predicate additionally consumes
5044        // bare identifiers (params/wires) like `continue_if`.
5045        if let Some(s) = &phase.rate {
5046            scan_param_refs(s, &mut refs);
5047        }
5048        if let Some(poll) = &phase.poll {
5049            scan_expression_idents(&poll.until, &mut refs.expression_idents);
5050            for s in [&poll.interval_ms, &poll.timeout_ms, &poll.max_error_retries]
5051                .into_iter()
5052                .flatten()
5053            {
5054                scan_param_refs(s, &mut refs);
5055            }
5056        }
5057        // SRD-13f Push D parallel: phase-level `bindings:` also
5058        // sit on their own scope post-Push-D; scan for param
5059        // refs so a phase-binding-only consumer doesn't falsely
5060        // trip the unused-param check.
5061        match &phase.bindings {
5062            nmbrs_workload::model::BindingsDef::PolydatSource(s) => {
5063                scan_param_refs(s, &mut refs);
5064                scan_expression_idents(s, &mut refs.expression_idents);
5065            }
5066            nmbrs_workload::model::BindingsDef::Map(m) => {
5067                for v in m.values() {
5068                    scan_param_refs(v, &mut refs);
5069                }
5070            }
5071        }
5072        // SRD-83 / SRD-101 — breaker predicates can consume a workload param,
5073        // but by DIFFERENT mechanisms, so scan each for the shape it actually
5074        // supports (a param used in the UNsupported shape stays flagged):
5075        //   - `stop_when` substitutes `{param}` before its predicate compiles;
5076        //     its bound scope can't resolve a bare param wire → `{param}` only.
5077        //   - `continue_if` resolves BARE wires through its for_iteration
5078        //     scope-walk (inherited consts/params) → bare idents only.
5079        for c in &phase.stop_when {
5080            scan_param_refs(&c.when, &mut refs);
5081        }
5082        if let Some(ci) = &phase.continue_if {
5083            scan_expression_idents(&ci.when, &mut refs.expression_idents);
5084        }
5085        for op in &phase.ops {
5086            scan_op(op, &mut refs);
5087        }
5088    }
5089
5090    // Scan scenario tree — every node kind contributes its
5091    // `{...}`-bearing fields. DoWhile/DoUntil contribute their
5092    // condition text; ForEach/ForCombinations/ForEachUnion
5093    // contribute their iteration specs.
5094    //
5095    // Scenario-tree `{name}` placeholders are runtime-interpolated
5096    // against the outer iter-var scope (the comprehension's
5097    // enclosing for-each, plus workload params). An unresolved
5098    // placeholder there surfaces a `path:line:col:` runtime error
5099    // through the interpolation pipeline — the early
5100    // workload-level "undeclared placeholder" check would steal
5101    // that diagnostic with a less specific error. So we route
5102    // these refs through a side-channel that contributes to the
5103    // declared-but-unreferenced check (workload params used only
5104    // in for_each text are still counted as referenced) but NOT
5105    // to `refs.placeholders` (which drives the strict
5106    // "must-resolve-now" guard).
5107    fn scan_scenario_nodes(nodes: &[nmbrs_workload::model::ScenarioNode], refs: &mut ParamRefs) {
5108        for node in nodes {
5109            match node {
5110                nmbrs_workload::model::ScenarioNode::Phase(_) => {}
5111                nmbrs_workload::model::ScenarioNode::Comprehension {
5112                    comprehension,
5113                    children,
5114                    ..
5115                } => {
5116                    // Grammar-based source-reference extraction.
5117                    // A comprehension clause `eh in eh_values`
5118                    // carries `eh_values` as a *bare* source
5119                    // reference (a `Generator`/`WorkloadParamList`
5120                    // spec), and `(v) in (concat(foo))` carries
5121                    // `foo` inside a function call. Byte-scanning
5122                    // for `{name}` misses both. `referenced_source_names`
5123                    // parses each spec with the Polydat expression
5124                    // grammar (via `polydat::dsl::refs`) and returns
5125                    // the free names structurally. These resolve at
5126                    // runtime, so they count as references (for the
5127                    // declared-but-unreferenced check) but bypass
5128                    // the strict undeclared-placeholder guard.
5129                    //
5130                    // A dynamic param-list reference like
5131                    // `limit in {k_{k}_limits}` surfaces as the
5132                    // composite name `k_{k}_limits` (the inner
5133                    // `{k}` is an iter-var hole filled at runtime).
5134                    // Route composite names — those still carrying
5135                    // a `{` — into `templates` so the structured
5136                    // `template_matches` name-composition grammar
5137                    // resolves them against `k_10_limits` /
5138                    // `k_100_limits` / …; plain names go to the
5139                    // runtime-placeholder set.
5140                    for name in comprehension.referenced_source_names() {
5141                        if name.contains('{') {
5142                            refs.templates.push(name);
5143                        } else {
5144                            refs.runtime_only_placeholders.insert(name);
5145                        }
5146                    }
5147                    // The names above are the ones a SOURCE reads as a
5148                    // reference. A param is also consumed by a `{name}`
5149                    // inside a quoted literal element
5150                    // (`src in ["{data_dir}/x"]`), inside a composite
5151                    // name within a quoted string, and by the `where:`
5152                    // predicate, none of which a source's free names
5153                    // include. Scan every string the comprehension tree
5154                    // holds (source specs, literal elements, predicates)
5155                    // for placeholders; they resolve at runtime, like the
5156                    // rest of the comprehension. The tree's serialized
5157                    // form reaches all of them, where its canonical text
5158                    // does not exist for every shape.
5159                    let mut deferred = ParamRefs::default();
5160                    if let Ok(tree) = serde_json::to_value(comprehension) {
5161                        scan_json_for_refs(&tree, &mut deferred);
5162                    }
5163                    refs.runtime_only_placeholders.extend(deferred.placeholders);
5164                    refs.templates.extend(deferred.templates);
5165                    scan_scenario_nodes(children, refs);
5166                }
5167                nmbrs_workload::model::ScenarioNode::DoWhile {
5168                    condition,
5169                    children,
5170                    ..
5171                }
5172                | nmbrs_workload::model::ScenarioNode::DoUntil {
5173                    condition,
5174                    children,
5175                    ..
5176                } => {
5177                    scan_param_refs(condition, refs);
5178                    scan_scenario_nodes(children, refs);
5179                }
5180                nmbrs_workload::model::ScenarioNode::IncludedScenario { children, .. } => {
5181                    scan_scenario_nodes(children, refs);
5182                }
5183                nmbrs_workload::model::ScenarioNode::Bindings { source, children } => {
5184                    // Scenario-tree `bindings:` (and the `set:`
5185                    // sugar form) carries Polydat matter text. Scan
5186                    // the body for `{name}` placeholders and
5187                    // bare identifiers and route through
5188                    // `runtime_only_placeholders` so a param
5189                    // referenced only by a bindings body still
5190                    // counts as referenced, without tripping the
5191                    // strict undeclared-placeholder guard (the
5192                    // body is resolved at kernel build time,
5193                    // not at op-template substitution).
5194                    let mut deferred = ParamRefs::default();
5195                    scan_param_refs(source, &mut deferred);
5196                    refs.runtime_only_placeholders.extend(deferred.placeholders);
5197                    refs.expression_idents.extend(deferred.expression_idents);
5198                    refs.templates.extend(deferred.templates);
5199                    scan_scenario_nodes(children, refs);
5200                }
5201            }
5202        }
5203    }
5204    for nodes in workload.scenarios.values() {
5205        scan_scenario_nodes(nodes, &mut refs);
5206    }
5207
5208    refs
5209}
5210
5211/// Collect every iter-var name introduced by a `for_each:` /
5212/// `for_combinations:` clause anywhere in the scenario tree.
5213///
5214/// These names become legitimate `{name}` placeholders inside
5215/// phases reached via that for-clause — the runner binds them
5216/// fresh per iteration through the workload kernel's
5217/// scope-coordinate mechanism. The "referenced but undeclared"
5218/// validator consults this set so it doesn't false-positive on
5219/// `{k}` / `{limit}` / `{profile}` references that are clearly
5220/// satisfied by an enclosing `for_each: "k in …, limit in …,
5221/// profile in …"`.
5222///
5223/// Walks every scenario in the workload (the union — any
5224/// scenario the operator might invoke), so the validator
5225/// remains correct regardless of which `scenario=` argument
5226/// the operator passes on the CLI.
5227fn collect_iter_var_names(
5228    workload: &nmbrs_workload::model::Workload,
5229) -> std::collections::HashSet<String> {
5230    let mut out = std::collections::HashSet::new();
5231    for nodes in workload.scenarios.values() {
5232        for node in nodes {
5233            collect_iter_vars_recursive(node, &mut out);
5234        }
5235    }
5236    // Phase-level `for_each:` declarations also introduce iter-vars
5237    // — `phases.X.for_each: "k in 1, 2, 3"` lets the phase's ops
5238    // reference `{k}`. The scenario walker doesn't traverse phase
5239    // bodies, so harvest from each phase's `for_each` clause too.
5240    for phase in workload.phases.values() {
5241        if let Some(text) = phase.for_each.as_deref()
5242            && let Ok(comp) =
5243                polydat::iteration::comprehension::spec::parse_comprehension_algebra(text)
5244        {
5245            for name in comp.coordinate_names() {
5246                out.insert(name.to_string());
5247            }
5248        }
5249    }
5250    out
5251}
5252
5253fn collect_iter_vars_recursive(
5254    node: &nmbrs_workload::model::ScenarioNode,
5255    out: &mut std::collections::HashSet<String>,
5256) {
5257    use nmbrs_workload::model::ScenarioNode::*;
5258    match node {
5259        Phase(_) => {}
5260        Comprehension {
5261            comprehension,
5262            children,
5263            ..
5264        } => {
5265            for name in comprehension.coordinate_names() {
5266                out.insert(name.to_string());
5267            }
5268            for child in children {
5269                collect_iter_vars_recursive(child, out);
5270            }
5271        }
5272        DoWhile {
5273            children, counter, ..
5274        }
5275        | DoUntil {
5276            children, counter, ..
5277        } => {
5278            // `counter:` introduces a bare iteration index name
5279            // that's legitimately referenceable inside the loop
5280            // body, even though there's no `for_each` clause.
5281            if let Some(c) = counter {
5282                out.insert(c.clone());
5283            }
5284            for child in children {
5285                collect_iter_vars_recursive(child, out);
5286            }
5287        }
5288        IncludedScenario { children, .. } => {
5289            for child in children {
5290                collect_iter_vars_recursive(child, out);
5291            }
5292        }
5293        // Scenario-tree `bindings:` (and `set:` sugar) doesn't
5294        // introduce an iter-var; it publishes a scope-local
5295        // binding layer. Just walk children.
5296        Bindings { children, .. } => {
5297            for child in children {
5298                collect_iter_vars_recursive(child, out);
5299            }
5300        }
5301    }
5302}
5303
5304/// Collect every binding LHS name (wire output) declared in GK
5305/// source anywhere in the workload — top-level `bindings:`,
5306/// per-phase `bindings:`, and per-op `bindings:`.
5307///
5308/// These names become legitimate `{name}` placeholders inside
5309/// op text (op-template `prepared:` / `raw:` strings get
5310/// `{wire}` interpolated to the wire's value at cycle time, just
5311/// like workload params get expanded earlier in the pipeline).
5312/// The "referenced but undeclared" validator consults this set so
5313/// it doesn't false-positive on `{query_vector}` / `{dim}` /
5314/// `{ground_truth}` references that are clearly satisfied by an
5315/// enclosing `bindings:` block.
5316///
5317/// Scanner is line-based and recognises six shapes:
5318///   * `input NAME[: TYPE]` — kernel input slot (bare form)
5319///   * `input (NAME[: TYPE], ...)` — kernel input slot (tuple form)
5320///   * `const NAME := …`     — init binding (eager, once per scope)
5321///   * `cursor NAME = …`   — cursor declaration
5322///   * `shared NAME := …`  — shared output (cross-scope cell)
5323///   * `const NAME := …`   — final binding
5324///   * `NAME := …`         — ordinary `:=` output binding
5325///
5326/// The collector also mirrors the workload-root kernel's auto-input
5327/// behaviour (see `bindings.rs::compile_workload_kernel`): when no
5328/// Polydat source anywhere in the workload declares any `input` slot,
5329/// the runtime injects `input cycle: u64` so `{cycle}` resolves at
5330/// op-template substitution time. Reflecting that injection in the
5331/// validator allow-set prevents false-positive rejection of
5332/// `{cycle}` placeholders in workloads with no explicit `bindings:`
5333/// block (e.g. inline `op="tick={cycle}"`).
5334fn collect_polydat_binding_names(
5335    workload: &nmbrs_workload::model::Workload,
5336) -> std::collections::HashSet<String> {
5337    let mut out = std::collections::HashSet::new();
5338    use nmbrs_workload::model::BindingsDef;
5339
5340    let mut any_input_decl = false;
5341    let mut scan_bindings =
5342        |bindings: &BindingsDef, sink: &mut std::collections::HashSet<String>| {
5343            match bindings {
5344                BindingsDef::PolydatSource(s) => {
5345                    scan_polydat_binding_lhs(sink, s);
5346                    if s.lines().any(|l| l.trim_start().starts_with("input ")) {
5347                        any_input_decl = true;
5348                    }
5349                }
5350                BindingsDef::Map(m) => {
5351                    // Legacy nosqlbench-style chains (`Hash(); Mod(...)`)
5352                    // are translated into Polydat bindings at runtime by
5353                    // `compile_bindings_with_opts`; the keys of the map
5354                    // become the wire names those translations produce.
5355                    // The validator's allow-set must reflect those names
5356                    // so referencing `{user_id}` in op text — where
5357                    // `user_id: Hash(); Mod(...)` is the binding key —
5358                    // doesn't trip the undeclared-placeholder guard.
5359                    for name in m.keys() {
5360                        sink.insert(name.clone());
5361                    }
5362                }
5363            }
5364        };
5365
5366    scan_bindings(&workload.bindings, &mut out);
5367    // Top-level `workload.ops` carry their own `bindings:` blocks
5368    // in inline-mode workloads (the inline parser puts
5369    // synthesised `__inline_N := <expr>` lines there). Without
5370    // walking this collection, the validator misses every
5371    // inline-rewrite-generated wire name.
5372    for op in &workload.ops {
5373        scan_bindings(&op.bindings, &mut out);
5374    }
5375    for phase in workload.phases.values() {
5376        scan_bindings(&phase.bindings, &mut out);
5377        for op in &phase.ops {
5378            scan_bindings(&op.bindings, &mut out);
5379        }
5380    }
5381
5382    // Runtime mirror: workload-root kernel auto-injects
5383    // `input cycle: u64` when no `input` line is declared anywhere.
5384    // Surface that injection to the validator.
5385    if !any_input_decl {
5386        out.insert("cycle".to_string());
5387    }
5388    out
5389}
5390
5391/// One occurrence of an invalid `{name}` placeholder inside a
5392/// Polydat expression context. The `location` describes which source
5393/// block in the workload (e.g. `"phase 'ann_query' bindings"`),
5394/// and the `placeholder` is the literal body that appeared inside
5395/// the offending `{...}` — kept verbatim so the error formatter
5396/// can locate the exact YAML line by substring search.
5397#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
5398struct PolydatBraceFinding {
5399    location: String,
5400    placeholder: String,
5401}
5402
5403/// Collect every `{name}` placeholder that appears inside a GK
5404/// source context but OUTSIDE a string literal — these will
5405/// always fail Polydat compile because `{...}` isn't valid expression
5406/// syntax. Each finding names the workload block it came from
5407/// so the error formatter can point at the offending site.
5408///
5409/// Walks every Polydat source in the workload: top-level `bindings:`,
5410/// per-phase `bindings:`, per-op `bindings:`.
5411fn collect_polydat_brace_refs(
5412    workload: &nmbrs_workload::model::Workload,
5413) -> Vec<PolydatBraceFinding> {
5414    use nmbrs_workload::model::BindingsDef;
5415    let mut out: Vec<PolydatBraceFinding> = Vec::new();
5416    // Braces are no longer categorically invalid in Polydat: the block form of
5417    // conditional selection (`if <cond> { a } else { b }`) uses them. So a brace is
5418    // only evidence of a stray YAML placeholder when the source ALSO fails to parse.
5419    // Gating on parseability keeps this check doing its actual job — converting a
5420    // cryptic "expected expression, got LBrace" into a message that names the file,
5421    // line and placeholder — without rejecting valid if-expressions.
5422    let mut push_refs = |loc: &str, source: &str| {
5423        let parses = polydat::dsl::lexer::lex(source)
5424            .ok()
5425            .and_then(|toks| polydat::dsl::parser::parse(toks).ok())
5426            .is_some();
5427        if parses {
5428            return;
5429        }
5430        for name in scan_polydat_braced_refs(source) {
5431            out.push(PolydatBraceFinding {
5432                location: loc.to_string(),
5433                placeholder: name,
5434            });
5435        }
5436    };
5437    if let BindingsDef::PolydatSource(s) = &workload.bindings {
5438        push_refs("workload `bindings:`", s);
5439    }
5440    for (phase_name, phase) in &workload.phases {
5441        if let BindingsDef::PolydatSource(s) = &phase.bindings {
5442            push_refs(&format!("phase '{phase_name}' bindings"), s);
5443        }
5444        for op in &phase.ops {
5445            if let BindingsDef::PolydatSource(s) = &op.bindings {
5446                push_refs(&format!("phase '{phase_name}' op-bindings"), s);
5447            }
5448        }
5449    }
5450    out
5451}
5452
5453/// Scan the raw YAML source for the first line that contains
5454/// the given placeholder text (with surrounding braces).
5455/// Returns the 1-based line number when found, `None` otherwise.
5456///
5457/// Used to upgrade the GK-brace validator's error message from
5458/// "phase 'foo' bindings" to a file:line locator the operator
5459/// can click on or jump to. Works because YAML block scalars
5460/// (`|` / `>`) preserve the body verbatim; the offending
5461/// `{name}` substring appears in the file exactly as the
5462/// validator captured it.
5463///
5464/// Falls back to `None` on the rare cases where the literal
5465/// also appears in an unrelated comment or string — the
5466/// validator's caller treats that as "give the location but
5467/// no line number." The substring is namespaced enough
5468/// (`{name}` with curly braces) that collisions are unlikely
5469/// in practice.
5470fn find_yaml_line_for_brace(yaml_source: &str, placeholder: &str) -> Option<usize> {
5471    let needle = format!("{{{placeholder}}}");
5472    yaml_source
5473        .lines()
5474        .enumerate()
5475        .find(|(_, line)| line.contains(&needle))
5476        .map(|(idx, _)| idx + 1)
5477}
5478
5479/// Scan Polydat source for `{name}` placeholders that appear OUTSIDE
5480/// string literals and OUTSIDE comments. Inside `"..."` or
5481/// `'...'` (with backslash escapes), `{...}` is part of the
5482/// string and gets handled by runtime interpolation — leave it
5483/// alone. Lines starting with `#` (and content after `#` on any
5484/// line) are comments — also skipped.
5485fn scan_polydat_braced_refs(source: &str) -> Vec<String> {
5486    let bytes = source.as_bytes();
5487    let mut out: Vec<String> = Vec::new();
5488    let mut i = 0;
5489    while i < bytes.len() {
5490        let b = bytes[i];
5491        // Line comment — skip to next newline.
5492        if b == b'#' {
5493            while i < bytes.len() && bytes[i] != b'\n' {
5494                i += 1;
5495            }
5496            continue;
5497        }
5498        // String literal — skip past the closing quote.
5499        if b == b'"' || b == b'\'' {
5500            let quote = b;
5501            i += 1;
5502            while i < bytes.len() {
5503                if bytes[i] == b'\\' && i + 1 < bytes.len() {
5504                    i += 2;
5505                    continue;
5506                }
5507                if bytes[i] == quote {
5508                    i += 1;
5509                    break;
5510                }
5511                i += 1;
5512            }
5513            continue;
5514        }
5515        // Outside any string — `{` opens a brace placeholder.
5516        if b == b'{' {
5517            // Find the matching `}`, allowing one level of
5518            // nesting for composite forms like `{k_{k}_limits}`.
5519            // We only need the OUTER body for the error message
5520            // — the inner placeholders are also wrong but the
5521            // outer is what the operator sees.
5522            let start = i + 1;
5523            let mut depth = 1;
5524            let mut j = start;
5525            while j < bytes.len() && depth > 0 {
5526                match bytes[j] {
5527                    b'{' => depth += 1,
5528                    b'}' => depth -= 1,
5529                    _ => {}
5530                }
5531                if depth == 0 {
5532                    break;
5533                }
5534                j += 1;
5535            }
5536            if depth == 0 && j > start {
5537                let body = &source[start..j];
5538                // Trim whitespace; ignore obviously-empty bodies.
5539                let trimmed = body.trim();
5540                if !trimmed.is_empty() {
5541                    out.push(trimmed.to_string());
5542                }
5543                i = j + 1;
5544                continue;
5545            }
5546            // Unmatched `{` — let the Polydat parser handle it with
5547            // its own error; don't double-report.
5548            break;
5549        }
5550        i += 1;
5551    }
5552    out
5553}
5554
5555/// Line-by-line scan of Polydat source for locally-bound names —
5556/// `cursor NAME = …`, `shared NAME := …`, `const NAME := …`,
5557/// `volatile NAME := …`, bare `NAME := …` assignments, and
5558/// `input NAME[: TYPE]` / `input (NAME[: TYPE], ...)` declarations.
5559/// Skips comments and blank lines. Lines that don't match any of
5560/// these shapes (function-call statements, comments, expression
5561/// continuations) are ignored.
5562fn scan_polydat_binding_lhs(out: &mut std::collections::HashSet<String>, source: &str) {
5563    for raw_line in source.lines() {
5564        let line = raw_line.trim();
5565        if line.is_empty() || line.starts_with('#') {
5566            continue;
5567        }
5568        // `input` declarations: collect declared slot names without
5569        // requiring an `=` / `:=` suffix. Both bare (`input cycle: u64`)
5570        // and tuple (`input (cycle: u64, q: f64)`) forms are handled.
5571        if let Some(rest) = line.strip_prefix("input ") {
5572            scan_input_decl_names(out, rest.trim());
5573            continue;
5574        }
5575        // `extern` declarations (`extern name: type [= default]`,
5576        // `extern (a: u64, b: f64)`) declare wire names just like
5577        // `input` — same `name: type` shape. Without this, a
5578        // `{name}` placeholder referencing an extern-declared wire
5579        // (e.g. a same-op capture target) trips the
5580        // undeclared-placeholder guard.
5581        if let Some(rest) = line.strip_prefix("extern ") {
5582            scan_input_decl_names(out, rest.trim());
5583            continue;
5584        }
5585        // Strip leading modifier (`const `, `cursor `, `shared `,
5586        // `volatile `); body is what follows. Modifiers can be
5587        // combined in a few cases (e.g. `shared const`,
5588        // `shared volatile`), so loop until no recognised prefix
5589        // remains.
5590        let mut body = line;
5591        loop {
5592            let stripped = body
5593                .strip_prefix("const ")
5594                .or_else(|| body.strip_prefix("cursor "))
5595                .or_else(|| body.strip_prefix("shared "))
5596                .or_else(|| body.strip_prefix("volatile "));
5597            match stripped {
5598                Some(rest) => body = rest,
5599                None => break,
5600            }
5601        }
5602        // Tuple-destructure LHS: `(a, b, c) := <expr>`. Each
5603        // identifier inside the parens becomes a separate
5604        // declared name. Used by multi-output stdlib nodes
5605        // (e.g. `(y, mo, d, h, mi, s, ms) := date_components(0)`)
5606        // and any other binding that unpacks multiple outputs.
5607        if body.starts_with('(') {
5608            if let Some(close) = body.find(')') {
5609                let after = body[close + 1..].trim_start();
5610                if after.starts_with(":=") || after.starts_with('=') {
5611                    for raw in body[1..close].split(',') {
5612                        let name = raw.trim();
5613                        if !name.is_empty() {
5614                            out.insert(name.to_string());
5615                        }
5616                    }
5617                }
5618            }
5619            continue;
5620        }
5621        // Pull the leading identifier.
5622        let bytes = body.as_bytes();
5623        let mut i = 0;
5624        while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
5625            i += 1;
5626        }
5627        if i == 0 {
5628            continue;
5629        }
5630        // What follows the identifier? Skip whitespace.
5631        let mut j = i;
5632        while j < bytes.len() && bytes[j].is_ascii_whitespace() {
5633            j += 1;
5634        }
5635        // Must be `=` (init/cursor) or `:=` (assignment); reject
5636        // anything else (function calls, expressions starting
5637        // with an ident, etc.).
5638        let is_binding = bytes.get(j) == Some(&b'=')
5639            || (bytes.get(j) == Some(&b':') && bytes.get(j + 1) == Some(&b'='));
5640        if is_binding {
5641            out.insert(body[..i].to_string());
5642            continue;
5643        }
5644        // Typed cell form: `name: type := default` (e.g.
5645        // `shared sstables: u64 := 0`). The `:` here is a type
5646        // annotation, not `:=` — skip the type token and accept
5647        // iff an assignment follows it. Without this arm, typed
5648        // shared/volatile declarations were invisible to the
5649        // undeclared-placeholder validator and any `{name}`
5650        // reference to one tripped a false positive.
5651        if bytes.get(j) == Some(&b':') {
5652            let rest = body[j + 1..].trim_start();
5653            let te = rest
5654                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
5655                .unwrap_or(rest.len());
5656            if te > 0 {
5657                let after_ty = rest[te..].trim_start();
5658                if after_ty.starts_with(":=") || after_ty.starts_with('=') {
5659                    out.insert(body[..i].to_string());
5660                }
5661            }
5662        }
5663    }
5664}
5665
5666/// Parse the name(s) out of an `input` declaration body (the text
5667/// after the `input ` keyword has been stripped).
5668///
5669/// Accepts both surface forms:
5670/// - `cycle` / `cycle: u64`        → inserts `cycle`
5671/// - `(a: u64, b: f64, ...)`        → inserts each declared name
5672///
5673/// Mirrors `parse_input_decl` in the Polydat parser; this is a
5674/// lightweight scanner used by scope-elision to register
5675/// locally-bound names without re-running the full lexer/parser.
5676fn scan_input_decl_names(out: &mut std::collections::HashSet<String>, body: &str) {
5677    let body = body.trim();
5678    if let Some(inner) = body.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
5679        for part in inner.split(',') {
5680            let name = part.trim().split(':').next().unwrap_or("").trim();
5681            if !name.is_empty() {
5682                out.insert(name.to_string());
5683            }
5684        }
5685        return;
5686    }
5687    let name = body.split(':').next().unwrap_or("").trim();
5688    if !name.is_empty() {
5689        out.insert(name.to_string());
5690    }
5691}
5692
5693/// Resolve a scenario name to a list of phase names.
5694fn resolve_scenario(
5695    scenarios: &HashMap<String, Vec<nmbrs_workload::model::ScenarioNode>>,
5696    phase_order: &[String],
5697    name: &str,
5698) -> Result<Vec<nmbrs_workload::model::ScenarioNode>, String> {
5699    if let Some(nodes) = scenarios.get(name) {
5700        return Ok(nodes.clone());
5701    }
5702    if name == "default" && !phase_order.is_empty() {
5703        return Ok(phase_order
5704            .iter()
5705            .map(|n| nmbrs_workload::model::ScenarioNode::Phase(n.clone()))
5706            .collect());
5707    }
5708    Err(format!("scenario '{name}' not found"))
5709}
5710
5711/// Format a scenario tree for display — one construct per line,
5712/// nested with two-space indent per level. Phases include their
5713/// declared `cycles:` and `concurrency:` config when available
5714/// from the workload's phase map so the operator can see the
5715/// run shape at a glance.
5716///
5717/// Example output for the full_cql_vector fulltest scenario:
5718///
5719/// ```text
5720/// scenario 'test_oracles'
5721///   for_each profile in matching_profiles('{dataset}', '{oracles_prefix}')
5722///     for_each table in vec_{profile}
5723///       teardown                          (cycles: 1, concurrency: 1)
5724///       schema                            (cycles: 1, concurrency: 1)
5725///       rampup
5726///       jolokia_flush
5727///       for_combinations [k, limit] in {k_values}, {k_{k}_limits}
5728///         ann_query                       (concurrency: {query_concurrency})
5729/// scenario 'test_fknn'
5730///   ...
5731/// ```
5732///
5733/// The replaced LISP-shaped one-liner had bracket nesting that
5734/// scaled badly past two levels and required mental parsing to
5735/// see the loop structure.
5736fn format_scenario_tree(
5737    nodes: &[nmbrs_workload::model::ScenarioNode],
5738    phases: &std::collections::HashMap<String, nmbrs_workload::model::WorkloadPhase>,
5739) -> String {
5740    let mut out = String::new();
5741    format_scenario_nodes(nodes, phases, 0, &mut out);
5742    // Trim trailing newline so the runner's log call doesn't
5743    // emit a double-blank line.
5744    if out.ends_with('\n') {
5745        out.pop();
5746    }
5747    out
5748}
5749
5750/// Render a multi-coord comprehension's `[vars] in [specs]`
5751/// in two column-aligned lines. Column `i` is padded to the
5752/// widest of `vars[i]` and `specs[i]` so corresponding entries
5753/// stack vertically:
5754///
5755/// ```text
5756/// for [sm,          mnc,          bw,          eh,           alf_label]
5757///  in [{sm_values}, {mnc_values}, {bw_values}, {eh_values}, concat({alf_label_values})]
5758/// ```
5759///
5760/// `for ` and ` in ` are 4 chars (padding `in` with a leading
5761/// space) so the `[` brackets and every column thereafter
5762/// share the same vertical line. Color highlights the
5763/// keywords when the active terminal supports it; on a
5764/// piped/no-color stderr the output stays plain.
5765///
5766/// `indent_prefix` is the per-depth indent at the call site
5767/// — applied to the second line so it sits at the same depth
5768/// as the first.
5769fn format_for_combinations(pairs: &[(String, String)], indent_prefix: &str, color: bool) -> String {
5770    let kw_open = if color { "\x1b[1;36m" } else { "" };
5771    let kw_close = if color { "\x1b[0m" } else { "" };
5772    let bracket_open = if color { "\x1b[2m" } else { "" };
5773    let bracket_close = if color { "\x1b[0m" } else { "" };
5774
5775    let widths: Vec<usize> = pairs
5776        .iter()
5777        .map(|(v, s)| v.chars().count().max(s.chars().count()))
5778        .collect();
5779
5780    let pad = |entry: &str, idx: usize, last: bool| -> String {
5781        // Last column gets no trailing comma + no padding —
5782        // the closing `]` lands flush against the final token.
5783        if last {
5784            entry.to_string()
5785        } else {
5786            // `<entry>,` then pad to `widths[idx] + 1` so the
5787            // next column begins at a constant offset.
5788            let with_comma = format!("{entry},");
5789            let width_target = widths[idx] + 1; // +1 for the comma
5790            let visible = with_comma.chars().count();
5791            if visible >= width_target {
5792                with_comma
5793            } else {
5794                format!("{with_comma}{:<pad$}", "", pad = width_target - visible)
5795            }
5796        }
5797    };
5798
5799    let last_idx = pairs.len().saturating_sub(1);
5800    let vars_line: String = pairs
5801        .iter()
5802        .enumerate()
5803        .map(|(i, (v, _))| pad(v, i, i == last_idx))
5804        .collect::<Vec<_>>()
5805        .join(" ");
5806    let specs_line: String = pairs
5807        .iter()
5808        .enumerate()
5809        .map(|(i, (_, s))| pad(s, i, i == last_idx))
5810        .collect::<Vec<_>>()
5811        .join(" ");
5812
5813    format!(
5814        "{kw_open}for{kw_close} {bracket_open}[{bracket_close}{vars_line}{bracket_open}]{bracket_close}\n\
5815         {indent_prefix} {kw_open}in{kw_close} {bracket_open}[{bracket_close}{specs_line}{bracket_open}]{bracket_close}"
5816    )
5817}
5818
5819fn format_scenario_nodes(
5820    nodes: &[nmbrs_workload::model::ScenarioNode],
5821    phases: &std::collections::HashMap<String, nmbrs_workload::model::WorkloadPhase>,
5822    depth: usize,
5823    out: &mut String,
5824) {
5825    use nmbrs_workload::model::ScenarioNode::*;
5826    let indent = " ".repeat(depth);
5827    for node in nodes {
5828        match node {
5829            Phase(name) => {
5830                let suffix = phases
5831                    .get(name)
5832                    .map(format_phase_config_suffix)
5833                    .unwrap_or_default();
5834                if suffix.is_empty() {
5835                    out.push_str(&format!("{indent}{name}\n"));
5836                } else {
5837                    // Pad name to a fixed column so the
5838                    // `(cycles:..., concurrency:...)` chip lines
5839                    // up across consecutive phases. 32 chars
5840                    // covers the typical phase names; longer
5841                    // names just push past the column without
5842                    // breaking layout.
5843                    out.push_str(&format!("{indent}{name:<32} {suffix}\n",));
5844                }
5845            }
5846            Comprehension {
5847                comprehension,
5848                children,
5849                ..
5850            } => {
5851                // Algebra-native display: walk the AST once to
5852                // detect Union vs flat, then format. Matches
5853                // the scope_tree::label_for_comprehension shape
5854                // at one level of detail finer (includes the
5855                // spec_expr for non-Union shapes).
5856                use polydat::iteration::comprehension::Comprehension as Comp;
5857                // Peel outer Order/Filter for structural detection.
5858                let mut body = comprehension;
5859                while let Comp::Order { child, .. } | Comp::Filter { child, .. } = body {
5860                    body = child;
5861                }
5862                let header = match body {
5863                    Comp::Union { children } => {
5864                        let names = comprehension.coordinate_names().join(", ");
5865                        format!("for_each_union [{}] ({} sub-spaces)", names, children.len())
5866                    }
5867                    _ => {
5868                        let pairs = comprehension.coordinate_specs();
5869                        if pairs.len() == 1 {
5870                            let (var, spec) = &pairs[0];
5871                            format!("for_each {var} in {spec}")
5872                        } else {
5873                            // Two-line column-aligned form for
5874                            // multi-coord comprehensions: variable
5875                            // names on the first line, source
5876                            // expressions on the second, each
5877                            // column padded to its widest
5878                            // (var, spec) pair so the columns
5879                            // line up vertically. Keywords
5880                            // `for` / ` in` are right-aligned
5881                            // so the `[` brackets land in the
5882                            // same column.
5883                            format_for_combinations(&pairs, &indent, crate::observer::use_color())
5884                        }
5885                    }
5886                };
5887                out.push_str(&format!("{indent}{header}\n"));
5888                format_scenario_nodes(children, phases, depth + 1, out);
5889            }
5890            DoWhile {
5891                condition,
5892                counter,
5893                children,
5894            } => {
5895                let ctr = counter
5896                    .as_deref()
5897                    .map(|c| format!(" (counter={c})"))
5898                    .unwrap_or_default();
5899                out.push_str(&format!("{indent}do_while '{condition}'{ctr}\n"));
5900                format_scenario_nodes(children, phases, depth + 1, out);
5901            }
5902            DoUntil {
5903                condition,
5904                counter,
5905                children,
5906            } => {
5907                let ctr = counter
5908                    .as_deref()
5909                    .map(|c| format!(" (counter={c})"))
5910                    .unwrap_or_default();
5911                out.push_str(&format!("{indent}do_until '{condition}'{ctr}\n"));
5912                format_scenario_nodes(children, phases, depth + 1, out);
5913            }
5914            IncludedScenario { name, children } => {
5915                out.push_str(&format!("{indent}scenario '{name}'\n"));
5916                format_scenario_nodes(children, phases, depth + 1, out);
5917            }
5918            Bindings { source, children } => {
5919                // First non-empty line of the source as a one-
5920                // line summary in the scenario-tree dump. Long
5921                // bodies stay readable in the YAML; the
5922                // hierarchical view just teases the binding.
5923                let summary = source
5924                    .lines()
5925                    .map(str::trim)
5926                    .find(|l| !l.is_empty())
5927                    .unwrap_or("");
5928                if source.lines().filter(|l| !l.trim().is_empty()).count() > 1 {
5929                    out.push_str(&format!("{indent}bindings: {summary} …\n"));
5930                } else {
5931                    out.push_str(&format!("{indent}bindings: {summary}\n"));
5932                }
5933                format_scenario_nodes(children, phases, depth + 1, out);
5934            }
5935        }
5936    }
5937}
5938
5939/// Render the `(cycles: X, concurrency: Y)` suffix for a phase
5940/// line in the scenario-tree summary. Includes only the fields
5941/// that the phase actually declared — phases that inherit the
5942/// runtime defaults skip the chip entirely so the tree line
5943/// stays uncluttered. Strings are shown verbatim (including
5944/// `{name}` placeholders) so the operator sees the workload's
5945/// declared intent rather than a runtime-evaluated number.
5946fn format_phase_config_suffix(phase: &nmbrs_workload::model::WorkloadPhase) -> String {
5947    let mut parts: Vec<String> = Vec::new();
5948    if let Some(c) = phase.cycles.as_deref()
5949        && !c.is_empty()
5950    {
5951        parts.push(format!("cycles: {c}"));
5952    }
5953    if let Some(c) = phase.concurrency.as_deref()
5954        && !c.is_empty()
5955    {
5956        parts.push(format!("concurrency: {c}"));
5957    }
5958    if parts.is_empty() {
5959        String::new()
5960    } else {
5961        format!("({})", parts.join(", "))
5962    }
5963}
5964
5965/// Bind an implementation into the blueprint its `implements:` names
5966/// (SRD-108), returning the bound workload: the blueprint, with the
5967/// implementation's op bodies, params, scenarios and report folded in.
5968///
5969/// `workload_file` is the implementation's own identity: its path, or
5970/// its catalog name when `is_bundled`. The blueprint reference
5971/// resolves relative to it, as an `extends:` target does.
5972fn bind_into_declared_blueprint(
5973    implementation: nmbrs_workload::model::Workload,
5974    target: &str,
5975    workload_file: Option<&str>,
5976    is_bundled: bool,
5977    params: &HashMap<String, String>,
5978) -> Result<nmbrs_workload::model::Workload, String> {
5979    let base_dir = (!is_bundled)
5980        .then(|| {
5981            workload_file
5982                .map(std::path::Path::new)
5983                .and_then(|p| p.parent().map(|d| d.to_path_buf()))
5984        })
5985        .flatten();
5986    let bundled_origin = is_bundled.then_some(workload_file).flatten();
5987    let (mut blueprint, blueprint_id) =
5988        load_secondary_workload(target, params, base_dir.as_deref(), bundled_origin)?;
5989    crate::diag!(
5990        crate::observer::LogLevel::Info,
5991        "implements: binding '{}' into blueprint '{blueprint_id}'",
5992        workload_file.unwrap_or("<inline>")
5993    );
5994    nmbrs_workload::implements::bind_implementation(&mut blueprint, implementation)
5995        .map_err(|e| format!("implements binding: {e}"))?;
5996    Ok(blueprint)
5997}
5998
5999/// Load the workload file at `path` as a run of it would: its
6000/// `extends:` chain merged and, when it is an implementation, bound
6001/// into its blueprint (SRD-108). Every command that reads a workload's
6002/// model reads this, so `nmbrs report workload=<impl>` sees the report
6003/// the run of that file rendered.
6004pub fn load_bound_workload_from_path(
6005    path: &std::path::Path,
6006    params: &HashMap<String, String>,
6007) -> Result<nmbrs_workload::model::Workload, String> {
6008    let workload = nmbrs_workload::parse::parse_workload_from_path(path, params)?;
6009    match workload.implements.clone() {
6010        Some(target) => {
6011            let file = path.to_string_lossy();
6012            bind_into_declared_blueprint(workload, &target, Some(file.as_ref()), false, params)
6013        }
6014        None => Ok(workload),
6015    }
6016}
6017
6018/// SRD-108 Part B — load a secondary workload document (an
6019/// `implements:` target, or the `impl=` module) through the same
6020/// resolution the primary `workload=` uses: local file first,
6021/// then the bundled catalog. Returns the parsed workload plus its
6022/// canonical identity string (canonicalized path, or catalog
6023/// name) for target-matching.
6024fn load_secondary_workload(
6025    reference: &str,
6026    params: &HashMap<String, String>,
6027    base_dir: Option<&std::path::Path>,
6028    bundled_origin: Option<&str>,
6029) -> Result<(nmbrs_workload::model::Workload, String), String> {
6030    match resolve_secondary_ref(reference, base_dir, bundled_origin)? {
6031        ResolvedWorkload::Path(path) => {
6032            let workload = nmbrs_workload::parse::parse_workload_from_path(
6033                std::path::Path::new(&path),
6034                params,
6035            )
6036            .map_err(|e| format!("parse workload '{path}': {e}"))?;
6037            Ok((workload, canonical_identity(&path)))
6038        }
6039        ResolvedWorkload::Bundled(bundled) => {
6040            let (merged, res_warnings) =
6041                nmbrs_workload::extends::load_and_merge_bundled(bundled)
6042                    .map_err(|e| format!("bundled workload `{}`: {e}", bundled.name))?;
6043            let mut workload = nmbrs_workload::parse::parse_workload(&merged, params)
6044                .map_err(|e| format!("parse bundled workload `{}`: {e}", bundled.name))?;
6045            workload.resolution_warnings.extend(res_warnings);
6046            Ok((workload, bundled.name.to_string()))
6047        }
6048    }
6049}
6050
6051/// Resolve a workload reference to its canonical identity WITHOUT
6052/// parsing it — used to compare an `implements:` target against
6053/// the invoked `workload=`.
6054fn workload_ref_identity(
6055    reference: &str,
6056    base_dir: Option<&std::path::Path>,
6057    bundled_origin: Option<&str>,
6058) -> Result<String, String> {
6059    match resolve_secondary_ref(reference, base_dir, bundled_origin)? {
6060        ResolvedWorkload::Path(path) => Ok(canonical_identity(&path)),
6061        ResolvedWorkload::Bundled(bundled) => Ok(bundled.name.to_string()),
6062    }
6063}
6064
6065/// SRD-109 Part 2 — resolve a driver manifest by name: local
6066/// `drivers/<name>/driver.yaml` under the cwd first, then the
6067/// bundled catalog entry `drivers/<name>/driver`. Both at once
6068/// FAVORS the local manifest (SRD-85 nearest-first) with a
6069/// logged warning naming both — shadowing is allowed but never
6070/// silent. Returns the manifest plus the resolved LIBRARY
6071/// reference: a file path for a local manifest, a catalog name
6072/// for a bundled one. An error when neither exists.
6073fn resolve_driver_manifest(
6074    name: &str,
6075) -> Result<(nmbrs_workload::drivers::DriverManifest, String), String> {
6076    let local_path = std::path::Path::new("drivers")
6077        .join(name)
6078        .join("driver.yaml");
6079    let catalog_name = format!("drivers/{name}/driver");
6080    let bundled = nmbrs_workload::catalog::lookup(&catalog_name);
6081    match (local_path.is_file(), bundled) {
6082        (true, Some(_)) => {
6083            crate::observer::log_tagged(
6084                crate::observer::LogLevel::Warn,
6085                crate::observer::EventTag::in_flight(crate::observer::EventCategory::Resolution),
6086                &format!(
6087                    "resolve: driver '{name}' matches multiple resources — local \
6088                 manifest {} AND bundled driver `{catalog_name}` — using the \
6089                 local manifest (filesystem-first). Same-named resources in \
6090                 multiple places invite confusion: prefer a unique name.",
6091                    local_path.display()
6092                ),
6093            );
6094            let source = std::fs::read_to_string(&local_path)
6095                .map_err(|e| format!("read driver manifest {}: {e}", local_path.display()))?;
6096            let manifest = nmbrs_workload::drivers::parse_driver_manifest(
6097                &source,
6098                &local_path.display().to_string(),
6099            )?;
6100            verify_driver_identity(&manifest, name)?;
6101            let dir = local_path.parent().expect("manifest path has a parent");
6102            let library_ref = resolve_driver_library_local(dir, &manifest.library)?;
6103            Ok((manifest, library_ref))
6104        }
6105        (true, None) => {
6106            let source = std::fs::read_to_string(&local_path)
6107                .map_err(|e| format!("read driver manifest {}: {e}", local_path.display()))?;
6108            let manifest = nmbrs_workload::drivers::parse_driver_manifest(
6109                &source,
6110                &local_path.display().to_string(),
6111            )?;
6112            verify_driver_identity(&manifest, name)?;
6113            let dir = local_path.parent().expect("manifest path has a parent");
6114            let library_ref = resolve_driver_library_local(dir, &manifest.library)?;
6115            Ok((manifest, library_ref))
6116        }
6117        (false, Some(entry)) => {
6118            let manifest =
6119                nmbrs_workload::drivers::parse_driver_manifest(entry.source, &catalog_name)?;
6120            verify_driver_identity(&manifest, name)?;
6121            let stem = manifest
6122                .library
6123                .strip_suffix(".yaml")
6124                .or_else(|| manifest.library.strip_suffix(".yml"))
6125                .unwrap_or(&manifest.library);
6126            let library_ref = format!("drivers/{name}/{stem}");
6127            Ok((manifest, library_ref))
6128        }
6129        (false, None) => Err(unknown_driver_error(name)),
6130    }
6131}
6132
6133/// `driver=<name>` names a driver manifest, and none is called
6134/// `name`. The error lists the manifests that exist, and points an
6135/// adapter name at `adapter=`, since `driver=` never selects one.
6136fn unknown_driver_error(name: &str) -> String {
6137    let known = nmbrs_workload::drivers::manifest_names();
6138    let adapter_hint = if crate::adapter::find_adapter_registration(name).is_some() {
6139        format!(" '{name}' is an adapter; select it with `adapter={name}`.")
6140    } else {
6141        String::new()
6142    };
6143    format!(
6144        "driver={name}: no driver manifest named '{name}' (looked for \
6145         ./drivers/{name}/driver.yaml and the bundled drivers/{name}/driver).\
6146         {adapter_hint} Known drivers: [{}]",
6147        known.join(", ")
6148    )
6149}
6150
6151/// A manifest must be named for the directory it lives in — a
6152/// mismatch is a packaging bug surfaced at load, not a silent
6153/// re-route.
6154fn verify_driver_identity(
6155    manifest: &nmbrs_workload::drivers::DriverManifest,
6156    name: &str,
6157) -> Result<(), String> {
6158    if manifest.driver != name {
6159        return Err(format!(
6160            "driver manifest for '{name}' declares `driver: {}` — the \
6161             manifest must be named for its directory",
6162            manifest.driver
6163        ));
6164    }
6165    Ok(())
6166}
6167
6168/// Resolve a local manifest's `library:` reference beside the
6169/// manifest: as written first, then with `.yaml` appended.
6170fn resolve_driver_library_local(dir: &std::path::Path, library: &str) -> Result<String, String> {
6171    let as_written = dir.join(library);
6172    if as_written.is_file() {
6173        return Ok(as_written.display().to_string());
6174    }
6175    let with_ext = dir.join(format!("{library}.yaml"));
6176    if with_ext.is_file() {
6177        return Ok(with_ext.display().to_string());
6178    }
6179    Err(format!(
6180        "driver manifest {}: library '{library}' not found beside the manifest",
6181        dir.display()
6182    ))
6183}
6184
6185/// Apply a resolved driver manifest to the invocation params:
6186/// the library lands as `workload=` (no workload given) or
6187/// `impl=` (a blueprint was invoked); the backing adapter and the
6188/// manifest's default params fill only ABSENT keys, so the CLI
6189/// always wins and the defaults still overlay the library's own
6190/// declared params (this map is the CLI overlay layer).
6191fn apply_driver_manifest(
6192    params: &mut HashMap<String, String>,
6193    driver_name: &str,
6194    manifest: nmbrs_workload::drivers::DriverManifest,
6195    library_ref: String,
6196    workload_given: bool,
6197) -> Result<(), String> {
6198    if params.contains_key("impl") {
6199        return Err(format!(
6200            "driver={driver_name} supplies the implementation library \
6201             ('{}') — impl= conflicts; pass one or the other",
6202            manifest.library
6203        ));
6204    }
6205    if workload_given {
6206        params.insert("impl".into(), library_ref.clone());
6207    } else {
6208        params.insert("workload".into(), library_ref.clone());
6209    }
6210    params
6211        .entry("adapter".to_string())
6212        .or_insert_with(|| manifest.adapter.clone());
6213    for (k, v) in &manifest.default_params {
6214        params.entry(k.clone()).or_insert_with(|| v.clone());
6215    }
6216    crate::diag!(
6217        crate::observer::LogLevel::Info,
6218        "driver: {driver_name} → adapter={}, library={library_ref}",
6219        manifest.adapter
6220    );
6221    Ok(())
6222}
6223
6224/// Resolve a secondary workload reference the way `extends:`
6225/// targets resolve: relative to the REFERRING DOCUMENT's
6226/// directory first (when one exists on disk), then the standard
6227/// cwd-local + bundled-catalog path. Without the base-dir leg, an
6228/// `implements: ./blueprint.yaml` inside a file would only resolve
6229/// when the invoking cwd happens to be the file's directory.
6230fn resolve_secondary_ref(
6231    reference: &str,
6232    base_dir: Option<&std::path::Path>,
6233    bundled_origin: Option<&str>,
6234) -> Result<ResolvedWorkload, String> {
6235    // SRD-85 nearest-first: every candidate is enumerated and the
6236    // nearest wins — the logical filesystem location is favored
6237    // over the embedded catalog BY DEFAULT (a fresh checkout must
6238    // never be silently shadowed by a stale binary's catalog).
6239    // Multiple matches are a warnable condition, logged with every
6240    // candidate named; never a hard error and never silent.
6241    let pinned = reference.starts_with("./") || reference.starts_with("../");
6242
6243    // 1. The referring document's own directory (nearest).
6244    let origin_file: Option<String> = base_dir
6245        .map(|dir| dir.join(reference))
6246        .filter(|c| c.is_file())
6247        .map(|c| c.display().to_string());
6248
6249    // A `./`-pinned reference that resolves beside its referring
6250    // FILE is explicit — no enumeration, no warning.
6251    if pinned
6252        && base_dir.is_some()
6253        && let Some(file) = origin_file
6254    {
6255        return Ok(ResolvedWorkload::Path(file));
6256    }
6257
6258    // 2. The cwd's logical layout (exact path, extension probing,
6259    //    cwd `workloads/`).
6260    let cwd_file: Option<String> = resolve_workload_file(reference).filter(|p| {
6261        // Dedupe against the origin-dir candidate.
6262        origin_file.as_deref().map(canonical_identity) != Some(canonical_identity(p))
6263    });
6264
6265    // 3. The bundled catalog: exact name, then the sibling idiom —
6266    //    the referring bundled document's namespace — then the bare
6267    //    stem (extension and `./` stripped: files reference siblings
6268    //    by filename, catalog names carry none).
6269    let stem = reference
6270        .strip_suffix(".yaml")
6271        .or_else(|| reference.strip_suffix(".yml"))
6272        .unwrap_or(reference);
6273    let stem = stem.strip_prefix("./").unwrap_or(stem);
6274    let ns_stem = bundled_origin
6275        .and_then(|o| o.rsplit_once('/'))
6276        .map(|(ns, _)| format!("{ns}/{stem}"));
6277    let bundled: Option<&'static nmbrs_workload::catalog::BundledWorkload> =
6278        nmbrs_workload::catalog::lookup(reference)
6279            .or_else(|| ns_stem.as_deref().and_then(nmbrs_workload::catalog::lookup))
6280            .or_else(|| nmbrs_workload::catalog::lookup(stem));
6281
6282    let mut names: Vec<String> = Vec::new();
6283    if let Some(p) = &origin_file {
6284        names.push(format!("file {p} (beside the referring document)"));
6285    }
6286    if let Some(p) = &cwd_file {
6287        names.push(format!("local file {p}"));
6288    }
6289    if let Some(b) = bundled {
6290        names.push(format!("bundled workload `{}`", b.name));
6291    }
6292
6293    if names.len() > 1 {
6294        crate::observer::log_tagged(
6295            crate::observer::LogLevel::Warn,
6296            crate::observer::EventTag::in_flight(crate::observer::EventCategory::Resolution),
6297            &format!(
6298                "resolve: reference '{reference}' matches multiple resources — {} — \
6299             using the nearest ({}). Same-named resources in multiple places \
6300             invite confusion: prefer a unique name, or pin the intent with a \
6301             `./` path / full catalog name.",
6302                names.join(" AND "),
6303                names[0]
6304            ),
6305        );
6306    }
6307
6308    if let Some(p) = origin_file {
6309        return Ok(ResolvedWorkload::Path(p));
6310    }
6311    if let Some(p) = cwd_file {
6312        return Ok(ResolvedWorkload::Path(p));
6313    }
6314    if let Some(b) = bundled {
6315        return Ok(ResolvedWorkload::Bundled(b));
6316    }
6317    Err(format!(
6318        "workload not found: '{reference}'. Not a local file, and no bundled \
6319         workload by that name — `nmbrs describe workloads` lists what this \
6320         binary carries.{}",
6321        nmbrs_workload::suggest::did_you_mean(&nmbrs_workload::suggest::suggest_workloads(
6322            reference
6323        )),
6324    ))
6325}
6326
6327/// Canonicalize a workload file path for identity comparison;
6328/// bundled names pass through unchanged (they contain no path
6329/// separators that resolve).
6330fn canonical_identity(reference: &str) -> String {
6331    std::fs::canonicalize(reference)
6332        .map(|p| p.display().to_string())
6333        .unwrap_or_else(|_| reference.to_string())
6334}
6335
6336/// SRD-106 Part 3 — light pre-read of the workload's merged YAML
6337/// for the top-level `stick_session:` flag. Runs BEFORE session
6338/// construction (the full workload parse happens after the session
6339/// exists, so it cannot inform session resolution). Resolution
6340/// mirrors the execution path — local file first, then the bundled
6341/// catalog — and `extends:` chains merge before the peek, so a
6342/// suite base declaring `stick_session: true` reaches derived
6343/// workloads. Any failure answers `None`; the full parse surfaces
6344/// the real error with proper context.
6345fn peek_stick_session(params: &HashMap<String, String>, args: &[String]) -> Option<bool> {
6346    if params.contains_key("op") {
6347        return None; // inline workloads carry no header
6348    }
6349    let workload_raw = params.get("workload").cloned().or_else(|| {
6350        args.iter()
6351            .find(|a| a.ends_with(".yaml") || a.ends_with(".yml"))
6352            .cloned()
6353    })?;
6354    // Pre-probe only (stick_session peek): resolution warnings
6355    // are dropped here — the authoritative load that follows
6356    // surfaces the identical warnings itself.
6357    let merged = match resolve_workload(&workload_raw).ok()? {
6358        ResolvedWorkload::Path(p) => {
6359            nmbrs_workload::extends::load_and_merge(std::path::Path::new(&p))
6360                .ok()?
6361                .0
6362        }
6363        ResolvedWorkload::Bundled(b) => nmbrs_workload::extends::load_and_merge_bundled(b).ok()?.0,
6364    };
6365    let doc: serde_yaml::Value = serde_yaml::from_str(&merged).ok()?;
6366    doc.get("stick_session")?.as_bool()
6367}
6368
6369/// Resolve a workload file path from a bare name.
6370/// Tries: as-is, with .yaml/.yml extension, then under workloads/.
6371/// SRD-85 resolution result: a local file path or a bundled
6372/// catalog entry.
6373pub enum ResolvedWorkload {
6374    Path(String),
6375    Bundled(&'static nmbrs_workload::catalog::BundledWorkload),
6376}
6377
6378/// Resolve a `workload=` value per SRD-85 nearest-first: local
6379/// files first (exact path, extension probing, cwd `workloads/`),
6380/// then the bundled catalog by exact name. A name that resolves
6381/// both ways FAVORS the logical filesystem location and logs a
6382/// warning naming both — shadowing is allowed but never silent.
6383/// `./`-prefixed paths pin the local reading without a warning.
6384pub fn resolve_workload(name: &str) -> Result<ResolvedWorkload, String> {
6385    let local = resolve_workload_file(name);
6386    let bundled = nmbrs_workload::catalog::lookup(name);
6387    match (local, bundled) {
6388        (Some(local_path), Some(b)) => {
6389            if !name.starts_with("./") && !name.starts_with("../") {
6390                crate::observer::log_tagged(
6391                    crate::observer::LogLevel::Warn,
6392                    crate::observer::EventTag::in_flight(
6393                        crate::observer::EventCategory::Resolution,
6394                    ),
6395                    &format!(
6396                        "resolve: workload '{name}' matches multiple resources — \
6397                     local file {local_path} AND bundled workload `{}` — using \
6398                     the local file (filesystem-first). Same-named resources in \
6399                     multiple places invite confusion: prefer a unique name, or \
6400                     pin the intent with a `./` path.",
6401                        b.name
6402                    ),
6403                );
6404            }
6405            Ok(ResolvedWorkload::Path(local_path))
6406        }
6407        (Some(local_path), None) => Ok(ResolvedWorkload::Path(local_path)),
6408        (None, Some(b)) => Ok(ResolvedWorkload::Bundled(b)),
6409        (None, None) => Err(format!(
6410            "workload not found: '{name}'. Not a local file, and no bundled \
6411             workload by that name — `nmbrs describe workloads` lists what \
6412             this binary carries.{}",
6413            nmbrs_workload::suggest::did_you_mean(&nmbrs_workload::suggest::suggest_workloads(
6414                name
6415            ),)
6416        )),
6417    }
6418}
6419
6420fn resolve_workload_file(name: &str) -> Option<String> {
6421    let p = std::path::Path::new(name);
6422    if p.exists() {
6423        return Some(name.to_string());
6424    }
6425
6426    // Already has yaml extension — no further search
6427    if name.ends_with(".yaml") || name.ends_with(".yml") {
6428        // Try under workloads/
6429        let under = format!("workloads/{name}");
6430        if std::path::Path::new(&under).exists() {
6431            return Some(under);
6432        }
6433        return None;
6434    }
6435
6436    // Try adding extensions
6437    for ext in [".yaml", ".yml"] {
6438        let with_ext = format!("{name}{ext}");
6439        if std::path::Path::new(&with_ext).exists() {
6440            return Some(with_ext);
6441        }
6442    }
6443
6444    // Try under workloads/
6445    for ext in ["", ".yaml", ".yml"] {
6446        let under = format!("workloads/{name}{ext}");
6447        if std::path::Path::new(&under).exists() {
6448            return Some(under);
6449        }
6450    }
6451
6452    None
6453}
6454
6455/// Normalize args: detect scenario shorthand where a bare word after
6456/// the workload file becomes `scenario=<name>`.
6457///
6458/// The auto-promotion has to skip the **values** of space-form
6459/// flags (`--session-path X`, `--readout Y`, etc.) — otherwise
6460/// the path or value gets misread as a scenario name and ends up
6461/// as `scenario=<path>`, which downstream code then materialises
6462/// as a literal directory at `<cwd>/scenario=<path>` (the
6463/// orphaned-dir bug we hit earlier). Use the same list
6464/// [`parse_params`] uses so the two surfaces agree on which
6465/// flags consume their next token.
6466pub fn normalize_args(args: &[String]) -> Vec<String> {
6467    // Spec-derived value-taking flags (installed at startup); the
6468    // session-flag fallback applies for library/test drivers.
6469    let value_flags = known_value_flags();
6470
6471    let mut result = Vec::new();
6472    let mut workload_seen = false;
6473    let mut scenario_set = false;
6474    let mut iter = args.iter().peekable();
6475    while let Some(arg) = iter.next() {
6476        // Pass through space-form flag + its value as a unit.
6477        // Equals-form (`--session-path=X`) is one token and
6478        // skips this branch.
6479        if value_flags.iter().any(|f| *f == arg) {
6480            result.push(arg.clone());
6481            if let Some(next) = iter.next() {
6482                result.push(next.clone());
6483            }
6484            continue;
6485        }
6486        if !workload_seen
6487            && (arg.ends_with(".yaml") || arg.ends_with(".yml") || arg.contains("workload="))
6488        {
6489            workload_seen = true;
6490            result.push(arg.clone());
6491        } else if workload_seen && !scenario_set && !arg.contains('=') && !arg.starts_with('-') {
6492            result.push(format!("scenario={arg}"));
6493            scenario_set = true;
6494        } else {
6495            result.push(arg.clone());
6496        }
6497    }
6498    result
6499}
6500
6501/// Bare flags accepted by the runner — these don't follow the
6502/// `key=value` shape but are otherwise recognized. Centralized
6503/// here so [`parse_params`] doesn't reject them and any consumer
6504/// can re-check the raw `args` for them.
6505const RECOGNIZED_BARE_FLAGS: &[&str] = &[
6506    "--strict",             // SRD-15 strict-mode toggle.
6507    "--resume-latest",      // SRD-44: resume from logs/latest.
6508    "--force-retry-failed", // SRD-44: prepend retry,warn to errors.
6509    "--refine",             // SRD-77: enable refine-mode skip-plan loading.
6510];
6511
6512/// Strip a single layer of matching outer quotes (single or
6513/// double) from a string slice. Idempotent for un-quoted input.
6514///
6515/// Per SRD 71 §"CLI parsing — quote elision": this lets wrapper
6516/// scripts forwarding `"$@"`, or `key="value"` constructions
6517/// that double-passed through a shell, parse the same as their
6518/// bare equivalents. Backtick and other quote-like characters
6519/// are deliberately not handled — they carry shell-evaluation
6520/// semantics that don't survive into our argv.
6521pub(crate) fn elide_outer_quotes(s: &str) -> &str {
6522    let bytes = s.as_bytes();
6523    if bytes.len() < 2 {
6524        return s;
6525    }
6526    let first = bytes[0];
6527    let last = bytes[bytes.len() - 1];
6528    if (first == b'\'' || first == b'"') && first == last {
6529        &s[1..s.len() - 1]
6530    } else {
6531        s
6532    }
6533}
6534
6535/// The error for a CLI argument whose key is no known parameter. `parse_params`
6536/// strips leading dashes, so `--x=1` and `x=1` both arrive as the key `x`; the
6537/// message names the argument as the operator wrote it. A dashed argument is
6538/// reported as a flag and matched against the known flags (a retired spelling
6539/// names its replacement); a bare `key=value` is matched against the known
6540/// parameters.
6541fn unrecognized_param_error(args: &[String], key: &str, known_params: &[&str]) -> String {
6542    let dashed = args.iter().find_map(|a| {
6543        let a = elide_outer_quotes(a);
6544        let name = a.split('=').next().unwrap_or(a);
6545        (name.starts_with('-') && name.trim_start_matches('-') == key).then_some(name)
6546    });
6547    match dashed {
6548        Some(flag) => {
6549            let suggestion = crate::session::retired_flag_replacement(flag).or_else(|| {
6550                let flags = known_flags();
6551                crate::suggest::closest_match(flag, flags.iter().copied())
6552            });
6553            match suggestion {
6554                Some(s) => format!("unrecognized flag '{flag}'. Did you mean '{s}'?"),
6555                None => format!("unrecognized flag '{flag}'"),
6556            }
6557        }
6558        None => match crate::suggest::closest_match(key, known_params.iter().copied()) {
6559            Some(s) => format!("unrecognized parameter '{key}='. Did you mean '{s}='?"),
6560            None => format!("unrecognized parameter '{key}='"),
6561        },
6562    }
6563}
6564
6565/// Flags consumed by `crate::session::resolve_session_dir` at startup.
6566/// They appear in raw `args` but shouldn't reach the per-key params map.
6567/// Both equals-form (`--session-path=/path`) and space-form
6568/// (`--session-path /path`) are recognised; the space-form value is
6569/// silently absorbed. Shared by [`parse_params`] and
6570/// [`detect_conflicting_duplicate_params`] so they treat these args
6571/// identically.
6572const SESSION_DIR_FLAGS: &[&str] = &[
6573    // Umbrella flag (kv-list).
6574    "--session",
6575    // Per-key long-form flags.
6576    "--session-name",
6577    "--session-path",
6578    "--session-reuse",
6579    "--session-keep",
6580    "--session-shelflife",
6581    // SRD-63 §8: `--readout=<body>` overrides the workload's
6582    // `on_update` binding for the run. Resolved by
6583    // `crate::session::resolve_flag` at runner-init; consumed here so
6584    // the value doesn't bleed into the workload params map.
6585    "--readout",
6586];
6587
6588/// Reject a `key=value` run param supplied more than once with
6589/// *conflicting* values. These params collapse into a map (last value
6590/// wins — see [`parse_params`]), which silently discards an earlier
6591/// value: e.g. `scenario=reset scenario=idx_sweep` drops `reset` and
6592/// runs `idx_sweep`. A repeat with an IDENTICAL value is harmless and
6593/// allowed (re-passing the same value shouldn't break a script); a
6594/// conflicting repeat is an ambiguous instruction, so it's rejected and
6595/// surfaced rather than silently last-wins ("Never Ignore Silently").
6596///
6597/// Mirrors `parse_params`'s arg walk: session-dir flags (own resolver)
6598/// and dotted phase-scoped overrides (`<phase>.<param>=`, a separate
6599/// namespace) are skipped, and the same quote elision is applied so
6600/// `scenario=x` and `scenario='x'` compare equal.
6601pub fn detect_conflicting_duplicate_params(args: &[String]) -> Result<(), String> {
6602    let mut seen: HashMap<String, String> = HashMap::new();
6603    let mut iter = args.iter().peekable();
6604    while let Some(arg) = iter.next() {
6605        // Session-dir flags: consumed by the startup hook, absorb the
6606        // space-form value so it isn't mistaken for a param.
6607        if known_value_flags()
6608            .iter()
6609            .any(|p| arg == p || arg.starts_with(&format!("{p}=")))
6610        {
6611            if !arg.contains('=') {
6612                let _consumed = iter.next();
6613            }
6614            continue;
6615        }
6616        let unquoted = elide_outer_quotes(arg.as_str());
6617        let stripped = unquoted.trim_start_matches('-');
6618        let Some(eq_pos) = stripped.find('=') else {
6619            continue;
6620        };
6621        let key = stripped[..eq_pos].to_string();
6622        // Dotted (non-path) keys are SRD-71 phase-scoped overrides — a
6623        // separate namespace — skipped here as in `parse_params`.
6624        if key.contains('.') && !key.contains('/') && !key.contains('\\') {
6625            continue;
6626        }
6627        let value = elide_outer_quotes(&stripped[eq_pos + 1..]).to_string();
6628        match seen.get(&key) {
6629            Some(prev) if *prev != value => {
6630                return Err(format!(
6631                    "parameter '{key}' specified more than once with conflicting \
6632                     values ('{prev}' and '{value}') — pass it exactly once"
6633                ));
6634            }
6635            Some(_) => {} // identical repeat — harmless, allow.
6636            None => {
6637                seen.insert(key, value);
6638            }
6639        }
6640    }
6641    Ok(())
6642}
6643
6644/// Parse `key=value` pairs from command line args.
6645///
6646/// Quote handling (SRD 71): if the whole arg or just the value
6647/// portion is wrapped in matching `'…'` / `"…"` quotes, those
6648/// quotes are stripped. So `cursor=0..53%`, `cursor='0..53%'`,
6649/// `cursor="0..53%"`, `'cursor=0..53%'`, and `"cursor=0..53%"`
6650/// all parse to the same `(name="cursor", value="0..53%")`
6651/// pair. The first `=` still splits name from value, so values
6652/// containing `=` retain everything after the first split.
6653pub fn parse_params(args: &[String]) -> HashMap<String, String> {
6654    let mut params = HashMap::new();
6655    let mut iter = args.iter().peekable();
6656    while let Some(arg) = iter.next() {
6657        // Session-dir flags (consumed by the startup hook,
6658        // not stored in params).
6659        if known_value_flags()
6660            .iter()
6661            .any(|p| arg == p || arg.starts_with(&format!("{p}=")))
6662        {
6663            if !arg.contains('=') {
6664                let _consumed = iter.next();
6665            }
6666            continue;
6667        }
6668
6669        // Quote elision (SRD 71): strip matching outer quotes
6670        // from the whole arg first — handles `'key=value'` and
6671        // `"key=value"` — then again from the value portion
6672        // after the `=` split — handles `key='value'` and
6673        // `key="value"`.
6674        let unquoted = elide_outer_quotes(arg.as_str());
6675        // Strip leading dashes: --dryrun=phase,wiring → dryrun=phase,wiring
6676        let stripped = unquoted.trim_start_matches('-');
6677        if let Some(eq_pos) = stripped.find('=') {
6678            let key = stripped[..eq_pos].to_string();
6679            // Dotted keys (without path separators) are SRD-71
6680            // phase-scoped overrides (`<phase-pattern>.<param>=`),
6681            // parsed by `crate::phase_params::parse_overrides` —
6682            // not workload params.
6683            if key.contains('.') && !key.contains('/') && !key.contains('\\') {
6684                continue;
6685            }
6686            let value = elide_outer_quotes(&stripped[eq_pos + 1..]).to_string();
6687            params.insert(key, value);
6688        } else if arg.ends_with(".yaml") || arg.ends_with(".yml") {
6689            // Workload file path — handled elsewhere
6690        } else if is_recognized_bare_flag(arg.as_str()) || arg.starts_with("--polydat-lib=") {
6691            // Bare runner flag — consumed elsewhere via `args`
6692            // scan (e.g. `--strict`, `--polydat-lib=path`).
6693        } else {
6694            crate::diag!(
6695                crate::observer::LogLevel::Error,
6696                "error: unrecognized argument '{arg}'. Expected key=value format."
6697            );
6698            std::process::exit(1);
6699        }
6700    }
6701    params
6702}
6703
6704/// Overlay CLI `key=value` params onto a base set, CLI winning on
6705/// conflict. The single precedence rule for the whole run — applied to
6706/// the session-tier effective params ([`effective_params`]) and to the
6707/// execution's workload params identically, so "CLI overrides the
6708/// workload" means the same thing everywhere.
6709fn overlay_cli_params(
6710    mut base: HashMap<String, String>,
6711    cli: &HashMap<String, String>,
6712) -> HashMap<String, String> {
6713    for (k, v) in cli {
6714        // Coerce the CLI value to the type already inferred for this key
6715        // (the declared default, resolved by `parse_workload`), so a
6716        // suffixed override like `max_size=10m` re-applies as a number
6717        // rather than overwriting the coerced value with raw text. Keys
6718        // with no declared default (ad-hoc CLI params) pass through.
6719        let coerced = match base.get(k) {
6720            Some(existing) => nmbrs_workload::magnitude::coerce_param_override(existing, v),
6721            None => v.clone(),
6722        };
6723        base.insert(k.clone(), coerced);
6724    }
6725    base
6726}
6727
6728/// The run's **effective parameters**: the workload's declared top-level
6729/// `params:` (extends-merged) as the base, with CLI `key=value` args
6730/// overlaid on top (CLI wins). This is the single consolidated param set —
6731/// the same one whether a setting is declared in the workload or passed on
6732/// the command line — used for session-tier services (metrics cadence,
6733/// push reporters, per-instance metrics) and console-ownership detection
6734/// alike. The per-execution path reaches the same result by overlaying CLI
6735/// onto the fully-parsed `workload.params` (see `run_execution`).
6736///
6737/// The workload reference is taken from `workload=` or a bare `.yaml`/`.yml`
6738/// positional; an unresolvable/absent workload contributes no base params
6739/// (the real load error, if any, surfaces later in the execution).
6740pub fn effective_params(args: &[String]) -> HashMap<String, String> {
6741    let cli = parse_params(args);
6742    let workload_ref = cli.get("workload").cloned().or_else(|| {
6743        args.iter()
6744            .find(|a| (a.ends_with(".yaml") || a.ends_with(".yml")) && !a.contains('='))
6745            .cloned()
6746    });
6747    let base = workload_ref
6748        .as_deref()
6749        .and_then(nmbrs_workload::verify::declared_params)
6750        .unwrap_or_default();
6751    overlay_cli_params(base, &cli)
6752}
6753
6754/// Param keys that configure the **session-tier** services — one value per
6755/// session, shared by every execution under it. Executions that declare
6756/// different values for any of these cannot share a session; a multi-
6757/// execution harness must group by them and set up one session per group
6758/// (see [`session_param_signature`]). `metrics_cadence` is the load-bearing
6759/// case: it fixes the cadence the optimizer settle detector samples, so
6760/// workloads wanting a sub-second cadence must run in their own session.
6761pub const SESSION_PARAMS: &[&str] = &["metrics_cadence"];
6762
6763/// The session-grouping signature for a workload reference: its declared
6764/// values (following `extends:`) for the [`SESSION_PARAMS`], sorted.
6765/// Workloads with equal signatures can share one session; differing ones
6766/// must not. Empty signature = "the default session is fine".
6767pub fn session_param_signature(reference: &str) -> Vec<(String, String)> {
6768    let declared = nmbrs_workload::verify::declared_params(reference).unwrap_or_default();
6769    let mut sig: Vec<(String, String)> = SESSION_PARAMS
6770        .iter()
6771        .filter_map(|k| declared.get(*k).map(|v| ((*k).to_string(), v.clone())))
6772        .collect();
6773    sig.sort();
6774    sig
6775}
6776
6777/// Resolve the metrics base interval + cadence ladder from the run's
6778/// effective params. A `metrics_cadence` param (workload or CLI, e.g.
6779/// `100ms` / `200ms`) sets the FINEST cadence — the pulse the SRD-86
6780/// optimizer settle detector samples — and the scheduler base interval, so
6781/// a windowed objective settles in a fraction of the default 1 s-cadence
6782/// wall-clock. A standard coarse ladder (1s/10s/30s/1m/5m) is layered above
6783/// it (keeping a 1 s rung bounds the fan-in from a sub-second floor). Absent
6784/// the param, this is the unchanged default: a 1 s base with the observer's
6785/// declared cadences (or [`Cadences::defaults`]).
6786fn resolve_cadence_config(
6787    params: &HashMap<String, String>,
6788    observer: &Arc<dyn crate::observer::RunObserver>,
6789) -> Result<(std::time::Duration, nmbrs_metrics::cadence::Cadences), String> {
6790    use std::time::Duration;
6791    let Some(raw) = params.get("metrics_cadence") else {
6792        let cadences = observer
6793            .cadences()
6794            .unwrap_or_else(nmbrs_metrics::cadence::Cadences::defaults);
6795        return Ok((Duration::from_secs(1), cadences));
6796    };
6797    let floor = nmbrs_metrics::cadence::parse_duration(raw).ok_or_else(|| {
6798        format!("metrics_cadence: invalid duration `{raw}` (use e.g. `100ms`, `200ms`, `1s`)")
6799    })?;
6800    if floor.is_zero() {
6801        return Err("metrics_cadence: must be greater than zero".to_string());
6802    }
6803    let mut layers = vec![floor];
6804    for secs in [1u64, 10, 30, 60, 300] {
6805        let d = Duration::from_secs(secs);
6806        if d > floor {
6807            layers.push(d);
6808        }
6809    }
6810    let cadences = nmbrs_metrics::cadence::Cadences::new(&layers)
6811        .map_err(|e| format!("metrics_cadence `{raw}`: cannot build a cadence ladder: {e:?}"))?;
6812    Ok((floor, cadences))
6813}
6814
6815/// Collect every occurrence of a repeatable flag (e.g.
6816/// `--trace=<spec>` or `trace=<spec>`) from a raw arg list.
6817/// Returns the values in order of appearance — `parse_params`
6818/// collapses repeats into a HashMap, so this is the escape
6819/// hatch for repeatable args.
6820///
6821/// Accepts both `--name=value` and `name=value` shapes for
6822/// symmetry with the rest of nmbrs's arg surface.
6823pub fn collect_repeated_flag(args: &[String], name: &str) -> Vec<String> {
6824    let mut out = Vec::new();
6825    let mut iter = args.iter().peekable();
6826    let long_eq = format!("--{name}=");
6827    let bare_eq = format!("{name}=");
6828    while let Some(arg) = iter.next() {
6829        let unquoted = elide_outer_quotes(arg.as_str());
6830        if let Some(v) = unquoted.strip_prefix(&long_eq) {
6831            out.push(elide_outer_quotes(v).to_string());
6832        } else if let Some(v) = unquoted.strip_prefix(&bare_eq) {
6833            out.push(elide_outer_quotes(v).to_string());
6834        } else if unquoted == format!("--{name}")
6835            && let Some(v) = iter.next()
6836        {
6837            out.push(elide_outer_quotes(v.as_str()).to_string());
6838        }
6839    }
6840    out
6841}
6842
6843/// Parse a cycle count that may have suffixes: K, M, B.
6844pub fn parse_count(s: &str) -> Option<u64> {
6845    let s = s.trim().to_uppercase();
6846    if let Some(n) = s.strip_suffix('K') {
6847        n.trim().parse::<u64>().ok().map(|v| v * 1_000)
6848    } else if let Some(n) = s.strip_suffix('M') {
6849        n.trim().parse::<u64>().ok().map(|v| v * 1_000_000)
6850    } else if let Some(n) = s.strip_suffix('B') {
6851        n.trim().parse::<u64>().ok().map(|v| v * 1_000_000_000)
6852    } else {
6853        s.parse().ok()
6854    }
6855}
6856
6857// =========================================================================
6858// Polydat Scope Composition (sysref 16)
6859// =========================================================================
6860
6861// `ManifestEntry` and `extract_manifest` now live in
6862// `polydat::kernel`. Re-exported here so existing
6863// `crate::runner::extract_manifest` / `ManifestEntry` callers
6864// keep working — pure compatibility shim.
6865pub use polydat::kernel::{ManifestEntry, extract_manifest};
6866
6867#[cfg(test)]
6868mod tests {
6869    use super::*;
6870
6871    // ── parse_params quote elision (SRD 71) ──────────────────
6872
6873    fn pp(args: &[&str]) -> HashMap<String, String> {
6874        parse_params(&args.iter().map(|s| s.to_string()).collect::<Vec<_>>())
6875    }
6876
6877    #[test]
6878    fn parse_params_bare_unchanged() {
6879        let m = pp(&["cursor=0..53%"]);
6880        assert_eq!(m.get("cursor").map(String::as_str), Some("0..53%"));
6881    }
6882
6883    #[test]
6884    fn parse_params_value_single_quoted_stripped() {
6885        let m = pp(&["cursor='0..53%'"]);
6886        assert_eq!(m.get("cursor").map(String::as_str), Some("0..53%"));
6887    }
6888
6889    #[test]
6890    fn parse_params_value_double_quoted_stripped() {
6891        let m = pp(&["cursor=\"0..53%\""]);
6892        assert_eq!(m.get("cursor").map(String::as_str), Some("0..53%"));
6893    }
6894
6895    #[test]
6896    fn parse_params_whole_arg_single_quoted_stripped() {
6897        let m = pp(&["'cursor=0..53%'"]);
6898        assert_eq!(m.get("cursor").map(String::as_str), Some("0..53%"));
6899    }
6900
6901    #[test]
6902    fn parse_params_whole_arg_double_quoted_stripped() {
6903        let m = pp(&["\"cursor=0..53%\""]);
6904        assert_eq!(m.get("cursor").map(String::as_str), Some("0..53%"));
6905    }
6906
6907    #[test]
6908    fn parse_params_bracket_value_with_quotes() {
6909        let m = pp(&["cursor='[0..53%)'"]);
6910        assert_eq!(m.get("cursor").map(String::as_str), Some("[0..53%)"));
6911    }
6912
6913    #[test]
6914    fn parse_params_mismatched_quotes_not_stripped() {
6915        let m = pp(&["cursor='0..53%\""]);
6916        // First char `'`, last char `"` — no matching pair.
6917        assert_eq!(m.get("cursor").map(String::as_str), Some("'0..53%\""));
6918    }
6919
6920    fn dup(args: &[&str]) -> Result<(), String> {
6921        let owned: Vec<String> = args.iter().map(|s| s.to_string()).collect();
6922        detect_conflicting_duplicate_params(&owned)
6923    }
6924
6925    #[test]
6926    fn duplicate_conflicting_scenario_is_rejected() {
6927        let err = dup(&["workload=x.yaml", "scenario=reset", "scenario=idx_sweep"]).unwrap_err();
6928        assert!(
6929            err.contains("scenario") && err.contains("reset") && err.contains("idx_sweep"),
6930            "expected a conflicting-duplicate error naming both values, got: {err}"
6931        );
6932    }
6933
6934    #[test]
6935    fn duplicate_identical_value_is_allowed() {
6936        // Re-passing the same value is harmless.
6937        assert!(dup(&["scenario=idx_sweep", "scenario=idx_sweep"]).is_ok());
6938    }
6939
6940    #[test]
6941    fn distinct_params_are_allowed() {
6942        assert!(dup(&["workload=x.yaml", "scenario=reset", "cycles=10", "host=h"]).is_ok());
6943    }
6944
6945    #[test]
6946    fn conflicting_duplicate_any_param_is_rejected() {
6947        // The guard is general — not just `scenario=`.
6948        assert!(dup(&["cycles=10", "cycles=20"]).is_err());
6949    }
6950
6951    #[test]
6952    fn duplicate_check_elides_quotes_before_comparing() {
6953        // `scenario=reset` and `scenario='reset'` are the SAME value.
6954        assert!(dup(&["scenario=reset", "scenario='reset'"]).is_ok());
6955        // …but genuinely different quoted values still conflict.
6956        assert!(dup(&["scenario='reset'", "scenario=\"idx_sweep\""]).is_err());
6957    }
6958
6959    /// A dashed argument is reported as the flag the operator wrote, and a
6960    /// retired spelling names its replacement rather than whatever edit
6961    /// distance finds nearest. A bare `key=value` stays a parameter.
6962    #[test]
6963    fn unrecognized_argument_error_matches_its_shape() {
6964        let args = vec!["--sessions-max=5".to_string()];
6965        assert_eq!(
6966            unrecognized_param_error(&args, "sessions-max", &["cycles"]),
6967            "unrecognized flag '--sessions-max'. Did you mean '--session-keep'?"
6968        );
6969        let args = vec!["cyclse=5".to_string()];
6970        assert_eq!(
6971            unrecognized_param_error(&args, "cyclse", &["cycles"]),
6972            "unrecognized parameter 'cyclse='. Did you mean 'cycles='?"
6973        );
6974    }
6975
6976    #[test]
6977    fn duplicate_check_skips_session_flags_and_dotted_overrides() {
6978        // Session-dir flags are consumed by their own resolver; dotted
6979        // keys are phase-scoped overrides — neither participates here.
6980        assert!(dup(&["--session-path", "/a", "--session-path", "/b"]).is_ok());
6981        assert!(dup(&["phase1.cycles=10", "phase2.cycles=20"]).is_ok());
6982    }
6983
6984    #[test]
6985    fn parse_params_equals_in_value_preserved() {
6986        // `key='a=b'` → name=`key`, value=`a=b`.
6987        let m = pp(&["key='a=b'"]);
6988        assert_eq!(m.get("key").map(String::as_str), Some("a=b"));
6989    }
6990
6991    #[test]
6992    fn parse_params_multiple_params_independent() {
6993        let m = pp(&["dataset=example", "cursor='0..1%'", "concurrency=\"100\""]);
6994        assert_eq!(m.get("dataset").map(String::as_str), Some("example"));
6995        assert_eq!(m.get("cursor").map(String::as_str), Some("0..1%"));
6996        assert_eq!(m.get("concurrency").map(String::as_str), Some("100"));
6997    }
6998
6999    // ── Polydat binding-LHS-name scanner ──────────────────────────
7000
7001    fn scan_to_set(src: &str) -> std::collections::HashSet<String> {
7002        let mut out = std::collections::HashSet::new();
7003        scan_polydat_binding_lhs(&mut out, src);
7004        out
7005    }
7006
7007    // ── scan_polydat_braced_refs: invalid `{...}` outside strings ─
7008
7009    #[test]
7010    fn polydat_brace_guard_allows_valid_if_block() {
7011        // Block-form conditional selection uses braces legitimately. The guard must
7012        // not flag it, because the source parses.
7013        let src = "extern segments: u64 = 0\nmean := if segments > 0 { 100 } else { 0 }\n";
7014        let parses = polydat::dsl::lexer::lex(src)
7015            .ok()
7016            .and_then(|t| polydat::dsl::parser::parse(t).ok())
7017            .is_some();
7018        assert!(parses, "if-block source must parse: {src}");
7019    }
7020
7021    #[test]
7022    fn polydat_brace_guard_still_catches_stray_placeholder() {
7023        // A YAML placeholder in expression position does NOT parse, so the guard
7024        // still fires and still names the placeholder.
7025        let src = "const passes := multiples_at_least({min_query_cycles}, base)\n";
7026        let parses = polydat::dsl::lexer::lex(src)
7027            .ok()
7028            .and_then(|t| polydat::dsl::parser::parse(t).ok())
7029            .is_some();
7030        assert!(!parses, "stray placeholder must fail to parse");
7031        let refs = scan_polydat_braced_refs(src);
7032        assert!(refs.iter().any(|r| r == "min_query_cycles"), "got {refs:?}");
7033    }
7034
7035    #[test]
7036    fn scan_polydat_braced_refs_flags_expression_position_braces() {
7037        // The user's case: `{name}` outside any string literal,
7038        // sitting where Polydat expects an expression. Always invalid.
7039        let refs = scan_polydat_braced_refs(
7040            "const passes := multiples_at_least({min_query_cycles}, base)\n",
7041        );
7042        assert_eq!(refs, vec!["min_query_cycles".to_string()]);
7043    }
7044
7045    #[test]
7046    fn scan_polydat_braced_refs_ignores_braces_inside_double_quotes() {
7047        // Inside `"…"` braces are valid — either workload-param
7048        // interp (if the runtime expanded the string earlier) or
7049        // Polydat string interpolation (parser turns it into printf).
7050        // Either way, scan_polydat_braced_refs must NOT flag them.
7051        let refs = scan_polydat_braced_refs(
7052            "const prebuffered := dataset_prebuffer(\"{dataset}:{profile}\")\n",
7053        );
7054        assert!(
7055            refs.is_empty(),
7056            "must not flag `{{dataset}}` / `{{profile}}` inside string \
7057             literal — string interpolation handles them, got {refs:?}"
7058        );
7059    }
7060
7061    #[test]
7062    fn scan_polydat_braced_refs_ignores_braces_inside_single_quotes() {
7063        let refs = scan_polydat_braced_refs("tag := assert_eq(actual, '{expected}')\n");
7064        assert!(
7065            refs.is_empty(),
7066            "single-quoted strings get the same treatment: {refs:?}"
7067        );
7068    }
7069
7070    #[test]
7071    fn scan_polydat_braced_refs_handles_escaped_quotes_in_strings() {
7072        // `"foo \"with brace {x}\" bar"` — the inner `{x}` is
7073        // inside a string the whole way through; backslash-escape
7074        // must not be treated as the end of the string.
7075        let refs = scan_polydat_braced_refs("x := concat(\"prefix \\\"{embedded}\\\" suffix\")\n");
7076        assert!(refs.is_empty(), "escaped quotes inside strings: {refs:?}");
7077    }
7078
7079    #[test]
7080    fn scan_polydat_braced_refs_ignores_comments() {
7081        let refs = scan_polydat_braced_refs(
7082            "# this is a comment with {fake} placeholder\n\
7083             const real := 1\n",
7084        );
7085        assert!(
7086            refs.is_empty(),
7087            "`{{fake}}` inside a comment must not be flagged: {refs:?}"
7088        );
7089    }
7090
7091    #[test]
7092    fn scan_polydat_braced_refs_catches_multiple_invalid_braces() {
7093        let refs = scan_polydat_braced_refs(
7094            "a := foo({x}, {y})\n\
7095             b := bar({z})\n",
7096        );
7097        // Order is source order; uniqueness isn't enforced here
7098        // (the validator caller dedups before reporting).
7099        assert_eq!(
7100            refs,
7101            vec!["x".to_string(), "y".to_string(), "z".to_string(),]
7102        );
7103    }
7104
7105    #[test]
7106    fn scan_polydat_braced_refs_handles_mixed_string_and_expression_braces() {
7107        // `{inside}` is in a string (OK); `{outside}` is in
7108        // expression position (flagged).
7109        let refs = scan_polydat_braced_refs("x := concat(\"foo {inside}\", {outside})\n");
7110        assert_eq!(refs, vec!["outside".to_string()]);
7111    }
7112
7113    // ── Polydat binding-LHS-name scanner ──────────────────────────
7114
7115    #[test]
7116    fn scan_polydat_binding_lhs_handles_typed_cell_form() {
7117        // `shared name: type := default` — the type annotation sits
7118        // between the name and the assignment; the scanner must still
7119        // collect the name (undeclared-placeholder false-positive fix).
7120        let mut out = std::collections::HashSet::new();
7121        scan_polydat_binding_lhs(
7122            &mut out,
7123            "shared sstables: u64 := 0\nshared measured: f64 := 1.0\nplain := 2\n",
7124        );
7125        assert!(out.contains("sstables"), "{out:?}");
7126        assert!(out.contains("measured"), "{out:?}");
7127        assert!(out.contains("plain"), "{out:?}");
7128    }
7129
7130    #[test]
7131    fn scan_polydat_binding_lhs_handles_tuple_destructure() {
7132        // Multi-output stdlib calls bind multiple names via
7133        // tuple destructure: `(a, b, c) := func(...)`. The
7134        // scanner must register every name on the LHS so the
7135        // placeholder validator doesn't false-flag downstream
7136        // `{a}` / `{b}` references.
7137        let names = scan_to_set("(y, mo, d, h, mi, s, ms) := date_components(0)\n");
7138        for expected in ["y", "mo", "d", "h", "mi", "s", "ms"] {
7139            assert!(
7140                names.contains(expected),
7141                "tuple-LHS scanner missed `{expected}` — got {names:?}"
7142            );
7143        }
7144    }
7145
7146    #[test]
7147    fn scan_polydat_binding_lhs_finds_all_recognised_shapes() {
7148        // Validates the wire-name scanner picks up every shape:
7149        // init / cursor / shared / final modifier-prefixed
7150        // bindings, plus bare `NAME := …` assignments.
7151        let names = scan_to_set(
7152            "const prebuffered := dataset_prebuffer(\"foo\")\n\
7153             cursor q = range(0, 100)\n\
7154             query_vector := query_vector_at(prebuffered, q)\n\
7155             shared query_passes := set_or_get(query_passes, 7)\n\
7156             const tag := \"label_00\"\n",
7157        );
7158        for expected in ["prebuffered", "q", "query_vector", "query_passes", "tag"] {
7159            assert!(
7160                names.contains(expected),
7161                "scanner missed `{expected}` — got {names:?}"
7162            );
7163        }
7164    }
7165
7166    #[test]
7167    fn scan_polydat_binding_lhs_skips_comments_and_blank_lines() {
7168        let names = scan_to_set(
7169            "# comment\n\
7170             \n\
7171             const real_binding := 1\n\
7172             # another comment\n",
7173        );
7174        assert_eq!(names.len(), 1);
7175        assert!(names.contains("real_binding"));
7176    }
7177
7178    #[test]
7179    fn scan_polydat_binding_lhs_ignores_non_binding_lines() {
7180        // Expression-call statements and continuation lines must
7181        // not introduce phantom wires.
7182        let names = scan_to_set(
7183            "foo(1, 2)\n\
7184             bar.baz\n\
7185             const real := 1\n",
7186        );
7187        assert_eq!(names.len(), 1);
7188        assert!(names.contains("real"));
7189    }
7190
7191    #[test]
7192    fn scan_polydat_binding_lhs_picks_up_input_decl_bare() {
7193        let names = scan_to_set("input cycle: u64\nx := hash(cycle)\n");
7194        assert!(names.contains("cycle"));
7195        assert!(names.contains("x"));
7196    }
7197
7198    #[test]
7199    fn scan_polydat_binding_lhs_picks_up_input_decl_untyped() {
7200        let names = scan_to_set("input cycle\n");
7201        assert!(names.contains("cycle"));
7202    }
7203
7204    #[test]
7205    fn scan_polydat_binding_lhs_picks_up_input_decl_tuple() {
7206        let names = scan_to_set("input (cycle: u64, q: f64)\n");
7207        assert!(names.contains("cycle"));
7208        assert!(names.contains("q"));
7209    }
7210
7211    #[test]
7212    fn scan_polydat_binding_lhs_picks_up_extern_decl() {
7213        // `extern name: type [= default]` declares a wire just like
7214        // `input` — a same-op capture target referenced via `{name}`
7215        // must not trip the undeclared-placeholder guard.
7216        let names = scan_to_set(
7217            "extern active_compactions: u64 = 0\n\
7218             extern completion_ratio: f64 = 0.0\n\
7219             extern (a: u64, b: f64)\n",
7220        );
7221        assert!(names.contains("active_compactions"));
7222        assert!(names.contains("completion_ratio"));
7223        assert!(names.contains("a"));
7224        assert!(names.contains("b"));
7225    }
7226
7227    #[test]
7228    fn parse_dryrun_controls_sets_list_flag() {
7229        let cfg = DiagnosticConfig::parse("controls");
7230        assert!(cfg.list_controls);
7231        // Implies phase depth so the runner exits before any
7232        // cycle-time work.
7233        assert_eq!(cfg.depth, ExecDepth::Phase);
7234    }
7235
7236    #[test]
7237    fn parse_dryrun_controls_combines_with_other_flags() {
7238        let cfg = DiagnosticConfig::parse("controls,labels");
7239        assert!(cfg.list_controls);
7240        assert!(cfg.show_labels);
7241    }
7242
7243    #[test]
7244    fn parse_dryrun_unknown_flag_does_not_set_controls() {
7245        let cfg = DiagnosticConfig::parse("phase,bogus");
7246        assert!(!cfg.list_controls);
7247    }
7248
7249    // ── SRD-13d Phase 7 — `dryrun=op` ──
7250
7251    #[test]
7252    fn parse_dryrun_op_sets_op_depth() {
7253        let cfg = DiagnosticConfig::parse("op");
7254        assert_eq!(cfg.depth, ExecDepth::Op);
7255    }
7256
7257    #[test]
7258    fn parse_dryrun_phase_still_sets_phase_depth() {
7259        let cfg = DiagnosticConfig::parse("phase");
7260        assert_eq!(cfg.depth, ExecDepth::Phase);
7261    }
7262
7263    #[test]
7264    fn parse_dryrun_cycle_still_sets_cycle_depth() {
7265        let cfg = DiagnosticConfig::parse("cycle");
7266        assert_eq!(cfg.depth, ExecDepth::Cycle);
7267    }
7268
7269    #[test]
7270    fn parse_dryrun_op_combines_with_wiring_flag() {
7271        let cfg = DiagnosticConfig::parse("op,wiring");
7272        assert_eq!(cfg.depth, ExecDepth::Op);
7273        assert!(cfg.show_wiring);
7274    }
7275
7276    #[test]
7277    fn parse_dryrun_wiring_alone_bumps_depth_to_op() {
7278        // `wiring` needs depth >= Op for kernels to exist; a bare
7279        // `dryrun=wiring` must auto-bump so it produces output
7280        // instead of silently doing nothing at depth=Phase.
7281        let cfg = DiagnosticConfig::parse("wiring");
7282        assert_eq!(cfg.depth, ExecDepth::Op);
7283        assert!(cfg.show_wiring);
7284    }
7285
7286    #[test]
7287    fn parse_dryrun_wiring_does_not_override_explicit_depth() {
7288        // Explicit phase depth wins; `wiring` is then a no-op
7289        // (no kernels to render at phase depth) — the user gets
7290        // what they asked for rather than a silent bump.
7291        let cfg = DiagnosticConfig::parse("phase,wiring");
7292        assert_eq!(cfg.depth, ExecDepth::Phase);
7293        assert!(cfg.show_wiring);
7294    }
7295
7296    #[test]
7297    fn exec_depth_ordering_matches_srd_13d() {
7298        // `Phase` is the shallowest stop, `Full` is the deepest;
7299        // `Op` sits between `Phase` and `Cycle`. Depth-gating
7300        // sites read this ordering as `< Cycle` ⇒ "skip cycles".
7301        assert!(ExecDepth::Phase < ExecDepth::Op);
7302        assert!(ExecDepth::Op < ExecDepth::Cycle);
7303        assert!(ExecDepth::Cycle < ExecDepth::Full);
7304        // The transitive should hold (it would be a derive
7305        // bug if it didn't, but assert it for documentation).
7306        assert!(ExecDepth::Phase < ExecDepth::Cycle);
7307        assert!(ExecDepth::Op < ExecDepth::Full);
7308    }
7309
7310    #[test]
7311    fn exec_depth_phase_and_op_short_circuit_before_cycles() {
7312        // The executor's per-phase early-exit fires when
7313        // `depth < Cycle`. Both Phase and Op satisfy that;
7314        // Cycle and Full do not.
7315        assert!(ExecDepth::Phase < ExecDepth::Cycle);
7316        assert!(ExecDepth::Op < ExecDepth::Cycle);
7317        assert!((ExecDepth::Cycle >= ExecDepth::Cycle));
7318        assert!((ExecDepth::Full >= ExecDepth::Cycle));
7319    }
7320
7321    #[test]
7322    fn render_scope_elision_summary_shows_materialised_and_elides_to() {
7323        use nmbrs_workload::model::{BindingsDef, ScenarioNode, WorkloadPhase};
7324        use std::collections::HashMap;
7325
7326        let phase = WorkloadPhase {
7327            key_metrics: Vec::new(),
7328            dimensions: Default::default(),
7329            cycles: None,
7330            concurrency: None,
7331            rate: None,
7332            daemon: false,
7333            adapter: None,
7334            errors: None,
7335            tries: None,
7336            tries_backoff: None,
7337            interval: None,
7338            repeat: None,
7339            error_rate_max: None,
7340            timeout: None,
7341            stop_when: Vec::new(),
7342            throttle: None,
7343            continue_if: None,
7344            tags: None,
7345            ops: vec![],
7346            for_each: None,
7347            loop_scope: None,
7348            iter_scope: None,
7349            checkpoint: None,
7350            status_metrics: vec![],
7351            metrics: Default::default(),
7352            bindings: BindingsDef::default(),
7353            poll: None,
7354            optimize: None,
7355        };
7356        let mut phases = HashMap::new();
7357        phases.insert("predict".to_string(), phase);
7358        let mut tree = crate::scope_tree::ScopeTree::build(
7359            "default",
7360            &[ScenarioNode::Phase("predict".into())],
7361        );
7362        // Conservative classifier: empty workload + empty
7363        // phase ⇒ scenario and phase elide into root.
7364        let inputs = crate::scope_elision::ClassifyInputs {
7365            bindings: &BindingsDef::default(),
7366            params: &HashMap::new(),
7367            phases: &phases,
7368        };
7369        crate::scope_elision::classify_and_mark(&mut tree, &inputs);
7370
7371        let mut buf: Vec<u8> = Vec::new();
7372        render_scope_elision_summary(&tree, &mut buf).unwrap();
7373        let s = String::from_utf8(buf).unwrap();
7374
7375        assert!(s.contains("scope elision summary"), "missing header: {s}");
7376        // Workload root materialises always (SRD-13d §5.1).
7377        assert!(
7378            s.contains("workload") && s.contains("materialised=true"),
7379            "expected materialised=true line for workload root: {s}"
7380        );
7381        // Scenario + phase elide into the workload root.
7382        assert!(
7383            s.contains("elides-to=workload"),
7384            "expected elides-to=workload for empty phase: {s}"
7385        );
7386        assert!(
7387            s.contains("workload.scenario.default"),
7388            "expected scenario logical name: {s}"
7389        );
7390        assert!(
7391            s.contains("workload.scenario.default.phase.predict"),
7392            "expected phase logical name: {s}"
7393        );
7394    }
7395
7396    #[test]
7397    fn render_controls_tree_empty_session_writes_placeholder() {
7398        let root = nmbrs_metrics::component::Component::root(
7399            nmbrs_metrics::labels::Labels::of("session", "t"),
7400            std::collections::HashMap::new(),
7401        );
7402        let mut buf: Vec<u8> = Vec::new();
7403        render_controls_tree(&root, &mut buf).unwrap();
7404        let s = String::from_utf8(buf).unwrap();
7405        assert!(s.contains("no controls declared"), "got: {s}");
7406    }
7407
7408    #[test]
7409    fn render_controls_tree_lists_session_root_controls() {
7410        let root = nmbrs_metrics::component::Component::root(
7411            nmbrs_metrics::labels::Labels::of("session", "t"),
7412            std::collections::HashMap::new(),
7413        );
7414        root.read().unwrap().controls().declare(
7415            nmbrs_metrics::controls::ControlBuilder::new("log_level", 1u32)
7416                .reify_as_gauge(|v| Some(*v as f64))
7417                .branch_scope(nmbrs_metrics::controls::BranchScope::Subtree)
7418                .from_f64(|v| Ok(v as u32))
7419                .final_at_scope("session_root")
7420                .build(),
7421        );
7422
7423        let mut buf: Vec<u8> = Vec::new();
7424        render_controls_tree(&root, &mut buf).unwrap();
7425        let s = String::from_utf8(buf).unwrap();
7426        assert!(s.contains("log_level"), "missing name: {s}");
7427        assert!(s.contains("scope=subtree"), "missing scope: {s}");
7428        assert!(
7429            s.contains("final@session_root"),
7430            "missing final marker: {s}"
7431        );
7432        assert!(s.contains("f64-writable"), "missing write surface: {s}");
7433    }
7434
7435    // ── Regression: --session-path value not auto-promoted to scenario= ──
7436    //
7437    // Bug shape (caught by user during Phase C live exercise):
7438    // `nmbrs run wl.yaml cycles=2 --session-path X` was rewritten to
7439    // `nmbrs run wl.yaml cycles=2 --session-path scenario=X` because
7440    // `normalize_args` walked tokens flat and saw `X` as a bare
7441    // post-workload positional. Symptom: a literal directory at
7442    // `<cwd>/scenario=X` was created. The fix peeks for value-taking
7443    // flags so the value passes through unchanged.
7444
7445    fn s(v: &[&str]) -> Vec<String> {
7446        v.iter().map(|x| x.to_string()).collect()
7447    }
7448
7449    #[test]
7450    fn normalize_args_session_path_space_form_value_passes_through() {
7451        let out = normalize_args(&s(&[
7452            "wl.yaml",
7453            "cycles=2",
7454            "--session-path",
7455            "target/test-tmp/foo/session",
7456        ]));
7457        // The path arg must NOT be turned into `scenario=...`.
7458        assert!(
7459            !out.iter().any(|a| a.starts_with("scenario=")),
7460            "scenario= auto-promotion fired on a flag value: {out:?}"
7461        );
7462        assert_eq!(
7463            out,
7464            s(&[
7465                "wl.yaml",
7466                "cycles=2",
7467                "--session-path",
7468                "target/test-tmp/foo/session",
7469            ])
7470        );
7471    }
7472
7473    #[test]
7474    fn normalize_args_session_path_equals_form_unchanged() {
7475        let out = normalize_args(&s(&[
7476            "wl.yaml",
7477            "--session-path=target/test-tmp/foo/session",
7478        ]));
7479        assert_eq!(
7480            out,
7481            s(&["wl.yaml", "--session-path=target/test-tmp/foo/session",])
7482        );
7483    }
7484
7485    #[test]
7486    fn normalize_args_real_scenario_positional_still_promotes() {
7487        // The original feature: bare-word scenario shorthand.
7488        // Must keep working when no value-flag interferes.
7489        let out = normalize_args(&s(&["wl.yaml", "myscenario", "cycles=2"]));
7490        assert_eq!(out, s(&["wl.yaml", "scenario=myscenario", "cycles=2",]));
7491    }
7492
7493    #[test]
7494    fn normalize_args_scenario_after_session_path_still_promotes() {
7495        // After a value-flag pair, the next free positional is
7496        // still eligible for scenario= promotion. This confirms
7497        // the bookkeeping survives the look-ahead.
7498        let out = normalize_args(&s(&["wl.yaml", "--session-path", "/tmp/x", "myscenario"]));
7499        assert_eq!(
7500            out,
7501            s(&["wl.yaml", "--session-path", "/tmp/x", "scenario=myscenario",])
7502        );
7503    }
7504
7505    #[test]
7506    fn normalize_args_readout_value_passes_through() {
7507        let out = normalize_args(&s(&["wl.yaml", "--readout", "throughput ok_pct"]));
7508        assert!(
7509            !out.iter().any(|a| a.starts_with("scenario=")),
7510            "readout body misread as scenario: {out:?}"
7511        );
7512    }
7513
7514    /// `format_for_combinations` lays out vars and specs in
7515    /// column-aligned pairs. Each column is padded to the
7516    /// widest of its (var, spec) so corresponding entries
7517    /// stack vertically. The `color = false` argument forces
7518    /// the no-ANSI branch so the assertion can pattern-match
7519    /// the raw text — no dependency on the process's ambient
7520    /// TTY / `NO_COLOR` state (which `observer::use_color()`
7521    /// caches process-wide on first call and can't be undone
7522    /// per-test).
7523    #[test]
7524    fn format_for_combinations_aligns_columns() {
7525        let pairs = vec![
7526            ("sm".to_string(), "{sm_values}".to_string()),
7527            ("mnc".to_string(), "{mnc_values}".to_string()),
7528            (
7529                "alf_label".to_string(),
7530                "concat({alf_label_values})".to_string(),
7531            ),
7532        ];
7533        let out = format_for_combinations(&pairs, "", false);
7534        let lines: Vec<&str> = out.split('\n').collect();
7535        assert_eq!(lines.len(), 2, "MUST produce exactly 2 lines: {out:?}");
7536        assert!(
7537            lines[0].starts_with("for ["),
7538            "first line MUST start with `for [`: {:?}",
7539            lines[0]
7540        );
7541        assert!(
7542            lines[1].starts_with(" in ["),
7543            "second line MUST start with ` in [`: {:?}",
7544            lines[1]
7545        );
7546        // Bracket columns align: the `[` after `for` and the
7547        // `[` after `in ` should be at the same column index.
7548        let l0_bracket = lines[0].find('[').unwrap();
7549        let l1_bracket = lines[1].find('[').unwrap();
7550        assert_eq!(
7551            l0_bracket, l1_bracket,
7552            "`[` brackets MUST align: line0={l0_bracket}, line1={l1_bracket}"
7553        );
7554        // Column alignment: the comma after `sm,` on line 0
7555        // sits at the same column as the comma after the
7556        // `{sm_values},` on line 1 — except padded so that
7557        // `mnc` on line 0 starts at the same column as
7558        // `{mnc_values}` on line 1.
7559        let mnc_pos = lines[0].find("mnc").unwrap();
7560        let mnc_values_pos = lines[1].find("{mnc_values}").unwrap();
7561        assert_eq!(
7562            mnc_pos, mnc_values_pos,
7563            "column 2 MUST align: `mnc`@{mnc_pos} vs `{{mnc_values}}`@{mnc_values_pos}\n{out}"
7564        );
7565        let alf_pos = lines[0].find("alf_label").unwrap();
7566        let alf_concat_pos = lines[1].find("concat(").unwrap();
7567        assert_eq!(
7568            alf_pos, alf_concat_pos,
7569            "column 3 MUST align: `alf_label`@{alf_pos} vs `concat(...)`@{alf_concat_pos}\n{out}"
7570        );
7571        // Closing brackets present on both lines.
7572        assert!(lines[0].ends_with(']'));
7573        assert!(lines[1].ends_with(']'));
7574    }
7575}