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    // A report left from before (or planted) is removed: only what this
176    // run writes is read.
177    // A tracked file is never a run's report (and is never deleted).
178    let mut tracked_report = false;
179    if let Some(report) = &check.junit
180        && let Ok(path) = ws.resolve(report)
181        && path.is_file()
182    {
183        tracked_report = crate::git::Git::at(ws.root())
184            .succeeds(&["ls-files", "--error-unmatch", "--", report])
185            .unwrap_or(false);
186        if !tracked_report {
187            let _ = std::fs::remove_file(&path);
188        }
189    }
190    let outcome = runner.run(&Invocation {
191        argv: check.argv.clone(),
192        cwd,
193        env: env.to_vec(),
194        timeout: check.timeout,
195        output_cap: OUTPUT_CAP,
196    });
197    result.duration_ms = u64::try_from(outcome.duration.as_millis()).unwrap_or(u64::MAX);
198    result.exit_code = outcome.exit_code;
199    result.stdout_tail = tail(&outcome.stdout.kept);
200    result.stderr_tail = tail(&outcome.stderr.kept);
201    result.truncated = outcome.stdout.truncated() || outcome.stderr.truncated();
202    result.status = if let Some(e) = &outcome.spawn_error {
203        result.note = Some(e.clone());
204        CheckStatus::Error
205    } else if outcome.timed_out {
206        result.note = Some(format!("timed out after {}s", check.timeout.as_secs()));
207        CheckStatus::TimedOut
208    } else if outcome.exit_code == Some(0) {
209        CheckStatus::Passed
210    } else if crate::init::no_tests(
211        &check.argv,
212        outcome.exit_code,
213        &format!("{}\n{}", result.stdout_tail, result.stderr_tail),
214    ) {
215        // An empty suite (pytest's exit 5) is no tests yet, as `init` reads
216        // it — nothing to regress — like nextest's `--no-tests=warn`.
217        result.note = Some("no tests yet".to_owned());
218        CheckStatus::Passed
219    } else {
220        CheckStatus::Failed
221    };
222
223    if let Some(report) = check.junit.as_ref().filter(|_| tracked_report) {
224        result
225            .note
226            .get_or_insert(format!("{report} is tracked by git: not a run's report"));
227    } else if let Some(report) = &check.junit {
228        let finished = outcome.started + outcome.duration;
229        match fresh_report(ws, report, outcome.started, finished) {
230            Ok(xml) => match junit::parse(&xml) {
231                Ok(tests) => result.tests = Some(tests),
232                Err(e) => result.note = Some(format!("{report}: {e}")),
233            },
234            Err(e) => {
235                result.note.get_or_insert(e);
236            }
237        }
238    }
239    result
240}
241
242/// Reads a JUnit report only if it was written by this run (not a leftover).
243fn fresh_report(
244    ws: &Workspace,
245    rel: &str,
246    started: std::time::SystemTime,
247    finished: std::time::SystemTime,
248) -> Result<String, String> {
249    let path = ws
250        .resolve(rel)
251        .map_err(|_| format!("no test report at {rel}"))?;
252    let modified = std::fs::metadata(&path)
253        .and_then(|m| m.modified())
254        .map_err(|e| format!("{rel}: {e}"))?;
255    // Allow one second of filesystem timestamp granularity.
256    let since = |t: std::time::SystemTime| {
257        t.duration_since(UNIX_EPOCH)
258            .map(|d| d.as_secs())
259            .unwrap_or(0)
260    };
261    if since(modified) + 1 < since(started) {
262        return Err(format!("{rel} predates this run; ignored"));
263    }
264    // Written after the run ended: not the run's report.
265    if since(modified) > since(finished) + 1 {
266        return Err(format!("{rel} is dated after this run ended; ignored"));
267    }
268    ws.read_text_limited(rel, MAX_REPORT_BYTES)
269        .map_err(|e| format!("{rel}: {e:?}"))
270}
271
272/// The last part of an output stream, without terminal escape sequences
273/// (reports are read in logs and JSON, not terminals).
274fn tail(bytes: &[u8]) -> String {
275    let start = bytes.len().saturating_sub(TAIL_BYTES);
276    strip_ansi(&String::from_utf8_lossy(&bytes[start..]))
277}
278
279/// Removes ESC sequences: CSI (`ESC [ … final`) and two-byte escapes (`ESC (B`).
280fn strip_ansi(s: &str) -> String {
281    let mut out = String::with_capacity(s.len());
282    let mut chars = s.chars().peekable();
283    while let Some(c) = chars.next() {
284        if c != '\u{1b}' {
285            out.push(c);
286            continue;
287        }
288        match chars.next() {
289            Some('[') => {
290                // Parameters and intermediates, then one final byte in @..~.
291                for c in chars.by_ref() {
292                    if ('@'..='~').contains(&c) {
293                        break;
294                    }
295                }
296            }
297            // Charset designations like `ESC ( B` carry one more byte.
298            Some(_) if chars.peek().is_some_and(char::is_ascii_alphanumeric) => {
299                chars.next();
300            }
301            Some(_) | None => {}
302        }
303    }
304    out
305}
306
307fn load_baseline(path: &Path, root: &Path) -> Result<VerifyReport, String> {
308    let bad = |why: &str| format!("baseline {}: {why}", path.display());
309    let meta = std::fs::metadata(path).map_err(|e| bad(&e.to_string()))?;
310    if meta.len() > MAX_BASELINE_BYTES {
311        return Err(bad("too large"));
312    }
313    let text = std::fs::read_to_string(path).map_err(|e| bad(&e.to_string()))?;
314    let value: serde_json::Value = serde_json::from_str(&text).map_err(|e| bad(&e.to_string()))?;
315    if value["schema_version"] != SCHEMA_VERSION || value["command"] != "verify" {
316        return Err(bad(
317            "not a `speccoder --json verify` result of schema version 1",
318        ));
319    }
320    let report: VerifyReport =
321        serde_json::from_value(value["data"].clone()).map_err(|e| bad(&e.to_string()))?;
322    if Path::new(&report.root) != root {
323        return Err(bad(&format!(
324            "recorded for {}, not this project",
325            report.root
326        )));
327    }
328    Ok(report)
329}
330
331fn summary(r: &VerifyReport) -> String {
332    let count = |s: CheckStatus| r.checks.iter().filter(|c| c.status == s).count();
333    let failed =
334        count(CheckStatus::Failed) + count(CheckStatus::TimedOut) + count(CheckStatus::Error);
335    let mut s = format!(
336        "{} passed, {failed} failed, {} skipped",
337        count(CheckStatus::Passed),
338        count(CheckStatus::Skipped)
339    );
340    if let Some(c) = &r.comparison {
341        s.push_str(&format!(
342            "; {} regressions vs baseline",
343            c.regressions.len()
344        ));
345    }
346    s
347}
348
349/// A failed check runs once more: failing again, the second run stands;
350/// passing, it is `flaky` — named, and never task evidence. Timeouts and
351/// errors are not re-run.
352pub fn rerun_once(first: CheckResult, again: impl FnOnce() -> CheckResult) -> CheckResult {
353    if first.status != CheckStatus::Failed {
354        return first;
355    }
356    let mut second = again();
357    if second.status == CheckStatus::Passed {
358        let last = format!("{}\n{}", first.stdout_tail, first.stderr_tail)
359            .lines()
360            .rev()
361            .find(|l| !l.trim().is_empty())
362            .unwrap_or_default()
363            .trim()
364            .to_owned();
365        second.flaky = true;
366        second.note = Some(if last.is_empty() {
367            "failed once, passed when run again".to_owned()
368        } else {
369            format!("failed once ({last}), passed when run again")
370        });
371    }
372    second
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    #[test]
380    fn strips_terminal_escapes() {
381        let colored = "\u{1b}(B\u{1b}[m\u{1b}[32m+    ] {\u{1b}[0m done";
382        assert_eq!(super::strip_ansi(colored), "+    ] { done");
383    }
384
385    #[test]
386    fn a_failed_check_runs_once_more() {
387        let result = |status: CheckStatus, out: &str| CheckResult {
388            name: "test".to_owned(),
389            argv: vec!["t".to_owned()],
390            status,
391            exit_code: None,
392            duration_ms: 0,
393            junit: false,
394            tests: None,
395            stdout_tail: out.to_owned(),
396            stderr_tail: String::new(),
397            truncated: false,
398            note: None,
399            flaky: false,
400        };
401        let passed = result(CheckStatus::Passed, "");
402        assert!(!rerun_once(passed.clone(), || unreachable!()).flaky);
403        let timed_out = result(CheckStatus::TimedOut, "");
404        assert_eq!(
405            rerun_once(timed_out, || unreachable!()).status,
406            CheckStatus::TimedOut
407        );
408        let flaky = rerun_once(result(CheckStatus::Failed, "boom\n"), || passed.clone());
409        assert!(flaky.flaky);
410        assert!(flaky.note.as_deref().unwrap().contains("boom"));
411        let twice = rerun_once(result(CheckStatus::Failed, "a"), || {
412            result(CheckStatus::Failed, "b")
413        });
414        assert_eq!((twice.flaky, twice.stdout_tail.as_str()), (false, "b"));
415    }
416}