Skip to main content

vitrify_cli/incremental/
blame.rs

1//! No new failures: a gate blames a batch only for rows that pass on the base.
2//!
3//! When Verification rows fail at a gate or a re-check, those rows run again
4//! on the base — the commit the batch was merged onto — in a pristine
5//! checkout of it:
6//!
7//! * **they pass on the base:** the batch broke them. The batch is rejected,
8//!   as it always was;
9//! * **they fail on the base too:** the batch did not break them. Their
10//!   units are **rotten** — something already on mainline broke them, or the
11//!   rows are flaky, which culprit finding ([`super::culprit`]) sorts out —
12//!   and the batch is judged on its other rows.
13//!
14//! This is the rule the gate already applies to the §5 Test command, applied
15//! per row. A row that failed beside others is run again alone before it
16//! counts as failed at all (`gate::run_rows`); that stays where it is, and
17//! only confirmed failures come here.
18//!
19//! The base is prepared the way every gate tree is: reset to the commit with
20//! no untracked or ignored file left ([`PristineCheckout`]), then the SDD's
21//! §5 Bootstrap and Build, then the failed rows one at a time. When the base
22//! itself cannot be set up (its Bootstrap or Build fails), nothing can be
23//! said about the rows there, and the batch is blamed for all of them — the
24//! conservative answer, and the one a gate gave before this rule existed.
25//!
26//! [`classify`] is the pure rule; [`judge`] runs the base and applies it.
27//! Both take what they run through two small injected pieces: a [`Runner`]
28//! (one §5 command or Verification row in a directory) and a [`Prepare`]
29//! (a pristine checkout at a commit).
30
31use std::collections::{BTreeMap, BTreeSet};
32use std::path::{Path, PathBuf};
33
34use vitrify_core::CoreError;
35use vitrify_core::graph::Node;
36
37use crate::gate::{self, Ran};
38use crate::git::Git;
39
40/// Runs one §5 command or one Verification row (through `sh -c`) in a
41/// directory. Shared by gates, re-checks and culprit probes.
42pub trait Runner: Send + Sync {
43    fn run(&self, cmd: &str, dir: &Path) -> Ran;
44}
45
46/// The runner a run uses: `gate::run_command` (its own temp slot, its own
47/// process group, stopped on interrupt).
48pub struct ShellRunner;
49
50impl Runner for ShellRunner {
51    fn run(&self, cmd: &str, dir: &Path) -> Ran {
52        gate::run_command(cmd, dir)
53    }
54}
55
56impl<F> Runner for F
57where
58    F: Fn(&str, &Path) -> Ran + Send + Sync,
59{
60    fn run(&self, cmd: &str, dir: &Path) -> Ran {
61        self(cmd, dir)
62    }
63}
64
65/// Makes a pristine checkout at a commit: the tree of `commit`, with no
66/// untracked or ignored file left. Returns the checkout's directory.
67pub trait Prepare: Send + Sync {
68    fn prepare(&self, commit: &str) -> Result<PathBuf, CoreError>;
69}
70
71/// The default [`Prepare`]: one detached git worktree at `path`, dedicated
72/// to one use (a lane's base checks, a lane's culprit probes), reset before
73/// every use with `reset --hard <commit>` and `clean -ffdx`. Only caches
74/// outside the checkout survive. Created on first use; a checkout that
75/// cannot be reset — a stale `index.lock` left by a killed process, a
76/// half-removed directory, one deleted while git still lists it — is
77/// removed and created again.
78#[derive(Debug, Clone)]
79pub struct PristineCheckout {
80    /// Any checkout of the repository: the worktree is added from it.
81    pub primary: Git,
82    pub path: PathBuf,
83}
84
85impl PristineCheckout {
86    pub fn new(primary: Git, path: impl Into<PathBuf>) -> PristineCheckout {
87        PristineCheckout {
88            primary,
89            path: path.into(),
90        }
91    }
92
93    fn reset(&self, commit: &str) -> Result<(), CoreError> {
94        let wt = self.primary.at(&self.path);
95        // an interrupted merge would refuse the reset
96        let _ = wt.merge_abort();
97        wt.reset_hard(commit).map_err(CoreError::from)?;
98        wt.clean_all().map_err(CoreError::from)
99    }
100
101    fn create(&self, commit: &str) -> Result<(), CoreError> {
102        if let Some(parent) = self.path.parent() {
103            fs_err::create_dir_all(parent).map_err(|e| CoreError::Io {
104                path: parent.to_path_buf(),
105                source: e,
106            })?;
107        }
108        self.primary
109            .worktree_add(&self.path, commit, true)
110            .map_err(CoreError::from)
111    }
112}
113
114impl Prepare for PristineCheckout {
115    fn prepare(&self, commit: &str) -> Result<PathBuf, CoreError> {
116        if self.path.join(".git").exists() && self.reset(commit).is_ok() {
117            return Ok(self.path.clone());
118        }
119        // Missing, or beyond resetting: start over. A directory deleted
120        // behind git's back is still registered as a worktree, and `worktree
121        // add` refuses it until it is pruned: removing the registration
122        // (or, where `remove` fails, pruning) comes first either way.
123        self.primary
124            .worktree_remove(&self.path)
125            .map_err(CoreError::from)?;
126        if self.path.exists() {
127            fs_err::remove_dir_all(&self.path).map_err(|e| CoreError::Io {
128                path: self.path.clone(),
129                source: e,
130            })?;
131        }
132        self.create(commit)?;
133        self.reset(commit)?;
134        Ok(self.path.clone())
135    }
136}
137
138/// One failed row's run on the base.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct OnBase {
141    pub row: String,
142    pub passed: bool,
143    /// The tail of its output there.
144    pub output: String,
145}
146
147/// What a set of failed rows says about the batch.
148#[derive(Debug, Clone, Default, PartialEq, Eq)]
149pub struct Verdict {
150    /// Rows that pass on the base: the batch broke them. Non-empty means the
151    /// batch is rejected. In the order given.
152    pub broken: Vec<String>,
153    /// Rows that fail on the base too, in the order given.
154    pub rotten_rows: Vec<String>,
155    /// The units each rotten row belongs to: rotten units, sorted, each
156    /// with its rotten rows in the order given.
157    pub rotten: BTreeMap<Node, Vec<String>>,
158    /// Why the base could not judge the rows, when it could not (its setup
159    /// failed); every row is then blamed on the batch.
160    pub base_unusable: Option<String>,
161}
162
163impl Verdict {
164    /// Whether the batch broke nothing: every failed row fails on the base
165    /// too.
166    pub fn batch_clean(&self) -> bool {
167        self.broken.is_empty()
168    }
169}
170
171/// The rule, pure. `failed` are the rows that failed (confirmed) at the gate
172/// or re-check, each distinct command once; `rows` gives each unit's rows,
173/// so the units of a rotten row can be named; `passed_on_base` answers for
174/// each failed row. A row `passed_on_base` does not answer for counts as
175/// passing there: the batch is blamed, the conservative side.
176pub fn classify(
177    failed: &[String],
178    rows: &BTreeMap<Node, Vec<String>>,
179    passed_on_base: &BTreeMap<String, bool>,
180) -> Verdict {
181    let mut out = Verdict::default();
182    let mut seen: BTreeSet<&str> = BTreeSet::new();
183    for row in failed {
184        if !seen.insert(row) {
185            continue;
186        }
187        if passed_on_base.get(row).copied().unwrap_or(true) {
188            out.broken.push(row.clone());
189        } else {
190            out.rotten_rows.push(row.clone());
191        }
192    }
193    for (node, unit_rows) in rows {
194        let mine: Vec<String> = out
195            .rotten_rows
196            .iter()
197            .filter(|r| unit_rows.contains(r))
198            .cloned()
199            .collect();
200        if !mine.is_empty() {
201            out.rotten.insert(node.clone(), mine);
202        }
203    }
204    out
205}
206
207/// What [`judge`] found: the verdict and each row's run on the base, or an
208/// interrupt.
209#[derive(Debug, Clone, PartialEq, Eq)]
210pub enum Judged {
211    Done {
212        verdict: Verdict,
213        on_base: Vec<OnBase>,
214    },
215    /// The run was interrupted while the base was being checked: nothing is
216    /// decided.
217    Interrupted,
218}
219
220/// Run the `failed` rows again on `base`: prepare the pristine checkout at
221/// `base`, run `setup` (the §5 Bootstrap and Build, those the SDD declares,
222/// in order), then each failed row once, one at a time; and [`classify`].
223/// Takes gate-pool capacity for its commands like any gate does — the
224/// caller's to account. Leaves the checkout at `base` as the rows left it;
225/// the next [`Prepare::prepare`] cleans it.
226pub fn judge(
227    failed: &[String],
228    rows: &BTreeMap<Node, Vec<String>>,
229    base: &str,
230    setup: &[String],
231    prepare: &dyn Prepare,
232    runner: &dyn Runner,
233) -> Result<Judged, CoreError> {
234    let distinct: Vec<String> = {
235        let mut seen = BTreeSet::new();
236        failed
237            .iter()
238            .filter(|r| seen.insert(r.as_str()))
239            .cloned()
240            .collect()
241    };
242    if distinct.is_empty() {
243        return Ok(Judged::Done {
244            verdict: Verdict::default(),
245            on_base: Vec::new(),
246        });
247    }
248    let dir = prepare.prepare(base)?;
249    for cmd in setup {
250        let ran = runner.run(cmd, &dir);
251        if ran.interrupted {
252            return Ok(Judged::Interrupted);
253        }
254        if !ran.ok() {
255            let why = format!("`{cmd}` failed on the base (exit {})", ran.code);
256            let mut verdict = classify(&distinct, rows, &BTreeMap::new());
257            verdict.base_unusable = Some(why);
258            return Ok(Judged::Done {
259                verdict,
260                on_base: Vec::new(),
261            });
262        }
263    }
264    let mut on_base = Vec::new();
265    let mut passed: BTreeMap<String, bool> = BTreeMap::new();
266    for row in &distinct {
267        let ran = runner.run(row, &dir);
268        if ran.interrupted {
269            return Ok(Judged::Interrupted);
270        }
271        passed.insert(row.clone(), ran.ok());
272        on_base.push(OnBase {
273            row: row.clone(),
274            passed: ran.ok(),
275            output: ran.output,
276        });
277    }
278    Ok(Judged::Done {
279        verdict: classify(&distinct, rows, &passed),
280        on_base,
281    })
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use std::sync::Mutex;
288
289    fn ran(code: i32) -> Ran {
290        Ran {
291            code,
292            output: format!("exit {code}"),
293            interrupted: false,
294        }
295    }
296
297    fn rows() -> BTreeMap<Node, Vec<String>> {
298        let mut m = BTreeMap::new();
299        m.insert(
300            Node::new("api", "U-001"),
301            vec!["row-a".to_string(), "row-b".to_string()],
302        );
303        m.insert(Node::new("api", "U-002"), vec!["row-b".to_string()]);
304        m.insert(Node::new("core", "U-001"), vec!["row-c".to_string()]);
305        m
306    }
307
308    /// A preparer that hands out one directory and counts its calls.
309    struct Fixed(Mutex<Vec<String>>);
310
311    impl Prepare for Fixed {
312        fn prepare(&self, commit: &str) -> Result<PathBuf, CoreError> {
313            self.0.lock().unwrap().push(commit.to_string());
314            Ok(PathBuf::from("/nowhere"))
315        }
316    }
317
318    /// A scripted runner: a command passes unless listed as failing; every
319    /// call is logged.
320    struct Script {
321        failing: Vec<&'static str>,
322        interrupt: Option<&'static str>,
323        log: Mutex<Vec<String>>,
324    }
325
326    impl Runner for Script {
327        fn run(&self, cmd: &str, _dir: &Path) -> Ran {
328            self.log.lock().unwrap().push(cmd.to_string());
329            if self.interrupt == Some(cmd) {
330                return Ran {
331                    code: -1,
332                    output: String::new(),
333                    interrupted: true,
334                };
335            }
336            ran(if self.failing.contains(&cmd) { 1 } else { 0 })
337        }
338    }
339
340    fn script(failing: &[&'static str]) -> Script {
341        Script {
342            failing: failing.to_vec(),
343            interrupt: None,
344            log: Mutex::new(Vec::new()),
345        }
346    }
347
348    #[test]
349    fn a_row_that_passes_on_the_base_is_the_batchs() {
350        let base: BTreeMap<String, bool> = [("row-a".to_string(), true)].into();
351        let v = classify(&["row-a".to_string()], &rows(), &base);
352        assert_eq!(v.broken, vec!["row-a"]);
353        assert!(v.rotten.is_empty());
354        assert!(!v.batch_clean());
355    }
356
357    #[test]
358    fn a_row_that_fails_on_the_base_makes_every_unit_it_belongs_to_rotten() {
359        let base: BTreeMap<String, bool> =
360            [("row-b".to_string(), false), ("row-c".to_string(), true)].into();
361        let v = classify(&["row-b".to_string(), "row-c".to_string()], &rows(), &base);
362        assert_eq!(v.broken, vec!["row-c"]);
363        assert_eq!(v.rotten_rows, vec!["row-b"]);
364        assert_eq!(
365            v.rotten.keys().cloned().collect::<Vec<_>>(),
366            vec![Node::new("api", "U-001"), Node::new("api", "U-002")]
367        );
368        assert_eq!(v.rotten[&Node::new("api", "U-001")], vec!["row-b"]);
369    }
370
371    #[test]
372    fn only_rotten_rows_leave_the_batch_clean() {
373        let base: BTreeMap<String, bool> = [("row-c".to_string(), false)].into();
374        let v = classify(&["row-c".to_string(), "row-c".to_string()], &rows(), &base);
375        assert!(v.batch_clean());
376        assert_eq!(v.rotten_rows, vec!["row-c"]);
377        assert_eq!(
378            v.rotten.keys().cloned().collect::<Vec<_>>(),
379            vec![Node::new("core", "U-001")]
380        );
381    }
382
383    #[test]
384    fn a_row_with_no_answer_from_the_base_is_blamed_on_the_batch() {
385        let v = classify(&["row-a".to_string()], &rows(), &BTreeMap::new());
386        assert_eq!(v.broken, vec!["row-a"]);
387    }
388
389    #[test]
390    fn judge_runs_setup_then_each_failed_row_once_on_the_base() {
391        let prep = Fixed(Mutex::new(Vec::new()));
392        let run = script(&["row-b"]);
393        let failed = vec![
394            "row-a".to_string(),
395            "row-b".to_string(),
396            "row-a".to_string(),
397        ];
398        let setup = vec!["bootstrap".to_string(), "build".to_string()];
399        let Judged::Done { verdict, on_base } =
400            judge(&failed, &rows(), "base1", &setup, &prep, &run).unwrap()
401        else {
402            panic!("interrupted");
403        };
404        assert_eq!(*prep.0.lock().unwrap(), vec!["base1"]);
405        assert_eq!(
406            *run.log.lock().unwrap(),
407            vec!["bootstrap", "build", "row-a", "row-b"]
408        );
409        assert_eq!(verdict.broken, vec!["row-a"]);
410        assert_eq!(verdict.rotten_rows, vec!["row-b"]);
411        assert_eq!(on_base.len(), 2);
412        assert!(on_base[0].passed && !on_base[1].passed);
413    }
414
415    #[test]
416    fn a_base_that_does_not_build_blames_the_batch() {
417        let prep = Fixed(Mutex::new(Vec::new()));
418        let run = script(&["build", "row-a"]);
419        let setup = vec!["build".to_string()];
420        let Judged::Done { verdict, .. } =
421            judge(&["row-a".to_string()], &rows(), "b", &setup, &prep, &run).unwrap()
422        else {
423            panic!("interrupted");
424        };
425        assert_eq!(verdict.broken, vec!["row-a"]);
426        assert!(verdict.base_unusable.unwrap().contains("`build` failed"));
427        assert_eq!(*run.log.lock().unwrap(), vec!["build"]);
428    }
429
430    #[test]
431    fn an_interrupt_decides_nothing() {
432        let prep = Fixed(Mutex::new(Vec::new()));
433        let mut run = script(&[]);
434        run.interrupt = Some("row-a");
435        let j = judge(&["row-a".to_string()], &rows(), "b", &[], &prep, &run).unwrap();
436        assert_eq!(j, Judged::Interrupted);
437    }
438
439    #[test]
440    fn nothing_failed_runs_nothing() {
441        let prep = Fixed(Mutex::new(Vec::new()));
442        let run = script(&[]);
443        let j = judge(&[], &rows(), "b", &["build".to_string()], &prep, &run).unwrap();
444        assert!(matches!(j, Judged::Done { verdict, .. } if verdict.batch_clean()));
445        assert!(prep.0.lock().unwrap().is_empty());
446        assert!(run.log.lock().unwrap().is_empty());
447    }
448}