Skip to main content

vitrify_cli/incremental/
culprit.rs

1//! Culprit finding for rotten units: probes in a pristine checkout.
2//!
3//! A unit is rotten when one of its Verification rows fails on the base too
4//! ([`super::blame`]): the batch at hand did not break it, so something
5//! already on mainline did — or the row is flaky. [`find`] runs
6//! flake-aware culprit finding ([`vitrify_core::facf`]) over the commits in
7//! between and reports a culprit commit, a flake, or no conclusion.
8//!
9//! # Candidates
10//!
11//! The candidates are the mainline commits after the unit's **anchor** — the
12//! commit of its latest `verified` journal event, where the row last passed
13//! — up to and including the base, oldest first. They are taken from the
14//! **first-parent** history of the base. Mainline moves only by integration
15//! (`--no-ff` merges of attempt branches, then the integration commit),
16//! re-check commits and claim transactions, so its first-parent chain is
17//! exactly the sequence of trees mainline has held. The commits inside a
18//! merged attempt branch never were mainline: they are a worker's partial
19//! states, often unbuildable, and probing them would blame a step of a
20//! worker's session rather than the integration that landed it. A merge is
21//! judged by its diff against its first parent — everything the integration
22//! brought in.
23//!
24//! # Prior
25//!
26//! Each candidate's own diff against its first parent goes through the
27//! re-check cascade ([`cascade::dirty_set`]) with the unit's closure and the
28//! repository's [`Ownership`]: a candidate is **touched** when it changed a
29//! path the unit is checked against. [`facf::Search::from_touched`] gives
30//! touched candidates almost all of the prior and every other candidate a
31//! small share, so a culprit that reached the unit through an undeclared
32//! dependency is still found, only later.
33//!
34//! # Probes
35//!
36//! Each probe prepares the pristine probe checkout at the candidate (reset,
37//! no untracked or ignored file), runs the SDD's §5 Bootstrap and Build
38//! there, then the row, all through the injected [`Runner`], and feeds the
39//! row's pass or fail to the search, until it concludes or its budget is
40//! spent. A probe whose Bootstrap or Build fails cannot run the row; it is
41//! **counted as a failure of the row**, with a note. A tree that does not
42//! build fails every row run on it, so that is what the row would have
43//! done; and the search's flake model absorbs a setup that failed only by
44//! chance, as it absorbs any spurious failure. Skipping the version instead
45//! would leave the search choosing it again. When the search ends the
46//! checkout is prepared once more at the base, so it is left pristine.
47//!
48//! # Running it
49//!
50//! [`find`] blocks for as long as its probes take. It is meant for a thread
51//! of its own, off the critical path: the rotten unit and its dependents
52//! wait either way. Give each lane its own probe checkout
53//! (`<worktrees>/probe-<slug>` by default, [`probe_checkout`]), never the
54//! lane's integration checkout, and count each probe command against the
55//! gate pool as the caller does for gate commands.
56
57use std::collections::BTreeSet;
58use std::path::{Path, PathBuf};
59
60use vitrify_core::CoreError;
61use vitrify_core::cascade::{self, Candidate, Closures, Owner, Ownership};
62use vitrify_core::facf::{self, Hypothesis, Search, Verdict};
63use vitrify_core::graph::Node;
64
65use super::blame::{Prepare, Runner};
66use crate::git::Git;
67
68/// The default probe checkout of the lane `slug`, under the worktree root.
69pub fn probe_checkout(worktrees: &Path, slug: &str) -> PathBuf {
70    worktrees.join(format!("probe-{slug}"))
71}
72
73/// A rotten unit's failing row, and where to search.
74#[derive(Debug, Clone)]
75pub struct Rotten<'a> {
76    pub node: &'a Node,
77    /// The row's 1-based position in the unit's Verification table, as the
78    /// report names it.
79    pub row_number: usize,
80    /// The row's command.
81    pub row: &'a str,
82    /// The unit's anchor: the commit of its latest `verified` event.
83    pub anchor: &'a str,
84    /// The base the row failed on.
85    pub base: &'a str,
86}
87
88/// How to probe.
89pub struct Probe<'a> {
90    /// Any checkout of the repository, to read history from.
91    pub git: &'a Git,
92    pub ownership: &'a Ownership,
93    /// The dependency closures; the rotten unit's entry is the one used.
94    pub closures: &'a Closures,
95    /// The SDD's §5 Bootstrap and Build, those it declares, in order.
96    pub setup: &'a [String],
97    pub prepare: &'a dyn Prepare,
98    pub runner: &'a dyn Runner,
99    pub config: facf::Config,
100}
101
102/// A commit named as the culprit (or the most likely one).
103#[derive(Debug, Clone, PartialEq)]
104pub struct Culprit {
105    pub sha: String,
106    pub short: String,
107    pub subject: String,
108    /// The units it integrated (from an `sdd: integrate …` message), or else
109    /// the units owning paths it changed; sorted.
110    pub upstream: Vec<Node>,
111    /// Whether `upstream` comes from an integration message.
112    pub integrated: bool,
113    pub probability: f64,
114}
115
116impl Culprit {
117    /// `core U-004 integrated`, `changed core U-004`, or the subject.
118    pub fn describe(&self) -> String {
119        let units = self
120            .upstream
121            .iter()
122            .map(|n| n.to_string())
123            .collect::<Vec<_>>()
124            .join(", ");
125        match (self.upstream.is_empty(), self.integrated) {
126            (true, _) => format!("\"{}\"", self.subject),
127            (false, true) => format!("{units} integrated"),
128            (false, false) => format!("changed {units}"),
129        }
130    }
131}
132
133/// What the search concluded.
134#[derive(Debug, Clone, PartialEq)]
135pub enum Finding {
136    /// This commit broke the row.
137    Culprit(Culprit),
138    /// No commit broke the row: it is flaky. The unit is re-checked again
139    /// later; the project should fix the row.
140    Flake { probability: f64 },
141    /// No confident conclusion within the budget (or no candidate at all);
142    /// `best` is the most likely culprit, when a commit is the most likely
143    /// hypothesis.
144    Inconclusive {
145        best: Option<Culprit>,
146        probability: f64,
147    },
148    /// The run was interrupted mid-search.
149    Interrupted,
150}
151
152/// One culprit search's report.
153#[derive(Debug, Clone, PartialEq)]
154pub struct Report {
155    pub node: Node,
156    pub row_number: usize,
157    pub row: String,
158    pub finding: Finding,
159    /// Candidate commits searched, and how many of them were touched.
160    pub candidates: usize,
161    pub touched: usize,
162    pub probes: usize,
163    /// Probes that could not run the row (setup failed), one line each.
164    pub notes: Vec<String>,
165}
166
167impl Report {
168    /// One line naming the unit, e.g. `api U-002 row 2 broke at a1b2c3d
169    /// (core U-004 integrated) — culprit found`.
170    pub fn line(&self) -> String {
171        format!("{} {}", self.node, self.finding_line())
172    }
173
174    /// The finding without the unit, for where the unit is already given,
175    /// e.g. `row 2 broke at a1b2c3d (core U-004 integrated) — culprit found`.
176    pub fn finding_line(&self) -> String {
177        let who = format!("row {}", self.row_number);
178        match &self.finding {
179            Finding::Culprit(c) => {
180                format!(
181                    "{who} broke at {} ({}) — culprit found",
182                    c.short,
183                    c.describe()
184                )
185            }
186            Finding::Flake { .. } => format!(
187                "{who} is flaky: no commit since its last check broke it — fix the row (`{}`); the unit is re-checked again",
188                self.row
189            ),
190            Finding::Inconclusive { best, .. } => match best {
191                Some(c) => format!(
192                    "{who} broke, culprit not found after {} probes (most likely {}, {}) — inconclusive",
193                    self.probes,
194                    c.short,
195                    c.describe()
196                ),
197                None if self.candidates == 0 && !self.notes.is_empty() => format!(
198                    "{who} broke, culprit not searched ({}) — inconclusive",
199                    self.notes.join("; ")
200                ),
201                None if self.candidates == 0 => format!(
202                    "{who} fails at its own last check — no commit to search — inconclusive"
203                ),
204                None => format!(
205                    "{who} broke, culprit not found after {} probes (most likely flaky) — inconclusive",
206                    self.probes
207                ),
208            },
209            Finding::Interrupted => format!("{who}: culprit search interrupted"),
210        }
211    }
212}
213
214/// Search for the commit that broke `rotten.row`. See the module doc for the
215/// candidates, the prior and the probes. Errors on git failures and a probe
216/// checkout that cannot be prepared.
217pub fn find(rotten: &Rotten<'_>, probe: &Probe<'_>) -> Result<Report, CoreError> {
218    let git = probe.git;
219    let mut report = Report {
220        node: rotten.node.clone(),
221        row_number: rotten.row_number,
222        row: rotten.row.to_string(),
223        finding: Finding::Inconclusive {
224            best: None,
225            probability: 0.0,
226        },
227        candidates: 0,
228        touched: 0,
229        probes: 0,
230        notes: Vec::new(),
231    };
232    // A recorded anchor is an abbreviated sha: peeled to a commit, so a
233    // prefix that a blob or tree shares is not ambiguous.
234    let Some(anchor) = git.resolve_commit(rotten.anchor).map_err(CoreError::from)? else {
235        report.notes.push(format!(
236            "its recorded anchor {} names no commit here",
237            rotten.anchor
238        ));
239        return Ok(report);
240    };
241    let base = git.rev_parse(rotten.base).map_err(CoreError::from)?;
242    let commits = git
243        .first_parent_range(&anchor, &base)
244        .map_err(CoreError::from)?;
245    report.candidates = commits.len();
246    if commits.is_empty() {
247        return Ok(report);
248    }
249
250    // the prior: which candidates changed a path the unit is checked against
251    let closure: BTreeSet<Node> = probe.closures.get(rotten.node).cloned().unwrap_or_default();
252    let closures: Closures = [(rotten.node.clone(), closure)].into();
253    let mut diffs: Vec<Vec<String>> = Vec::with_capacity(commits.len());
254    let mut touched: Vec<bool> = Vec::with_capacity(commits.len());
255    for c in &commits {
256        let parent = format!("{c}^1");
257        let paths = git.changed_paths(&parent, c).map_err(CoreError::from)?;
258        let changes: cascade::Changes = [(parent.clone(), paths.clone())].into();
259        let cand = [Candidate {
260            node: rotten.node.clone(),
261            anchor: Some(parent),
262        }];
263        touched.push(!cascade::dirty_set(&cand, &changes, &closures, probe.ownership).is_empty());
264        diffs.push(paths);
265    }
266    report.touched = touched.iter().filter(|&&t| t).count();
267    let mut search = Search::from_touched(&touched, &probe.config)
268        .map_err(|e| CoreError::refusal(1, format!("error: culprit search: {e}")))?;
269
270    let mut interrupted = false;
271    while let Some(version) = search.next_probe() {
272        let commit = &commits[version];
273        let dir = probe.prepare.prepare(commit)?;
274        let Some(passed) = run_probe(probe, &dir, rotten.row, commit, &mut report.notes) else {
275            interrupted = true;
276            break;
277        };
278        search
279            .observe(version, passed)
280            .map_err(|e| CoreError::refusal(1, format!("error: culprit search: {e}")))?;
281    }
282    report.probes = search.probes_used();
283    // leave the probe checkout pristine, at the base
284    probe.prepare.prepare(&base)?;
285
286    let culprit = |index: usize, probability: f64| -> Result<Culprit, CoreError> {
287        describe(
288            git,
289            probe.ownership,
290            &commits[index],
291            &diffs[index],
292            probability,
293        )
294    };
295    report.finding = if interrupted {
296        Finding::Interrupted
297    } else {
298        match search.verdict() {
299            Verdict::Culprit { index, probability } => {
300                Finding::Culprit(culprit(index, probability)?)
301            }
302            Verdict::Flake { probability } => Finding::Flake { probability },
303            Verdict::Inconclusive { best, probability } => Finding::Inconclusive {
304                best: match best {
305                    Hypothesis::Commit(index) => Some(culprit(index, probability)?),
306                    Hypothesis::NoCulprit => None,
307                },
308                probability,
309            },
310            // invariant: the loop ends only once the search is not Searching
311            Verdict::Searching => Finding::Inconclusive {
312                best: None,
313                probability: 0.0,
314            },
315        }
316    };
317    Ok(report)
318}
319
320/// One probe in the prepared checkout `dir`: setup, then the row. `None`
321/// when interrupted; a failed setup counts as a failure of the row.
322fn run_probe(
323    probe: &Probe<'_>,
324    dir: &Path,
325    row: &str,
326    commit: &str,
327    notes: &mut Vec<String>,
328) -> Option<bool> {
329    for cmd in probe.setup {
330        let ran = probe.runner.run(cmd, dir);
331        if ran.interrupted {
332            return None;
333        }
334        if !ran.ok() {
335            notes.push(format!(
336                "`{cmd}` failed at {} (exit {}): counted as a failure of the row",
337                &commit[..7.min(commit.len())],
338                ran.code
339            ));
340            return Some(false);
341        }
342    }
343    let ran = probe.runner.run(row, dir);
344    if ran.interrupted {
345        return None;
346    }
347    Some(ran.ok())
348}
349
350/// Name a commit: short sha, subject, and the upstream units it changed.
351fn describe(
352    git: &Git,
353    ownership: &Ownership,
354    sha: &str,
355    paths: &[String],
356    probability: f64,
357) -> Result<Culprit, CoreError> {
358    let subject = git.subject(sha).map_err(CoreError::from)?;
359    let short = git.short_sha(sha).map_err(CoreError::from)?;
360    let mut owners: BTreeSet<Node> = BTreeSet::new();
361    let mut spec_slugs: BTreeSet<String> = BTreeSet::new();
362    for p in paths {
363        match ownership.classify(p) {
364            Owner::Unit(n) | Owner::Test { unit: Some(n), .. } => {
365                owners.insert(n);
366            }
367            Owner::Spec(slug) => {
368                spec_slugs.insert(slug);
369            }
370            _ => {}
371        }
372    }
373    let integrated = integrated_units(&subject);
374    let (upstream, from_message) = if integrated.is_empty() {
375        (owners.iter().cloned().collect::<Vec<_>>(), false)
376    } else {
377        // the message names unit ids; their SDD is the one whose units — or
378        // whose spec — the merge changed
379        let slugs: BTreeSet<String> = owners
380            .iter()
381            .map(|n| n.slug.clone())
382            .chain(spec_slugs)
383            .collect();
384        let mut nodes: Vec<Node> = Vec::new();
385        for unit in &integrated {
386            let mut found = false;
387            for n in owners.iter().filter(|n| &n.unit == unit) {
388                nodes.push(n.clone());
389                found = true;
390            }
391            if !found
392                && slugs.len() == 1
393                && let Some(slug) = slugs.first()
394            {
395                nodes.push(Node::new(slug.as_str(), unit.as_str()));
396            }
397        }
398        nodes.sort();
399        nodes.dedup();
400        if nodes.is_empty() {
401            (owners.into_iter().collect(), false)
402        } else {
403            (nodes, true)
404        }
405    };
406    Ok(Culprit {
407        sha: sha.to_string(),
408        short,
409        subject,
410        upstream,
411        integrated: from_message,
412        probability,
413    })
414}
415
416/// The unit ids an integration's subject names: `sdd: integrate U-004 (c3)`
417/// names `U-004`; an integration commit `sdd: verify U-001 (c1), U-002 (c4)`
418/// names both. Empty for any other subject.
419fn integrated_units(subject: &str) -> Vec<String> {
420    let Some(rest) = subject
421        .strip_prefix("sdd: integrate ")
422        .or_else(|| subject.strip_prefix("sdd: verify "))
423    else {
424        return Vec::new();
425    };
426    rest.split(", ")
427        .filter_map(|part| part.split_whitespace().next())
428        .filter(|id| !id.is_empty())
429        .map(str::to_string)
430        .collect()
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436
437    #[test]
438    fn integration_subjects_name_their_units() {
439        assert_eq!(integrated_units("sdd: integrate U-004 (c3)"), vec!["U-004"]);
440        assert_eq!(
441            integrated_units("sdd: verify U-001 (c1), U-002 (c4)"),
442            vec!["U-001", "U-002"]
443        );
444        assert!(integrated_units("fix the parser").is_empty());
445    }
446
447    #[test]
448    fn a_culprit_is_described_by_what_it_integrated_or_changed() {
449        let mut c = Culprit {
450            sha: "a1b2c3d4".into(),
451            short: "a1b2c3d".into(),
452            subject: "sdd: integrate U-004 (c3)".into(),
453            upstream: vec![Node::new("core", "U-004")],
454            integrated: true,
455            probability: 0.97,
456        };
457        assert_eq!(c.describe(), "core U-004 integrated");
458        c.integrated = false;
459        assert_eq!(c.describe(), "changed core U-004");
460        c.upstream.clear();
461        assert_eq!(c.describe(), "\"sdd: integrate U-004 (c3)\"");
462        let report = Report {
463            node: Node::new("api", "U-002"),
464            row_number: 2,
465            row: "make check".into(),
466            finding: Finding::Culprit(Culprit {
467                upstream: vec![Node::new("core", "U-004")],
468                integrated: true,
469                ..c
470            }),
471            candidates: 3,
472            touched: 1,
473            probes: 2,
474            notes: Vec::new(),
475        };
476        assert_eq!(
477            report.line(),
478            "api U-002 row 2 broke at a1b2c3d (core U-004 integrated) — culprit found"
479        );
480    }
481}