Skip to main content

speccoder_runtime/verify/
mod.rs

1//! `speccoder verify`: run the project's declared checks and judge the result.
2
3pub mod config;
4pub mod junit;
5pub mod process;
6pub mod summary;
7
8use std::path::{Path, PathBuf};
9use std::time::UNIX_EPOCH;
10
11use crate::format::Workspace;
12use speccoder_core::verify::{CheckResult, CheckStatus, VerifyReport, compare, passes};
13use speccoder_core::{CommandData, CommandResult, CommandStatus, SCHEMA_VERSION};
14
15use self::config::{Check, Tier};
16use self::process::{CommandRunner, Invocation, OUTPUT_CAP, scrubbed_env};
17
18/// Largest JUnit report read.
19const MAX_REPORT_BYTES: u64 = 64 * 1024 * 1024;
20/// Largest baseline file read.
21const MAX_BASELINE_BYTES: u64 = 64 * 1024 * 1024;
22/// Output kept in the report per stream.
23const TAIL_BYTES: usize = 4 * 1024;
24
25/// Runs the checks of the project containing `path` with `runner`.
26///
27/// `tier`: `None` runs every check; `Some(Fast)` only fast ones.
28/// `against`: a file saved from `speccoder --json verify`.
29pub fn verify(
30    path: &Path,
31    tier: Option<Tier>,
32    against: Option<&Path>,
33    runner: &dyn CommandRunner,
34) -> CommandResult {
35    let config_error = |msg: String| CommandResult::new("verify", CommandStatus::ConfigError, &msg);
36    let baseline = match against
37        .map(|p| {
38            let root = path
39                .canonicalize()
40                .ok()
41                .and_then(|p| find_config(&p))
42                .unwrap_or_default();
43            load_baseline(p, &root)
44        })
45        .transpose()
46    {
47        Ok(b) => b,
48        Err(e) => return config_error(e),
49    };
50    let mut report = match run_checks(path, tier, runner) {
51        Ok(r) => r,
52        // No check at all: add one — `init` would only say the file exists.
53        Err(e) if e.starts_with("no applicable checks") => {
54            return config_error(e).with_code("NO-CHECKS");
55        }
56        Err(e) => return config_error(e),
57    };
58    report.comparison = baseline.as_ref().map(|b| compare(b, &report));
59    report.passed = passes(&report.checks, report.comparison.as_ref());
60
61    let status = if report.passed {
62        CommandStatus::Ok
63    } else {
64        CommandStatus::VerificationFailed
65    };
66    let message = summary(&report);
67    CommandResult::new("verify", status, &message).with_data(CommandData::Verify(Box::new(report)))
68}
69
70/// Runs the applicable checks of the project containing `path` and returns
71/// the report (no comparison yet). `Err` is a configuration problem: no
72/// `speccoder.toml`, an invalid one, or nothing applicable — never a pass.
73pub fn run_checks(
74    path: &Path,
75    tier: Option<Tier>,
76    runner: &dyn CommandRunner,
77) -> Result<VerifyReport, String> {
78    let root = path.canonicalize().ok().and_then(|p| find_config(&p)).ok_or_else(|| {
79        format!(
80            "no {} at or above {}; declare checks first, e.g. [checks.test] argv = [\"cargo\", \"test\"]",
81            config::FILE,
82            path.display()
83        )
84    })?;
85    let ws = Workspace::at(&root).ok_or_else(|| format!("cannot open {}", root.display()))?;
86    let checks = ws
87        .read_text(config::FILE)
88        .map_err(|e| format!("{e:?}"))
89        .and_then(|t| config::parse(&t))
90        .map_err(|e| format!("{}: {e}", config::FILE))?;
91
92    let env = scrubbed_env(std::env::vars());
93    let results: Vec<CheckResult> = checks
94        .iter()
95        .filter(|c| tier.is_none_or(|t| c.tier == t))
96        .map(|c| {
97            rerun_once(run_check(&ws, c, &env, runner), || {
98                run_check(&ws, c, &env, runner)
99            })
100        })
101        .collect();
102    if results.iter().all(|r| r.status == CheckStatus::Skipped) {
103        return Err(format!(
104            "no applicable checks in {}{} — nothing would be verified",
105            config::FILE,
106            tier.map(|t| format!(" for tier {}", t.as_str()))
107                .unwrap_or_default()
108        ));
109    }
110    let passed = passes(&results, None);
111    Ok(VerifyReport {
112        root: ws.root().display().to_string(),
113        tier: tier.map_or("all", Tier::as_str).to_owned(),
114        checks: results,
115        comparison: None,
116        passed,
117    })
118}
119
120/// The argv of every configured check (for the command policy).
121pub fn check_argvs(root: &Path) -> Vec<Vec<String>> {
122    std::fs::read_to_string(root.join(config::FILE))
123        .ok()
124        .and_then(|t| config::parse(&t).ok())
125        .map(|cs| cs.into_iter().map(|c| c.argv).collect())
126        .unwrap_or_default()
127}
128
129/// The nearest ancestor of `start` (inclusive) holding `speccoder.toml`.
130pub fn find_config(start: &Path) -> Option<PathBuf> {
131    start
132        .ancestors()
133        .find(|d| d.join(config::FILE).is_file())
134        .map(Path::to_path_buf)
135}
136
137fn run_check(
138    ws: &Workspace,
139    check: &Check,
140    env: &[(String, String)],
141    runner: &dyn CommandRunner,
142) -> CheckResult {
143    let mut result = CheckResult {
144        name: check.name.clone(),
145        argv: check.argv.clone(),
146        status: CheckStatus::Skipped,
147        exit_code: None,
148        duration_ms: 0,
149        junit: check.junit.is_some(),
150        tests: None,
151        stdout_tail: String::new(),
152        stderr_tail: String::new(),
153        truncated: false,
154        note: None,
155        flaky: false,
156    };
157    if let Some(path) = &check.when_exists
158        && ws.resolve(path).is_err()
159    {
160        result.note = Some(format!("not applicable: {path} does not exist"));
161        return result;
162    }
163    let cwd = match ws.resolve(&check.cwd) {
164        Ok(p) if p.is_dir() => p,
165        _ => {
166            result.status = CheckStatus::Error;
167            result.note = Some(format!(
168                "cwd `{}` is not a directory inside the project",
169                check.cwd
170            ));
171            return result;
172        }
173    };
174
175    let outcome = runner.run(&Invocation {
176        argv: check.argv.clone(),
177        cwd,
178        env: env.to_vec(),
179        timeout: check.timeout,
180        output_cap: OUTPUT_CAP,
181    });
182    result.duration_ms = u64::try_from(outcome.duration.as_millis()).unwrap_or(u64::MAX);
183    result.exit_code = outcome.exit_code;
184    result.stdout_tail = tail(&outcome.stdout.kept);
185    result.stderr_tail = tail(&outcome.stderr.kept);
186    result.truncated = outcome.stdout.truncated() || outcome.stderr.truncated();
187    result.status = if let Some(e) = &outcome.spawn_error {
188        result.note = Some(e.clone());
189        CheckStatus::Error
190    } else if outcome.timed_out {
191        result.note = Some(format!("timed out after {}s", check.timeout.as_secs()));
192        CheckStatus::TimedOut
193    } else if outcome.exit_code == Some(0) {
194        CheckStatus::Passed
195    } else {
196        CheckStatus::Failed
197    };
198
199    if let Some(report) = &check.junit {
200        match fresh_report(ws, report, outcome.started) {
201            Ok(xml) => match junit::parse(&xml) {
202                Ok(tests) => result.tests = Some(tests),
203                Err(e) => result.note = Some(format!("{report}: {e}")),
204            },
205            Err(e) => {
206                result.note.get_or_insert(e);
207            }
208        }
209    }
210    result
211}
212
213/// Reads a JUnit report only if it was written by this run (not a leftover).
214fn fresh_report(
215    ws: &Workspace,
216    rel: &str,
217    started: std::time::SystemTime,
218) -> Result<String, String> {
219    let path = ws
220        .resolve(rel)
221        .map_err(|_| format!("no test report at {rel}"))?;
222    let modified = std::fs::metadata(&path)
223        .and_then(|m| m.modified())
224        .map_err(|e| format!("{rel}: {e}"))?;
225    // Allow one second of filesystem timestamp granularity.
226    let since = |t: std::time::SystemTime| {
227        t.duration_since(UNIX_EPOCH)
228            .map(|d| d.as_secs())
229            .unwrap_or(0)
230    };
231    if since(modified) + 1 < since(started) {
232        return Err(format!("{rel} predates this run; ignored"));
233    }
234    ws.read_text_limited(rel, MAX_REPORT_BYTES)
235        .map_err(|e| format!("{rel}: {e:?}"))
236}
237
238/// The last part of an output stream, without terminal escape sequences
239/// (reports are read in logs and JSON, not terminals).
240fn tail(bytes: &[u8]) -> String {
241    let start = bytes.len().saturating_sub(TAIL_BYTES);
242    strip_ansi(&String::from_utf8_lossy(&bytes[start..]))
243}
244
245/// Removes ESC sequences: CSI (`ESC [ … final`) and two-byte escapes (`ESC (B`).
246fn strip_ansi(s: &str) -> String {
247    let mut out = String::with_capacity(s.len());
248    let mut chars = s.chars().peekable();
249    while let Some(c) = chars.next() {
250        if c != '\u{1b}' {
251            out.push(c);
252            continue;
253        }
254        match chars.next() {
255            Some('[') => {
256                // Parameters and intermediates, then one final byte in @..~.
257                for c in chars.by_ref() {
258                    if ('@'..='~').contains(&c) {
259                        break;
260                    }
261                }
262            }
263            // Charset designations like `ESC ( B` carry one more byte.
264            Some(_) if chars.peek().is_some_and(char::is_ascii_alphanumeric) => {
265                chars.next();
266            }
267            Some(_) | None => {}
268        }
269    }
270    out
271}
272
273fn load_baseline(path: &Path, root: &Path) -> Result<VerifyReport, String> {
274    let bad = |why: &str| format!("baseline {}: {why}", path.display());
275    let meta = std::fs::metadata(path).map_err(|e| bad(&e.to_string()))?;
276    if meta.len() > MAX_BASELINE_BYTES {
277        return Err(bad("too large"));
278    }
279    let text = std::fs::read_to_string(path).map_err(|e| bad(&e.to_string()))?;
280    let value: serde_json::Value = serde_json::from_str(&text).map_err(|e| bad(&e.to_string()))?;
281    if value["schema_version"] != SCHEMA_VERSION || value["command"] != "verify" {
282        return Err(bad(
283            "not a `speccoder --json verify` result of schema version 1",
284        ));
285    }
286    let report: VerifyReport =
287        serde_json::from_value(value["data"].clone()).map_err(|e| bad(&e.to_string()))?;
288    if Path::new(&report.root) != root {
289        return Err(bad(&format!(
290            "recorded for {}, not this project",
291            report.root
292        )));
293    }
294    Ok(report)
295}
296
297fn summary(r: &VerifyReport) -> String {
298    let count = |s: CheckStatus| r.checks.iter().filter(|c| c.status == s).count();
299    let failed =
300        count(CheckStatus::Failed) + count(CheckStatus::TimedOut) + count(CheckStatus::Error);
301    let mut s = format!(
302        "{} passed, {failed} failed, {} skipped",
303        count(CheckStatus::Passed),
304        count(CheckStatus::Skipped)
305    );
306    if let Some(c) = &r.comparison {
307        s.push_str(&format!(
308            "; {} regressions vs baseline",
309            c.regressions.len()
310        ));
311    }
312    s
313}
314
315/// A failed check runs once more: failing again, the second run stands;
316/// passing, it is `flaky` — named, and never task evidence. Timeouts and
317/// errors are not re-run.
318pub fn rerun_once(first: CheckResult, again: impl FnOnce() -> CheckResult) -> CheckResult {
319    if first.status != CheckStatus::Failed {
320        return first;
321    }
322    let mut second = again();
323    if second.status == CheckStatus::Passed {
324        let last = format!("{}\n{}", first.stdout_tail, first.stderr_tail)
325            .lines()
326            .rev()
327            .find(|l| !l.trim().is_empty())
328            .unwrap_or_default()
329            .trim()
330            .to_owned();
331        second.flaky = true;
332        second.note = Some(if last.is_empty() {
333            "failed once, passed when run again".to_owned()
334        } else {
335            format!("failed once ({last}), passed when run again")
336        });
337    }
338    second
339}
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344
345    #[test]
346    fn strips_terminal_escapes() {
347        let colored = "\u{1b}(B\u{1b}[m\u{1b}[32m+    ] {\u{1b}[0m done";
348        assert_eq!(super::strip_ansi(colored), "+    ] { done");
349    }
350
351    #[test]
352    fn a_failed_check_runs_once_more() {
353        let result = |status: CheckStatus, out: &str| CheckResult {
354            name: "test".to_owned(),
355            argv: vec!["t".to_owned()],
356            status,
357            exit_code: None,
358            duration_ms: 0,
359            junit: false,
360            tests: None,
361            stdout_tail: out.to_owned(),
362            stderr_tail: String::new(),
363            truncated: false,
364            note: None,
365            flaky: false,
366        };
367        let passed = result(CheckStatus::Passed, "");
368        assert!(!rerun_once(passed.clone(), || unreachable!()).flaky);
369        let timed_out = result(CheckStatus::TimedOut, "");
370        assert_eq!(
371            rerun_once(timed_out, || unreachable!()).status,
372            CheckStatus::TimedOut
373        );
374        let flaky = rerun_once(result(CheckStatus::Failed, "boom\n"), || passed.clone());
375        assert!(flaky.flaky);
376        assert!(flaky.note.as_deref().unwrap().contains("boom"));
377        let twice = rerun_once(result(CheckStatus::Failed, "a"), || {
378            result(CheckStatus::Failed, "b")
379        });
380        assert_eq!((twice.flaky, twice.stdout_tail.as_str()), (false, "b"));
381    }
382}