Skip to main content

nmbrs_workload/
verify.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Workload verification — run a workload and check its output against rules
5//! embedded in the workload file. Shared by the `nmbrs check` subcommand and the
6//! example-walker test, so "how CI checks the examples" and "how a user checks
7//! their own workload" are the same code.
8//!
9//! A verification target is resolved the same way `nmbrs run` resolves
10//! `workload=…`: a directory (walk every workload under it), an existing
11//! `.yaml`/`.yml` file (run it by path), or a **bundled catalog name** such as
12//! `examples/cursors/all_cursor/enumerate` (run it by name, read its rules from the embedded
13//! source). So whatever tab-completion offers for `nmbrs check <TAB>` — local
14//! files *and* catalog names — checks the same way it runs.
15//!
16//! Two **equivalent** rule surfaces (a file may use either, or both — their
17//! cases combine):
18//!
19//! 1. **`#@` comment directives** — trailing YAML comments, inert to the
20//!    runtime:
21//!    ```text
22//!    #@ run scenario=enumerate
23//!    #@ expect 50 completed, 0 failed
24//!    #@ case overload
25//!    #@   run concurrency=32 rate=100000
26//!    #@   expect-fail error_rate_exceeded
27//!    #@ requires backend (needs a live service)
28//!    #@ session cwd            (sessions under the sandbox cwd — stick_session)
29//!    #@ again phases=probe     (a second invocation, session state preserved)
30//!    ```
31//! 2. **A `verify:` YAML block** — also inert (the runtime ignores unknown
32//!    top-level keys). Three equivalent shapes:
33//!    ```yaml
34//!    # single case (a directive map)
35//!    verify: { run: scenario=enumerate, expect: "50 completed, 0 failed" }
36//!    # a list of cases
37//!    verify:
38//!      - { case: a, run: scenario=a, expect: "..." }
39//!      - { case: b, expect-fail: "..." }
40//!    # a name-keyed map (key = case name)
41//!    verify:
42//!      a: { run: scenario=a, expect: "..." }
43//!      b: { expect: ["x", "y"] }
44//!    ```
45//!
46//! `expect` / `expect-fail` accept a single regex or a list of regexes. Each
47//! must match the run's combined stdout+stderr; `expect-fail` additionally
48//! requires a non-zero exit.
49
50use regex::Regex;
51use std::path::{Path, PathBuf};
52use std::process::Command;
53use std::time::{Duration, Instant};
54
55/// Default per-case run timeout, in seconds.
56pub const DEFAULT_TIMEOUT_SECS: u64 = 90;
57
58/// Keywords recognized inside a `verify:` directive map (vs. case names).
59const DIRECTIVE_KEYS: &[&str] = &[
60    "run",
61    "expect",
62    "expect-fail",
63    "expect_fail",
64    "requires",
65    "timeout",
66    "case",
67];
68
69/// One verification case: an invocation plus the regexes its output must match.
70pub struct VerifyCase {
71    pub name: String,
72    pub run_args: Vec<String>,
73    /// SRD-108 examples round-trip — extra invocations of the SAME
74    /// workload in the same sandbox after the first run, one arg
75    /// list per `#@ again` line, session state PRESERVED between
76    /// invocations. Every non-final invocation must succeed; the
77    /// final one feeds the expect / expect-fail rules, and the
78    /// `expect` regexes match the CONCATENATED output of all
79    /// invocations.
80    pub again: Vec<Vec<String>>,
81    /// `#@ session cwd` — omit the harness's `--session-path`
82    /// injection so sessions land under the (throwaway) sandbox
83    /// cwd's `sessions/` root. Required for behaviors keyed to
84    /// `sessions/latest` (SRD-106 `stick_session`); the sandbox
85    /// `sessions/` dir is wiped at case start so cases stay
86    /// independent.
87    pub session_cwd: bool,
88    pub expects: Vec<Regex>,
89    pub expect_fails: Vec<Regex>,
90    pub timeout: u64,
91}
92
93impl VerifyCase {
94    fn new(name: impl Into<String>) -> Self {
95        VerifyCase {
96            name: name.into(),
97            run_args: Vec::new(),
98            again: Vec::new(),
99            session_cwd: false,
100            expects: Vec::new(),
101            expect_fails: Vec::new(),
102            timeout: DEFAULT_TIMEOUT_SECS,
103        }
104    }
105}
106
107/// The parsed verification plan for one workload file.
108pub struct VerifyPlan {
109    /// `Some(reason)` ⇒ skip this file (e.g. needs external infra).
110    pub requires: Option<String>,
111    pub cases: Vec<VerifyCase>,
112}
113
114impl VerifyPlan {
115    /// Parse both rule surfaces from a workload file's text and combine them.
116    pub fn parse(src: &str) -> Result<VerifyPlan, String> {
117        let mut plan = parse_directives(src)?;
118        merge_verify_block(src, &mut plan)?;
119        Ok(plan)
120    }
121
122    /// True when the file declares no verification rules at all.
123    pub fn is_empty(&self) -> bool {
124        self.requires.is_none() && self.cases.is_empty()
125    }
126}
127
128fn compile(v: &str) -> Result<Regex, String> {
129    Regex::new(v).map_err(|e| format!("bad regex {v:?}: {e}"))
130}
131
132// ── `#@` comment directives ───────────────────────────────────────────────
133
134fn parse_directives(src: &str) -> Result<VerifyPlan, String> {
135    let mut requires: Option<String> = None;
136    let mut cases: Vec<VerifyCase> = Vec::new();
137    let mut cur: Option<VerifyCase> = None;
138
139    for raw in src.lines() {
140        let line = raw.trim_start();
141        let Some(rest) = line.strip_prefix("#@") else {
142            continue;
143        };
144        let rest = rest.trim();
145        let (kw, val) = match rest.split_once(char::is_whitespace) {
146            Some((k, v)) => (k.trim_end_matches(':'), v.trim()),
147            None => (rest.trim_end_matches(':'), ""),
148        };
149        macro_rules! case {
150            () => {
151                cur.get_or_insert_with(|| VerifyCase::new("default"))
152            };
153        }
154        match kw {
155            "requires" => requires = Some(val.to_string()),
156            "case" => {
157                if let Some(c) = cur.take() {
158                    cases.push(c);
159                }
160                cur = Some(VerifyCase::new(val));
161            }
162            "run" => case!().run_args = val.split_whitespace().map(String::from).collect(),
163            "again" => case!()
164                .again
165                .push(val.split_whitespace().map(String::from).collect()),
166            "session" => match val {
167                "cwd" => case!().session_cwd = true,
168                other => return Err(format!("unknown `#@ session {other}` (only `cwd`)")),
169            },
170            "expect" => case!().expects.push(compile(val)?),
171            "expect-fail" | "expect_fail" => case!().expect_fails.push(compile(val)?),
172            "timeout" => {
173                case!().timeout = val.parse().map_err(|_| format!("bad timeout {val:?}"))?
174            }
175            other => return Err(format!("unknown `#@ {other}` directive")),
176        }
177    }
178    if let Some(c) = cur.take() {
179        cases.push(c);
180    }
181    Ok(VerifyPlan { requires, cases })
182}
183
184// ── `verify:` YAML block ──────────────────────────────────────────────────
185
186fn merge_verify_block(src: &str, plan: &mut VerifyPlan) -> Result<(), String> {
187    // The file may not be a YAML mapping (or may be a `#@`-only file); either
188    // way, no `verify:` block to merge.
189    let Ok(doc) = serde_yaml::from_str::<serde_yaml::Value>(src) else {
190        return Ok(());
191    };
192    let Some(block) = doc.get("verify") else {
193        return Ok(());
194    };
195    match block {
196        serde_yaml::Value::Sequence(items) => {
197            for (i, item) in items.iter().enumerate() {
198                plan.cases.push(case_from_map(item, None, i)?);
199            }
200        }
201        serde_yaml::Value::Mapping(m) => {
202            let all_directives = m
203                .keys()
204                .all(|k| k.as_str().is_some_and(|s| DIRECTIVE_KEYS.contains(&s)));
205            if all_directives {
206                // A single directive map — either a file-level `requires` skip
207                // or one unnamed case.
208                if let Some(req) = m.get("requires").and_then(|v| v.as_str()) {
209                    plan.requires = Some(req.to_string());
210                } else {
211                    plan.cases.push(case_from_map(block, None, 0)?);
212                }
213            } else {
214                // A name-keyed map: each key is a case name.
215                for (k, v) in m {
216                    let name = k.as_str().ok_or("verify: case name must be a string")?;
217                    plan.cases.push(case_from_map(v, Some(name), 0)?);
218                }
219            }
220        }
221        _ => return Err("verify: must be a map or a list of cases".to_string()),
222    }
223    Ok(())
224}
225
226/// Build a case from a `verify:` entry map. `name_override` (the key in a
227/// name-keyed map) wins; else the entry's `case:` field; else `case-<idx>`.
228fn case_from_map(
229    v: &serde_yaml::Value,
230    name_override: Option<&str>,
231    idx: usize,
232) -> Result<VerifyCase, String> {
233    let m = v.as_mapping().ok_or("verify: each case must be a map")?;
234    let get = |k: &str| m.get(serde_yaml::Value::from(k));
235    let name = name_override
236        .map(String::from)
237        .or_else(|| get("case").and_then(|x| x.as_str()).map(String::from))
238        .unwrap_or_else(|| format!("case-{idx}"));
239    let mut case = VerifyCase::new(name);
240    if let Some(run) = get("run").and_then(|x| x.as_str()) {
241        case.run_args = run.split_whitespace().map(String::from).collect();
242    }
243    for s in strings_of(get("expect")) {
244        case.expects.push(compile(&s)?);
245    }
246    for s in strings_of(get("expect-fail").or_else(|| get("expect_fail"))) {
247        case.expect_fails.push(compile(&s)?);
248    }
249    if let Some(t) = get("timeout").and_then(|x| x.as_u64()) {
250        case.timeout = t;
251    }
252    Ok(case)
253}
254
255/// A scalar string or a sequence of strings → `Vec<String>`.
256fn strings_of(v: Option<&serde_yaml::Value>) -> Vec<String> {
257    match v {
258        Some(serde_yaml::Value::String(s)) => vec![s.clone()],
259        Some(serde_yaml::Value::Sequence(items)) => items
260            .iter()
261            .filter_map(|x| x.as_str().map(String::from))
262            .collect(),
263        _ => Vec::new(),
264    }
265}
266
267// ── Run + check ───────────────────────────────────────────────────────────
268
269/// What one verification case produced.
270pub enum Outcome {
271    Pass,
272    Skip(String),
273    Fail(String),
274}
275
276/// Run one case via `<binary> run workload=… <args> --session-path …` (under
277/// an in-process deadline) from `sandbox`, capture combined output, and check
278/// the rules.
279/// `workload_ref` is whatever goes after `workload=` — an absolute file path
280/// or a bundled catalog name; the subprocess resolves it exactly as a normal
281/// `nmbrs run` would.
282pub fn run_case(
283    binary: &Path,
284    workload_ref: &str,
285    sandbox: &Path,
286    label: &str,
287    case: &VerifyCase,
288) -> Result<(), String> {
289    let safe_label = label.replace(['/', ' ', ':'], "_");
290    let session = sandbox.join(format!("session-{safe_label}"));
291    // Case independence for cwd-session cases: each gets a
292    // PRIVATE working directory, so its `sessions/latest` can
293    // neither re-attach to a prior case's session nor race a
294    // concurrent case's — the check walker drives cases on
295    // worker threads, and a shared cwd made multi-invocation
296    // re-attach cases fail only in large sweeps.
297    let case_cwd;
298    let workdir: &Path = if case.session_cwd {
299        case_cwd = sandbox.join(format!("cwd-{safe_label}"));
300        let _ = std::fs::remove_dir_all(&case_cwd);
301        std::fs::create_dir_all(&case_cwd).map_err(|e| format!("create case cwd: {e}"))?;
302        &case_cwd
303    } else {
304        let _ = std::fs::remove_dir_all(&session);
305        sandbox
306    };
307
308    // The deadline is enforced here rather than by wrapping in the
309    // coreutils `timeout` program: that binary isn't a given on
310    // macOS, and on Windows `timeout.exe` is the cmd.exe delay
311    // command — it can't run a child at all.
312    let invoke = |args: &[String]| -> Result<(String, bool, bool), String> {
313        use std::io::Read as _;
314        use std::process::Stdio;
315        let mut cmd = Command::new(binary);
316        cmd.arg("run")
317            .arg(format!("workload={workload_ref}"))
318            .args(args);
319        if !case.session_cwd {
320            cmd.arg("--session-path").arg(&session);
321        }
322        let mut child = cmd
323            .current_dir(workdir)
324            .stdin(Stdio::null())
325            .stdout(Stdio::piped())
326            .stderr(Stdio::piped())
327            .spawn()
328            .map_err(|e| format!("spawn failed: {e}"))?;
329        // Drain both pipes on threads so a chatty child can't fill
330        // one while we watch the deadline, deadlocking both sides.
331        let mut out_pipe = child.stdout.take().expect("stdout piped");
332        let mut err_pipe = child.stderr.take().expect("stderr piped");
333        let out_h = std::thread::spawn(move || {
334            let mut buf = Vec::new();
335            let _ = out_pipe.read_to_end(&mut buf);
336            buf
337        });
338        let err_h = std::thread::spawn(move || {
339            let mut buf = Vec::new();
340            let _ = err_pipe.read_to_end(&mut buf);
341            buf
342        });
343        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(case.timeout);
344        let (status, timed_out) = loop {
345            if let Some(st) = child.try_wait().map_err(|e| format!("wait failed: {e}"))? {
346                break (st, false);
347            }
348            if std::time::Instant::now() >= deadline {
349                let _ = child.kill();
350                let st = child.wait().map_err(|e| format!("wait failed: {e}"))?;
351                break (st, true);
352            }
353            std::thread::sleep(std::time::Duration::from_millis(25));
354        };
355        let stdout = out_h.join().unwrap_or_default();
356        let stderr = err_h.join().unwrap_or_default();
357        let mut combined = format!(
358            "{}{}",
359            String::from_utf8_lossy(&stdout),
360            String::from_utf8_lossy(&stderr)
361        );
362        if !status.success() {
363            // How the run ended is part of its result: a run killed by a
364            // signal prints nothing of its own to say so.
365            combined.push_str(&format!("\nnmbrs run ended with {status}\n"));
366        }
367        Ok((combined, status.success(), timed_out))
368    };
369
370    let (mut combined, mut succeeded, mut timed_out) = invoke(&case.run_args)?;
371    for (i, extra) in case.again.iter().enumerate() {
372        if !succeeded || timed_out {
373            return Err(format!(
374                "invocation {} of {} failed before the `again` steps                  completed:
375{combined}",
376                i + 1,
377                case.again.len() + 1
378            ));
379        }
380        let (c, s, to) = invoke(extra)?;
381        combined.push_str(&c);
382        succeeded = s;
383        timed_out = to;
384    }
385    check_case_output(case, &combined, succeeded, timed_out)
386}
387
388/// How many trailing output lines a failure with no error line is reported
389/// with.
390const FAILURE_TAIL_LINES: usize = 15;
391
392/// Check one case's RUN RESULT against its expectations — the run-mechanism-
393/// agnostic half of [`run_case`]. `combined` is the merged stdout+stderr the
394/// run produced; `succeeded` is its exit success; `timed_out` is the timeout
395/// signal. Used both by the subprocess [`run_case`] and by `nmbrs`'s in-process
396/// `run_executions`-backed verification (so the SAME `expect` / `expect-fail`
397/// rules apply whether examples run as subprocesses or as concurrent in-process
398/// executions sharing one session).
399pub fn check_case_output(
400    case: &VerifyCase,
401    combined: &str,
402    succeeded: bool,
403    timed_out: bool,
404) -> Result<(), String> {
405    if timed_out {
406        return Err(format!("timed out after {}s", case.timeout));
407    }
408    if case.expect_fails.is_empty() {
409        if !succeeded {
410            // Name the failure by its error line; a run that failed without
411            // one is reported by the end of what it did print.
412            let err = match combined
413                .lines()
414                .find(|l| l.contains("error:") || l.contains("panic"))
415            {
416                Some(line) => line.to_string(),
417                None => {
418                    let lines: Vec<&str> = combined.lines().collect();
419                    let tail = &lines[lines.len().saturating_sub(FAILURE_TAIL_LINES)..];
420                    format!("no error line; the output ended:\n{}", tail.join("\n"))
421                }
422            };
423            return Err(format!("run failed (expected success): {err}"));
424        }
425    } else {
426        if succeeded {
427            return Err("expected a failure (`expect-fail`) but the run succeeded".to_string());
428        }
429        for re in &case.expect_fails {
430            if !re.is_match(combined) {
431                return Err(format!(
432                    "expect-fail /{re}/ did not match the failure output"
433                ));
434            }
435        }
436    }
437    for re in &case.expects {
438        if !re.is_match(combined) {
439            return Err(format!("expect /{re}/ did not match the output"));
440        }
441    }
442    Ok(())
443}
444
445/// Whether a workload is REQUIRED to declare verification rules.
446///
447/// True for anything under an `examples/` directory: those files are the
448/// documented, CI-gated surface, and one arriving without rules is a
449/// regression in the documentation itself. Everywhere else rules are
450/// optional — an unruled workload is skipped, not failed.
451///
452/// Path-component matching, not substring: a workload at
453/// `/home/me/examples-scratch/w.yaml` is not under `examples/`, while
454/// `/repo/examples/optimizer/w.yaml` is.
455pub fn requires_verification_rules(run_ref: &str) -> bool {
456    std::path::Path::new(run_ref)
457        .components()
458        .any(|c| c.as_os_str() == "examples")
459}
460
461/// Verify a workload from its rule text + run reference: parse the rules, run
462/// every case, return one `(label, Outcome)` per case (or a single Skip / Fail
463/// for the whole workload). `run_ref` is what to pass as `workload=` — an
464/// absolute file path or a catalog name.
465pub fn verify_source(
466    binary: &Path,
467    label_root: &str,
468    run_ref: &str,
469    rule_text: &str,
470    sandbox: &Path,
471) -> Vec<(String, Outcome)> {
472    let plan = match VerifyPlan::parse(rule_text) {
473        Ok(p) => p,
474        Err(e) => return vec![(label_root.to_string(), Outcome::Fail(e))],
475    };
476    if let Some(reason) = plan.requires {
477        return vec![(label_root.to_string(), Outcome::Skip(reason))];
478    }
479    if plan.cases.is_empty() {
480        // A workload with no rules is not a failure in general — it is a
481        // workload nobody asked to be checked. `nmbrs check <dir>` walks every
482        // YAML it finds, and most of those (adapter workloads, operational
483        // ones like an incremental compaction sweep) exist to be RUN against real
484        // infrastructure, not to self-verify; failing them made the walk's
485        // result meaningless and trained people to ignore it.
486        //
487        // Under `examples/` the opposite holds: those files are the
488        // documentation CI gates, and one landing without rules is exactly
489        // the regression this check exists to catch. So there, silence is a
490        // failure.
491        return vec![(
492            label_root.to_string(),
493            if requires_verification_rules(run_ref) {
494                Outcome::Fail(
495                    "no verification rules — every workload under `examples/` must \
496                     declare them (add `#@ expect …` comments or a `verify:` block)"
497                        .into(),
498                )
499            } else {
500                Outcome::Skip("no verification rules — nothing to check".into())
501            },
502        )];
503    }
504    plan.cases
505        .iter()
506        .map(|c| {
507            let label = format!("{label_root}::{}", c.name);
508            let outcome = match run_case(binary, run_ref, sandbox, &label, c) {
509                Ok(()) => Outcome::Pass,
510                Err(e) => Outcome::Fail(format!("{label}: {e}")),
511            };
512            (label, outcome)
513        })
514        .collect()
515}
516
517/// Verify one workload file: read it, then run it by its absolute path. The
518/// file is read relative to *this* process's cwd, but the run reference is made
519/// absolute because each case is launched from a sandbox cwd.
520pub fn verify_file(
521    binary: &Path,
522    label_root: &str,
523    workload: &Path,
524    sandbox: &Path,
525) -> Vec<(String, Outcome)> {
526    let src = match std::fs::read_to_string(workload) {
527        Ok(s) => s,
528        Err(e) => {
529            return vec![(
530                label_root.to_string(),
531                Outcome::Fail(format!("read error: {e}")),
532            )];
533        }
534    };
535    let abs = workload
536        .canonicalize()
537        .unwrap_or_else(|_| workload.to_path_buf());
538    verify_source(binary, label_root, &abs.to_string_lossy(), &src, sandbox)
539}
540
541/// Where a verification target's rule text and run reference come from. Mirrors
542/// `nmbrs run`'s `workload=…` resolution.
543pub enum WorkloadSource {
544    /// A workload file on disk: run by (absolute) path, rules from the file.
545    File(PathBuf),
546    /// A bundled catalog workload: run by name, rules from the embedded source.
547    Catalog { name: String, source: String },
548}
549
550/// Resolve a single workload reference the way `nmbrs run` does: an existing
551/// `.yaml`/`.yml` file path first, then a bundled catalog name. `None` if it is
552/// neither. Directories are not a single workload — callers handle those
553/// separately (via [`verify_path`]).
554pub fn resolve_ref(reference: &str) -> Option<WorkloadSource> {
555    let p = Path::new(reference);
556    if p.is_file() {
557        // Absolute so the sandbox-cwd subprocess can still find it.
558        return Some(WorkloadSource::File(
559            p.canonicalize().unwrap_or_else(|_| p.to_path_buf()),
560        ));
561    }
562    crate::catalog::lookup(reference).map(|w| WorkloadSource::Catalog {
563        name: w.name.to_string(),
564        source: w.source.to_string(),
565    })
566}
567
568/// A workload reference's **declared top-level `params:`** (string scalars),
569/// following its `extends:` chain — resolved the way `nmbrs run` resolves
570/// `workload=…`. Returns `None` if the reference resolves to nothing or has
571/// no `params:` block.
572///
573/// The canonical "what params did the workload declare" accessor. The
574/// runner folds these under the CLI params (CLI wins) to form the run's
575/// effective params, so a setting works identically whether declared in the
576/// workload or passed on the command line. Also used to recognize a
577/// **console-owning adapter declared in the workload** (e.g.
578/// `params: { adapter: plotter }`) so the dashboard yields to the adapter on
579/// a TTY (SRD-41/87); the returned params carry the adapter's display-shaping
580/// keys (e.g. stdout's `filename`) so the preference is decided correctly.
581pub fn declared_params(reference: &str) -> Option<std::collections::HashMap<String, String>> {
582    let merged = match resolve_ref(reference)? {
583        // Display-shaping probe only: resolution warnings are
584        // dropped HERE because the authoritative load that follows
585        // this probe surfaces the identical warnings itself.
586        WorkloadSource::File(path) => crate::extends::load_and_merge(&path).ok()?.0,
587        WorkloadSource::Catalog { name, .. } => {
588            crate::extends::load_and_merge_bundled(crate::catalog::lookup(&name)?)
589                .ok()?
590                .0
591        }
592    };
593    let doc: serde_yaml::Value = serde_yaml::from_str(&merged).ok()?;
594    let params = doc.get("params")?.as_mapping()?;
595    let mut out = std::collections::HashMap::new();
596    for (k, v) in params {
597        let Some(key) = k.as_str() else { continue };
598        // Only scalar params shape the display decision; skip nested
599        // structures. Numbers / bools render to their lexical form.
600        let val = match v {
601            serde_yaml::Value::String(s) => s.clone(),
602            serde_yaml::Value::Number(n) => n.to_string(),
603            serde_yaml::Value::Bool(b) => b.to_string(),
604            _ => continue,
605        };
606        out.insert(key.to_string(), val);
607    }
608    Some(out)
609}
610
611/// Aggregate verification result across one or more files.
612#[derive(Default)]
613pub struct VerifySummary {
614    pub passed: usize,
615    pub skipped: Vec<String>,
616    pub failures: Vec<String>,
617    /// One entry per workload checked, in completion order — the
618    /// raw material for an end-of-run "slowest workloads" report.
619    pub timings: Vec<WorkloadTiming>,
620}
621
622/// A single workload's aggregate outcome, for live progress and the
623/// timing report. Coarser than [`Outcome`] (which is per *case*): a
624/// workload with any failing case is [`CheckStatus::Fail`]; one with no
625/// failures and at least one skip (and no pass) is [`CheckStatus::Skip`];
626/// otherwise [`CheckStatus::Pass`].
627#[derive(Debug, Clone, Copy, PartialEq, Eq)]
628pub enum CheckStatus {
629    Pass,
630    Skip,
631    Fail,
632}
633
634/// Wall-clock spent checking one workload, with its aggregate status.
635#[derive(Debug, Clone)]
636pub struct WorkloadTiming {
637    pub label: String,
638    pub elapsed: Duration,
639    pub status: CheckStatus,
640}
641
642/// Live verification progress, emitted as workloads start and finish so a
643/// caller (e.g. `nmbrs check`) can render an active/pending/done/errors
644/// status line. Invoked from worker threads — handlers must be `Sync`.
645#[derive(Debug, Clone)]
646pub enum CheckProgress {
647    /// Discovery finished — `total` workloads will be checked.
648    Begin { total: usize },
649    /// A workload began running.
650    Started { label: String },
651    /// A workload finished, with its wall-clock and aggregate status.
652    Finished {
653        label: String,
654        elapsed: Duration,
655        status: CheckStatus,
656    },
657}
658
659/// A progress handler. `&`-shared across verification worker threads.
660pub type ProgressFn<'a> = dyn Fn(CheckProgress) + Sync + 'a;
661
662/// No-op progress handler, for callers that only want the summary.
663pub fn no_progress(_: CheckProgress) {}
664
665/// Fold a file's per-case outcomes into one [`CheckStatus`].
666fn aggregate_status(outcomes: &[(String, Outcome)]) -> CheckStatus {
667    let mut saw_pass = false;
668    let mut saw_skip = false;
669    for (_, o) in outcomes {
670        match o {
671            Outcome::Fail(_) => return CheckStatus::Fail,
672            Outcome::Pass => saw_pass = true,
673            Outcome::Skip(_) => saw_skip = true,
674        }
675    }
676    if saw_skip && !saw_pass {
677        CheckStatus::Skip
678    } else {
679        CheckStatus::Pass
680    }
681}
682
683/// Verify a workload file or every `*.yaml` under a directory (recursively).
684/// Files run concurrently (cases within a file are sequential). `progress`
685/// is invoked from worker threads as each workload starts and finishes —
686/// pass [`no_progress`] for a quiet run.
687pub fn verify_path(
688    binary: &Path,
689    path: &Path,
690    sandbox: &Path,
691    progress: &ProgressFn,
692) -> VerifySummary {
693    let _ = std::fs::create_dir_all(sandbox);
694    let mut files: Vec<PathBuf> = Vec::new();
695    if path.is_dir() {
696        collect_yaml(path, &mut files);
697        files.sort();
698    } else {
699        files.push(path.to_path_buf());
700    }
701    progress(CheckProgress::Begin { total: files.len() });
702
703    let acc: std::sync::Mutex<VerifySummary> = std::sync::Mutex::new(VerifySummary::default());
704    // Work-stealing over `files`: a shared atomic cursor each worker pulls from
705    // when it frees up. Static chunking serialized the slow demos (settle /
706    // servo workloads that dwell on real-time metric windows) behind one chunk
707    // while other chunks idled; a shared queue runs them concurrently, so the
708    // wall-clock floor is the single slowest file, not a chunk-sum. Workers
709    // spend almost all their time blocked on the child `nmbrs` process, so we
710    // oversubscribe past core count (2× cores, capped) to overlap the waits.
711    let next = std::sync::atomic::AtomicUsize::new(0);
712    let workers = files.len().min(
713        std::thread::available_parallelism()
714            .map(|n| n.get())
715            .unwrap_or(4)
716            .saturating_mul(2)
717            .clamp(1, 16),
718    );
719    std::thread::scope(|s| {
720        for _ in 0..workers {
721            s.spawn(|| {
722                loop {
723                    let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
724                    let Some(f) = files.get(i) else { break };
725                    let label = f
726                        .file_name()
727                        .and_then(|n| n.to_str())
728                        .unwrap_or("?")
729                        .to_string();
730                    // Run the file (a sequence of cases) outside the lock, then
731                    // fold its outcomes under a single lock acquisition.
732                    progress(CheckProgress::Started {
733                        label: label.clone(),
734                    });
735                    let start = Instant::now();
736                    let outcomes = verify_file(binary, &label, f, sandbox);
737                    let elapsed = start.elapsed();
738                    let status = aggregate_status(&outcomes);
739                    let mut g = acc.lock().unwrap();
740                    for (lbl, outcome) in outcomes {
741                        match outcome {
742                            Outcome::Pass => g.passed += 1,
743                            Outcome::Skip(r) => g.skipped.push(format!("{lbl}: {r}")),
744                            Outcome::Fail(m) => g.failures.push(m),
745                        }
746                    }
747                    g.timings.push(WorkloadTiming {
748                        label: label.clone(),
749                        elapsed,
750                        status,
751                    });
752                    drop(g);
753                    progress(CheckProgress::Finished {
754                        label,
755                        elapsed,
756                        status,
757                    });
758                }
759            });
760        }
761    });
762    let mut sum = acc.into_inner().unwrap();
763    sum.skipped.sort();
764    sum.failures.sort();
765    sum
766}
767
768/// Verify a target named the way `nmbrs run` names workloads: a directory (walk
769/// every workload under it), an existing workload file, or a bundled catalog
770/// name (`examples/cursors/all_cursor/enumerate`, …). This is the `nmbrs check` entry point — so
771/// anything the binary can `run` by name, it can `check` by the same name.
772pub fn verify_target(
773    binary: &Path,
774    target: &str,
775    sandbox: &Path,
776    progress: &ProgressFn,
777) -> VerifySummary {
778    let p = Path::new(target);
779    if p.is_dir() {
780        return verify_path(binary, p, sandbox, progress);
781    }
782    let _ = std::fs::create_dir_all(sandbox);
783    // A single named target is one workload; emit the same Begin/Started/
784    // Finished lifecycle a directory walk does so progress rendering is
785    // uniform, and record its timing for the report.
786    progress(CheckProgress::Begin { total: 1 });
787    let label = match &resolve_ref(target) {
788        Some(WorkloadSource::File(path)) => path
789            .file_name()
790            .and_then(|n| n.to_str())
791            .unwrap_or(target)
792            .to_string(),
793        _ => target.to_string(),
794    };
795    progress(CheckProgress::Started {
796        label: label.clone(),
797    });
798    let start = Instant::now();
799    let cases: Vec<(String, Outcome)> = match resolve_ref(target) {
800        Some(WorkloadSource::File(path)) => verify_file(binary, &label, &path, sandbox),
801        Some(WorkloadSource::Catalog { name, source }) => {
802            verify_source(binary, &name, &name, &source, sandbox)
803        }
804        None => vec![(
805            target.to_string(),
806            Outcome::Fail(format!(
807                "no such workload '{target}': not a local file, not a directory, and \
808                 no bundled workload by that name (try `nmbrs describe workloads --all`).{}",
809                crate::suggest::did_you_mean(&crate::suggest::suggest_workloads(target))
810            )),
811        )],
812    };
813    let elapsed = start.elapsed();
814    let status = aggregate_status(&cases);
815    let mut sum = VerifySummary::default();
816    for (lbl, outcome) in cases {
817        match outcome {
818            Outcome::Pass => sum.passed += 1,
819            Outcome::Skip(r) => sum.skipped.push(format!("{lbl}: {r}")),
820            Outcome::Fail(m) => sum.failures.push(m),
821        }
822    }
823    sum.timings.push(WorkloadTiming {
824        label: label.clone(),
825        elapsed,
826        status,
827    });
828    progress(CheckProgress::Finished {
829        label,
830        elapsed,
831        status,
832    });
833    sum
834}
835
836/// Every `*.yaml` / `*.yml` workload file under `dir` (recursive),
837/// sorted. The discovery half of [`verify_path`], exposed so the
838/// in-process example walker (`nmbrs_runtime::verify_in_process`) finds
839/// the same files the subprocess walker does.
840pub fn collect_workload_files(dir: &Path) -> Vec<PathBuf> {
841    let mut files = Vec::new();
842    collect_yaml(dir, &mut files);
843    files.sort();
844    files
845}
846
847fn collect_yaml(dir: &Path, out: &mut Vec<PathBuf>) {
848    let Ok(entries) = std::fs::read_dir(dir) else {
849        return;
850    };
851    for e in entries.flatten() {
852        let p = e.path();
853        if p.is_dir() {
854            collect_yaml(&p, out);
855        } else if p.extension().is_some_and(|x| x == "yaml" || x == "yml") {
856            out.push(p);
857        }
858    }
859}
860
861#[cfg(test)]
862mod rules_required_tests {
863    use super::requires_verification_rules;
864
865    /// Under `examples/`, rules are the point — a file without them is a
866    /// documentation regression, so the check must fail rather than skip.
867    #[test]
868    fn examples_require_rules() {
869        assert!(requires_verification_rules(
870            "/repo/examples/optimizer/control.yaml"
871        ));
872        assert!(requires_verification_rules("examples/w.yaml"));
873        assert!(requires_verification_rules(
874            "/repo/nmbrs/examples/modules/module_test.yaml"
875        ));
876    }
877
878    /// Everywhere else rules are optional: adapter and operational workloads
879    /// exist to be RUN against real infrastructure, not to self-verify.
880    #[test]
881    fn other_locations_do_not_require_rules() {
882        assert!(!requires_verification_rules(
883            "/repo/nmbrs/workloads/cql/incremental_sweep.yaml"
884        ));
885        assert!(!requires_verification_rules("/tmp/scratch.yaml"));
886        assert!(!requires_verification_rules("some_catalog_name"));
887    }
888
889    /// Component matching, not substring — a sibling directory whose name
890    /// merely starts with "examples" is not the examples tree.
891    #[test]
892    fn matches_path_components_not_substrings() {
893        assert!(!requires_verification_rules(
894            "/home/me/examples-scratch/w.yaml"
895        ));
896        assert!(!requires_verification_rules("/home/me/myexamples/w.yaml"));
897        assert!(requires_verification_rules(
898            "/home/me/examples/scratch/w.yaml"
899        ));
900    }
901}
902
903#[cfg(test)]
904mod tests {
905    use super::*;
906
907    #[test]
908    fn comment_and_yaml_forms_are_equivalent() {
909        let comment = "ops: { a: { raw: x } }\n#@ run cycles=3\n#@ expect 0 failed\n";
910        let single = "ops: { a: { raw: x } }\nverify: { run: cycles=3, expect: \"0 failed\" }\n";
911        let listed =
912            "ops: { a: { raw: x } }\nverify:\n  - { run: cycles=3, expect: \"0 failed\" }\n";
913        let named =
914            "ops: { a: { raw: x } }\nverify:\n  smoke: { run: cycles=3, expect: \"0 failed\" }\n";
915        for src in [comment, single, listed, named] {
916            let p = VerifyPlan::parse(src).expect("parse");
917            assert_eq!(p.cases.len(), 1, "one case for: {src}");
918            assert_eq!(p.cases[0].run_args, vec!["cycles=3"], "run for: {src}");
919            assert_eq!(p.cases[0].expects.len(), 1, "expect for: {src}");
920        }
921    }
922
923    #[test]
924    fn name_keyed_map_yields_named_cases() {
925        let src = "verify:\n  alpha: { run: scenario=a, expect: \"x\" }\n  beta: { expect: [\"y\", \"z\"] }\n";
926        let p = VerifyPlan::parse(src).unwrap();
927        let names: Vec<&str> = p.cases.iter().map(|c| c.name.as_str()).collect();
928        assert!(
929            names.contains(&"alpha") && names.contains(&"beta"),
930            "names: {names:?}"
931        );
932        let beta = p.cases.iter().find(|c| c.name == "beta").unwrap();
933        assert_eq!(beta.expects.len(), 2);
934    }
935
936    #[test]
937    fn requires_block_skips_the_file() {
938        let p = VerifyPlan::parse("verify: { requires: needs a backend }\n").unwrap();
939        assert_eq!(p.requires.as_deref(), Some("needs a backend"));
940        assert!(p.cases.is_empty());
941    }
942
943    #[test]
944    fn comment_and_block_cases_combine() {
945        let src = "#@ case fromcomment\n#@   expect a\nverify:\n  fromblock: { expect: b }\n";
946        let p = VerifyPlan::parse(src).unwrap();
947        let names: Vec<&str> = p.cases.iter().map(|c| c.name.as_str()).collect();
948        assert!(
949            names.contains(&"fromcomment") && names.contains(&"fromblock"),
950            "{names:?}"
951        );
952    }
953
954    #[test]
955    fn resolve_ref_finds_files_and_rejects_unknown_names() {
956        // An on-disk file resolves to an absolute `File` source.
957        let dir = std::env::temp_dir().join(format!("nmbrs-verify-resolve-{}", std::process::id()));
958        let _ = std::fs::create_dir_all(&dir);
959        let file = dir.join("w.yaml");
960        std::fs::write(&file, "ops: { a: { raw: x } }\n").unwrap();
961        match resolve_ref(file.to_str().unwrap()) {
962            Some(WorkloadSource::File(p)) => assert!(p.is_absolute(), "absolute: {p:?}"),
963            other => panic!(
964                "expected File, got {}",
965                matches!(other, Some(WorkloadSource::Catalog { .. })) as i32
966            ),
967        }
968        // A name that is neither a file nor (in this test process) a bundled
969        // workload resolves to nothing — the CLI reports it as not found.
970        assert!(resolve_ref("definitely/not/a/workload").is_none());
971        let _ = std::fs::remove_dir_all(&dir);
972    }
973}