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