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