1use 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
68pub fn probe_checkout(worktrees: &Path, slug: &str) -> PathBuf {
70 worktrees.join(format!("probe-{slug}"))
71}
72
73#[derive(Debug, Clone)]
75pub struct Rotten<'a> {
76 pub node: &'a Node,
77 pub row_number: usize,
80 pub row: &'a str,
82 pub anchor: &'a str,
84 pub base: &'a str,
86}
87
88pub struct Probe<'a> {
90 pub git: &'a Git,
92 pub ownership: &'a Ownership,
93 pub closures: &'a Closures,
95 pub setup: &'a [String],
97 pub prepare: &'a dyn Prepare,
98 pub runner: &'a dyn Runner,
99 pub config: facf::Config,
100}
101
102#[derive(Debug, Clone, PartialEq)]
104pub struct Culprit {
105 pub sha: String,
106 pub short: String,
107 pub subject: String,
108 pub upstream: Vec<Node>,
111 pub integrated: bool,
113 pub probability: f64,
114}
115
116impl Culprit {
117 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#[derive(Debug, Clone, PartialEq)]
135pub enum Finding {
136 Culprit(Culprit),
138 Flake { probability: f64 },
141 Inconclusive {
145 best: Option<Culprit>,
146 probability: f64,
147 },
148 Interrupted,
150}
151
152#[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 pub candidates: usize,
161 pub touched: usize,
162 pub probes: usize,
163 pub notes: Vec<String>,
165}
166
167impl Report {
168 pub fn line(&self) -> String {
171 format!("{} {}", self.node, self.finding_line())
172 }
173
174 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
214pub 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 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 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 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 Verdict::Searching => Finding::Inconclusive {
312 best: None,
313 probability: 0.0,
314 },
315 }
316 };
317 Ok(report)
318}
319
320fn 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
350fn 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 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
416fn 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}