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