Skip to main content

nmbrs_runtime/
workload_lint.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Load-time authoring lints for semantic surfaces serde cannot check
5//! (SRD-83 follow-up). Runs once at workload load — before any phase
6//! dispatch, dryrun included — per the dryrun-as-validation-floor
7//! doctrine and "never ignore silently".
8//!
9//! Three checks:
10//!
11//! 1. **Error-router specs parse.** Every `errors:` spec — phase-level
12//!    and op-level — goes through the real
13//!    [`ErrorRouter`](nmbrs_errorhandler::ErrorRouter) parser, so a
14//!    bad verb or regex is a load error naming its phase/op instead of
15//!    a first-error-at-runtime surprise. Specs carrying `{param}`
16//!    interpolation are skipped here (they resolve later and are
17//!    parsed again at scope init).
18//! 2. **Error-router catch-all lint.** An error class matching no rule
19//!    falls through to `stop` with only an eprintln; a router without a
20//!    literal `.*` rule therefore has a silent fall-through mode. One
21//!    warning per such spec.
22//! 3. **Metric-family lint.** `metric('family, …', 'stat')` and
23//!    `metric_window(…)` selectors inside `stop_when`, `continue_if`,
24//!    and phase `poll.until` predicates read 0.0 SILENTLY when the
25//!    family never registers — a typo'd family makes a coordination
26//!    gate pass instantly or hang to its timeout. Family tokens are
27//!    checked against the built-in activity instrument namespace plus
28//!    every phase-declared `metrics:` name. Unknown families WARN
29//!    rather than fail: adapter counters and relevancy families are
30//!    registered at runtime and are not statically knowable.
31//!
32//! Hard failures come back as `Err`; warnings come back as strings for
33//! the caller to route through `diag!` (keeps this module pure and
34//! directly testable).
35
36use nmbrs_workload::model::{StopConditionSpec, WorkloadPhase};
37
38/// Built-in activity instrument families, mirroring
39/// `ActivityMetrics::register_on` (activity.rs) — the same namespace the
40/// SRD-83 stop-condition wires draw from. Phase-declared `metrics:`
41/// names are unioned in per workload before matching.
42const ACTIVITY_FAMILIES: [&str; 18] = [
43    "cycles_servicetime",
44    "cycles_waittime",
45    "cycles_responsetime",
46    "result_success",
47    "result_failure",
48    "result_total",
49    "cycles_total",
50    "skips_total",
51    "errors_total",
52    "attempt_total",
53    "attempt_success",
54    "attempt_failure",
55    "stanzas_total",
56    "daemon_cancelled_total",
57    "daemon_errors_total",
58    "result_elements",
59    "result_bytes",
60    "tries",
61];
62
63/// Run every lint over the loaded workload. `Ok(warnings)` — the run
64/// may proceed, with each warning routed to the operator; `Err` — a
65/// spec is malformed and the load fails.
66pub fn lint_workload<'a>(
67    workload_stop_when: &[StopConditionSpec],
68    phases: impl Iterator<Item = (&'a str, &'a WorkloadPhase)> + Clone,
69) -> Result<Vec<String>, String> {
70    let mut warnings = Vec::new();
71
72    // The metric-family allowlist: built-ins + every phase-declared
73    // phase-metric name across the workload (a gate in one phase may
74    // legitimately read a metric another phase declares).
75    let mut known: Vec<String> = ACTIVITY_FAMILIES.iter().map(|s| s.to_string()).collect();
76    for (_, phase) in phases.clone() {
77        known.extend(phase.metrics.keys().cloned());
78    }
79
80    for sc in workload_stop_when {
81        lint_metric_families(&sc.when, &known, "workload `stop_when`", &mut warnings);
82    }
83
84    for (name, phase) in phases {
85        let ctx = format!("phase '{name}'");
86        if let Some(spec) = phase.errors.as_deref() {
87            lint_error_router(spec, &ctx, &mut warnings)?;
88        }
89        for op in &phase.ops {
90            if let Some(serde_json::Value::String(spec)) = op.params.get("errors") {
91                lint_error_router(spec, &format!("{ctx} op '{}'", op.name), &mut warnings)?;
92            }
93        }
94        for sc in &phase.stop_when {
95            lint_metric_families(
96                &sc.when,
97                &known,
98                &format!("{ctx} `stop_when`"),
99                &mut warnings,
100            );
101        }
102        if let Some(gate) = &phase.continue_if {
103            lint_metric_families(
104                &gate.when,
105                &known,
106                &format!("{ctx} `continue_if`"),
107                &mut warnings,
108            );
109        }
110        if let Some(poll) = &phase.poll {
111            lint_metric_families(
112                &poll.until,
113                &known,
114                &format!("{ctx} `poll.until`"),
115                &mut warnings,
116            );
117        }
118    }
119
120    Ok(warnings)
121}
122
123/// Check one `errors:` router spec: it must parse (hard error), and it
124/// should carry a catch-all rule (warning). Interpolated specs are
125/// deferred to runtime resolution.
126fn lint_error_router(spec: &str, ctx: &str, warnings: &mut Vec<String>) -> Result<(), String> {
127    if spec.contains('{') {
128        return Ok(()); // `{param}`-bearing; resolved and parsed later
129    }
130    let router = nmbrs_errorhandler::ErrorRouter::parse(spec)
131        .map_err(|e| format!("{ctx}: invalid `errors:` spec '{spec}': {e}"))?;
132    if !router.has_catch_all() {
133        warnings.push(format!(
134            "{ctx}: `errors: \"{spec}\"` has no catch-all rule — an error \
135             class matching no pattern falls through to `stop`; end the \
136             spec with `.*:<verbs>` to make the default explicit"
137        ));
138    }
139    Ok(())
140}
141
142/// Scan one polydat predicate source for `metric(…)` /
143/// `metric_window(…)` calls with a literal selector, and warn on family
144/// tokens outside the known namespace.
145fn lint_metric_families(src: &str, known: &[String], ctx: &str, warnings: &mut Vec<String>) {
146    for family in metric_families(src) {
147        if family.contains('{') {
148            continue; // interpolated — resolved later
149        }
150        if !known.iter().any(|k| k == &family) && !crate::adapter::adapter_publishes_family(&family)
151        {
152            warnings.push(format!(
153                "{ctx}: `metric()` selector names family '{family}', which is \
154                 not a built-in instrument family, a declared phase metric, or a \
155                 family an adapter publishes — \
156                 an unregistered family reads 0.0 silently; check the spelling \
157                 (predicate: {src})"
158            ));
159        }
160    }
161}
162
163/// Extract the family token (the first comma-separated field of the
164/// selector literal) from every `metric('…')` / `metric_window('…')`
165/// call in `src`. Non-literal selectors (an expression, not a quoted
166/// string) yield nothing — those are resolved at runtime.
167fn metric_families(src: &str) -> Vec<String> {
168    let bytes = src.as_bytes();
169    let mut out = Vec::new();
170    let mut i = 0;
171    while let Some(rel) = src[i..].find("metric") {
172        let start = i + rel;
173        i = start + "metric".len();
174        // Word boundary on the left: reject e.g. `my_metric(`.
175        if start > 0 {
176            let prev = bytes[start - 1] as char;
177            if prev.is_alphanumeric() || prev == '_' {
178                continue;
179            }
180        }
181        // Optional `_window` suffix, then `(`.
182        let mut j = i;
183        if src[j..].starts_with("_window") {
184            j += "_window".len();
185        }
186        let rest = src[j..].trim_start();
187        let Some(after_paren) = rest.strip_prefix('(') else {
188            continue;
189        };
190        let sel = after_paren.trim_start();
191        let Some(quote) = sel.chars().next().filter(|c| *c == '\'' || *c == '"') else {
192            continue; // non-literal selector
193        };
194        let body = &sel[1..];
195        let Some(end) = body.find(quote) else {
196            continue;
197        };
198        let selector = &body[..end];
199        let family = selector.split(',').next().unwrap_or("").trim().to_string();
200        if !family.is_empty() {
201            out.push(family);
202        }
203    }
204    out
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    #[test]
212    fn extracts_families_from_both_call_forms() {
213        let src = "metric('cycles_total, phase=ingest', 'count') >= 5 \
214                   && metric_window(\"result_failure\", 'rate') < 0.1";
215        assert_eq!(
216            metric_families(src),
217            vec!["cycles_total".to_string(), "result_failure".to_string()]
218        );
219    }
220
221    #[test]
222    fn ignores_non_literal_selectors_and_other_identifiers() {
223        assert!(metric_families("my_metric('x','count') + metric(fam, 'count')").is_empty());
224    }
225
226    #[test]
227    fn unknown_family_warns_known_family_does_not() {
228        let known: Vec<String> = ACTIVITY_FAMILIES.iter().map(|s| s.to_string()).collect();
229        let mut w = Vec::new();
230        lint_metric_families(
231            "metric('cycles_totl, phase=x', 'count') > 0",
232            &known,
233            "t",
234            &mut w,
235        );
236        assert_eq!(w.len(), 1, "typo'd family must warn: {w:?}");
237        w.clear();
238        lint_metric_families(
239            "metric('cycles_total, phase=x', 'count') > 0",
240            &known,
241            "t",
242            &mut w,
243        );
244        assert!(w.is_empty(), "known family must not warn: {w:?}");
245    }
246
247    #[test]
248    fn router_without_catch_all_warns_with_catch_all_does_not() {
249        let mut w = Vec::new();
250        lint_error_router("TimeoutError:retry,warn", "t", &mut w).unwrap();
251        assert_eq!(w.len(), 1, "no catch-all must warn: {w:?}");
252        w.clear();
253        lint_error_router("TimeoutError:retry,warn;.*:counter", "t", &mut w).unwrap();
254        assert!(w.is_empty(), "catch-all present must not warn: {w:?}");
255    }
256
257    #[test]
258    fn bad_router_spec_is_a_load_error_interpolated_is_deferred() {
259        let mut w = Vec::new();
260        let err = lint_error_router(".*:sotp", "phase 'p'", &mut w).unwrap_err();
261        assert!(err.contains("unknown error handler"), "got: {err}");
262        lint_error_router("{overload_policy}", "t", &mut w)
263            .expect("interpolated spec must be deferred, not parsed");
264    }
265}