1use nmbrs_workload::model::{StopConditionSpec, WorkloadPhase};
37
38const 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
63pub 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 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
123fn lint_error_router(spec: &str, ctx: &str, warnings: &mut Vec<String>) -> Result<(), String> {
127 if spec.contains('{') {
128 return Ok(()); }
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
142fn 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; }
150 if !known.iter().any(|k| k == &family) {
151 warnings.push(format!(
152 "{ctx}: `metric()` selector names family '{family}', which is \
153 not a built-in instrument family or a declared phase metric — \
154 an unregistered family reads 0.0 silently; check the spelling \
155 (predicate: {src})"
156 ));
157 }
158 }
159}
160
161fn metric_families(src: &str) -> Vec<String> {
166 let bytes = src.as_bytes();
167 let mut out = Vec::new();
168 let mut i = 0;
169 while let Some(rel) = src[i..].find("metric") {
170 let start = i + rel;
171 i = start + "metric".len();
172 if start > 0 {
174 let prev = bytes[start - 1] as char;
175 if prev.is_alphanumeric() || prev == '_' {
176 continue;
177 }
178 }
179 let mut j = i;
181 if src[j..].starts_with("_window") {
182 j += "_window".len();
183 }
184 let rest = src[j..].trim_start();
185 let Some(after_paren) = rest.strip_prefix('(') else {
186 continue;
187 };
188 let sel = after_paren.trim_start();
189 let Some(quote) = sel.chars().next().filter(|c| *c == '\'' || *c == '"') else {
190 continue; };
192 let body = &sel[1..];
193 let Some(end) = body.find(quote) else {
194 continue;
195 };
196 let selector = &body[..end];
197 let family = selector.split(',').next().unwrap_or("").trim().to_string();
198 if !family.is_empty() {
199 out.push(family);
200 }
201 }
202 out
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 #[test]
210 fn extracts_families_from_both_call_forms() {
211 let src = "metric('cycles_total, phase=ingest', 'count') >= 5 \
212 && metric_window(\"result_failure\", 'rate') < 0.1";
213 assert_eq!(
214 metric_families(src),
215 vec!["cycles_total".to_string(), "result_failure".to_string()]
216 );
217 }
218
219 #[test]
220 fn ignores_non_literal_selectors_and_other_identifiers() {
221 assert!(metric_families("my_metric('x','count') + metric(fam, 'count')").is_empty());
222 }
223
224 #[test]
225 fn unknown_family_warns_known_family_does_not() {
226 let known: Vec<String> = ACTIVITY_FAMILIES.iter().map(|s| s.to_string()).collect();
227 let mut w = Vec::new();
228 lint_metric_families(
229 "metric('cycles_totl, phase=x', 'count') > 0",
230 &known,
231 "t",
232 &mut w,
233 );
234 assert_eq!(w.len(), 1, "typo'd family must warn: {w:?}");
235 w.clear();
236 lint_metric_families(
237 "metric('cycles_total, phase=x', 'count') > 0",
238 &known,
239 "t",
240 &mut w,
241 );
242 assert!(w.is_empty(), "known family must not warn: {w:?}");
243 }
244
245 #[test]
246 fn router_without_catch_all_warns_with_catch_all_does_not() {
247 let mut w = Vec::new();
248 lint_error_router("TimeoutError:retry,warn", "t", &mut w).unwrap();
249 assert_eq!(w.len(), 1, "no catch-all must warn: {w:?}");
250 w.clear();
251 lint_error_router("TimeoutError:retry,warn;.*:counter", "t", &mut w).unwrap();
252 assert!(w.is_empty(), "catch-all present must not warn: {w:?}");
253 }
254
255 #[test]
256 fn bad_router_spec_is_a_load_error_interpolated_is_deferred() {
257 let mut w = Vec::new();
258 let err = lint_error_router(".*:sotp", "phase 'p'", &mut w).unwrap_err();
259 assert!(err.contains("unknown error handler"), "got: {err}");
260 lint_error_router("{overload_policy}", "t", &mut w)
261 .expect("interpolated spec must be deferred, not parsed");
262 }
263}