From 63738b73bd4eefe5d34604eaf0e5c3f000ca3abd Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 17 Nov 2026 11:31:28 -0500 Subject: [PATCH 1/7] A red check is reproduced against the base branch before a revert or a blame Before a CI fix round the failure is read from its own report (test, error, screenshot, report link) and the failing test runs with the head's test code against the base branch's deployment and the pull request's preview; both results and each failing check's result on the base head are kept on the run. A revert of CoderHelm's own work needs a record showing the change caused the failure. Blame and "couldn't confirm" sentences are held against the record. The description's CI failing section and revert lines are rebuilt for the head. --- docs/incidents/cr_red_on_every_branch.md | 5 + services/common/src/ci_lines.rs | 235 ++++ services/common/src/ci_repro.rs | 1023 +++++++++++++++++ services/common/src/lib.rs | 5 + services/worker/src/passes/ci_repro.rs | 551 +++++++++ services/worker/src/passes/description.rs | 60 + .../incidents/cr_red_on_every_branch.rs | 219 ++++ services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/resume.rs | 275 ++++- 9 files changed, 2330 insertions(+), 44 deletions(-) create mode 100644 docs/incidents/cr_red_on_every_branch.md create mode 100644 services/common/src/ci_lines.rs create mode 100644 services/common/src/ci_repro.rs create mode 100644 services/worker/src/passes/ci_repro.rs create mode 100644 services/worker/src/passes/incidents/cr_red_on_every_branch.rs diff --git a/docs/incidents/cr_red_on_every_branch.md b/docs/incidents/cr_red_on_every_branch.md new file mode 100644 index 000000000..9943d23c1 --- /dev/null +++ b/docs/incidents/cr_red_on_every_branch.md @@ -0,0 +1,5 @@ +# cr. `cr_red_on_every_branch` + +**What happened:** A pull request's end-to-end check failed on a test it had edited, while a vendor portal the page embeds had just opened registration: the test was red on every branch, staging included. The failure comment named the test, its error and had a screenshot of the vendor's sign-in drawer. The run never compared the test with the base branch. A fix attempt wrote that another spec was "broken on main"; the supervisor then reverted seven of the pull request's own files to an older head, which failed the same way. The description kept "CI is failing" with a lint warning as the error and "Deferred: reverted 7 file(s)" after the work had come back, and the run wrote that it couldn't confirm what the test saw. Four other runs reverted their own work with no comparison, one for a cloud account's load balancer limit in the preview deploy. + +**The guarantee:** Before a CI fix round the failure is read from its own report (test, error, screenshot, report link) and the failing test is run with the head's test code against the base branch's deployment and the pull request's preview; both results, and each failing check's result on the base branch's head, are kept on the run (`common::ci_repro`). The fixer gets all of it, the screenshot as an image. A revert of CoderHelm's own work needs a record on the head that shows the change makes a check fail; a failure red on the base too is fixed on the branch and said, never reverted. Nothing CoderHelm writes calls a failure the base branch's, flaky or not this change's without that record, or says a failure couldn't be confirmed while its report was read. The "CI is failing" section names its head and goes once the head moves or its checks show no failure; a revert's "Deferred" line goes once its files are back (`common::ci_lines`). diff --git a/services/common/src/ci_lines.rs b/services/common/src/ci_lines.rs new file mode 100644 index 000000000..2715430bd --- /dev/null +++ b/services/common/src/ci_lines.rs @@ -0,0 +1,235 @@ +//! The lines a pull request carries about its own CI, true for its head. +//! +//! A pull request's description kept "CI is failing" (with a lint warning +//! quoted as the error) and "Deferred: reverted 7 file(s)" after the work +//! had come back on a later head and the checks were running again. Both +//! were written once, by the path that stopped fixing, and nothing ever +//! took them out. +//! +//! The rules: +//! +//! - The "CI is failing" section names the head it was written on +//! ([`failing_section`]). On every build of the description +//! ([`reconcile`]) it goes when the head moved, or when the head's checks +//! show no failure. +//! - A revert's "Deferred" line names the green head it went back to and +//! the files it put back ([`revert_line`]). It goes once any of those +//! files differs from that head again: the work came back, so "reverted" +//! is no longer true. + +/// The "CI is failing" section's markers. +pub const FAILING_START: &str = ""; + +/// The marker on a revert's line. +pub const REVERT_MARK: &str = "\n{}\n{FAILING_END}", + inner.trim() + ) +} + +/// The head a "CI is failing" section in `body` was written on: `Some("")` +/// for a section written before it named one, `None` with no section. +pub fn failing_head(body: &str) -> Option { + let i = body.find(FAILING_START)?; + let rest = &body[i + FAILING_START.len()..]; + let end = rest.find("-->").unwrap_or(0); + let attrs = &rest[..end]; + Some( + attrs + .split_whitespace() + .find_map(|a| a.strip_prefix("head=")) + .unwrap_or("") + .to_string(), + ) +} + +/// `body` without its "CI is failing" section. +pub fn without_failing(body: &str) -> String { + let (Some(a), Some(b)) = (body.find(FAILING_START), body.find(FAILING_END)) else { + return body.to_string(); + }; + if b < a { + return body.to_string(); + } + let mut out = body.to_string(); + out.replace_range(a..b + FAILING_END.len(), ""); + squeeze(&out) +} + +fn squeeze(s: &str) -> String { + let mut out = s.to_string(); + while out.contains("\n\n\n") { + out = out.replace("\n\n\n", "\n\n"); + } + out.trim().to_string() +} + +/// A revert's line under "Deferred": the note, and a hidden mark with the +/// green head it went back to and the files it put back. +pub fn revert_line(note: &str, to: &str, paths: &[String]) -> String { + let to: String = to.chars().take(40).collect(); + let paths: Vec = paths + .iter() + .filter(|p| !p.contains(char::is_whitespace) && !p.contains("--")) + .cloned() + .collect(); + format!( + "- {} {REVERT_MARK}to={to} paths={} -->", + note.trim(), + paths.join(",") + ) +} + +/// A revert named on a line of the description. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RevertMark { + pub to: String, + pub paths: Vec, +} + +/// The revert a line names, when it carries the mark. +pub fn revert_of(line: &str) -> Option { + let i = line.find(REVERT_MARK)?; + let rest = &line[i + REVERT_MARK.len()..]; + let attrs = &rest[..rest.find("-->").unwrap_or(rest.len())]; + let mut to = String::new(); + let mut paths = Vec::new(); + for a in attrs.split_whitespace() { + if let Some(t) = a.strip_prefix("to=") { + to = t.to_string(); + } else if let Some(p) = a.strip_prefix("paths=") { + paths = p + .split(',') + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect(); + } + } + (!to.is_empty()).then_some(RevertMark { to, paths }) +} + +/// Every revert the description names. +pub fn reverts_in(body: &str) -> Vec { + body.lines().filter_map(revert_of).collect() +} + +/// Where the head's checks stand, as the build read them. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct HeadCi { + pub head: String, + /// The head's checks were read. + pub read: bool, + /// The checks failing on the head. + pub failing: Vec, +} + +/// `body` with its CI lines true for the head: the "CI is failing" section +/// goes when it was written on another head or the head's checks show no +/// failure; a revert's line goes when `undone` says its files changed +/// again since the green head it went back to. +pub fn reconcile(body: &str, ci: &HeadCi, undone: &dyn Fn(&RevertMark) -> bool) -> String { + let mut out = body.to_string(); + if let Some(at) = failing_head(&out) { + let other_head = !at.is_empty() + && !ci.head.is_empty() + && !ci.head.starts_with(&at) + && !at.starts_with(&ci.head); + let no_failure = ci.read && ci.failing.is_empty(); + if other_head || no_failure { + out = without_failing(&out); + } + } + if out.contains(REVERT_MARK) { + let kept: Vec<&str> = out + .lines() + .filter(|l| revert_of(l).is_none_or(|m| !undone(&m))) + .collect(); + out = kept.join("\n"); + out = drop_empty_deferred(&out); + } + out +} + +/// A "Deferred" heading left with nothing under it goes too. +fn drop_empty_deferred(body: &str) -> String { + let lines: Vec<&str> = body.lines().collect(); + let mut out: Vec<&str> = Vec::new(); + let mut i = 0; + while i < lines.len() { + let l = lines[i]; + if l.trim() == "## Deferred" { + let next = lines[i + 1..] + .iter() + .find(|n| !n.trim().is_empty()) + .map(|n| n.trim()); + if next.is_none_or(|n| n.starts_with('#') || n.starts_with("\n## CI is failing\n**CI is failing:** `Deploy Preview`.\n\n\nRemoves the link.\n\n## Deferred\n- CI stayed red: reverted 2 file(s) to b66dfd3. "; + + #[test] + fn the_failing_section_goes_with_its_head_or_a_green_head() { + assert_eq!(failing_head(BODY).as_deref(), Some("abc123456789")); + let same = HeadCi { + head: "abc123456789ff".into(), + read: true, + failing: vec!["Deploy Preview".into()], + }; + assert!(reconcile(BODY, &same, &|_| false).contains("## CI is failing")); + let moved = HeadCi { + head: "def000".into(), + read: false, + failing: vec![], + }; + assert!(!reconcile(BODY, &moved, &|_| false).contains("CI is failing")); + let green = HeadCi { + head: "abc123456789".into(), + read: true, + failing: vec![], + }; + let out = reconcile(BODY, &green, &|_| false); + assert!(!out.contains("CI is failing"), "{out}"); + assert!( + out.starts_with("Source ticket: WEB-1\n\nRemoves the link."), + "{out}" + ); + } + + #[test] + fn a_revert_line_goes_once_its_work_came_back() { + let marks = reverts_in(BODY); + assert_eq!( + marks, + vec![RevertMark { + to: "b66dfd3aaaa".into(), + paths: vec!["a.ts".into(), "b.ts".into()] + }] + ); + let ci = HeadCi::default(); + assert!(reconcile(BODY, &ci, &|_| false).contains("reverted 2 file(s)")); + let out = reconcile(BODY, &ci, &|m| m.paths.contains(&"a.ts".to_string())); + assert!(!out.contains("reverted"), "{out}"); + assert!(!out.contains("## Deferred"), "{out}"); + let line = revert_line("Reverted.", "b66dfd3", &["x y.ts".into(), "c.ts".into()]); + assert_eq!(revert_of(&line).unwrap().paths, vec!["c.ts".to_string()]); + } +} diff --git a/services/common/src/ci_repro.rs b/services/common/src/ci_repro.rs new file mode 100644 index 000000000..0157027eb --- /dev/null +++ b/services/common/src/ci_repro.rs @@ -0,0 +1,1023 @@ +//! A red check is reproduced before anything is decided about it. +//! +//! A pull request's end-to-end test failed on a vendor's portal that had +//! just opened registration: the test was red on every branch. The fix +//! rounds first wrote that a different test was "broken on main", then the +//! supervisor reverted seven of the pull request's own files to an older +//! head, which failed the same way. The failure comment on the pull request +//! named the test, its error and had a screenshot of what the page showed; +//! the run still wrote that it "couldn't confirm" the cause. Four other +//! runs reverted their own work the same way, one of them for a cloud +//! account's load balancer limit in the preview deploy. +//! +//! The rules, each enforced in code: +//! +//! - **A comparison is on record before a decision.** [`Record`]: the +//! failing test run with the head's test code against the base branch's +//! deployment (staging, `base`) and against the pull request's (the +//! preview, `change`), or the same check's result on the base branch's +//! head next to its result on this head. [`Record::verdict`] reads it: +//! red on the base too is not this change's; green on the base and red +//! here is this change's; a leg that did not run (no address, no browser, +//! the host unreachable) proves nothing. +//! - **No revert without it.** [`may_revert`]: CoderHelm's own work comes +//! out for red checks only when a record on this head shows this change +//! makes a check fail, and never when one shows it fails on the base too. +//! - **No blame without it.** [`hold_blame`]: a sentence that calls a +//! failure the base branch's, flaky, pre-existing or not this change's is +//! replaced unless a record on this head shows the test fails on the base +//! too. A sentence that quotes a measured count (`0/40 passed`) carries +//! its own evidence and stays. +//! - **Read evidence is never "unconfirmed".** [`hold_unread`]: a sentence +//! that says a failure couldn't be confirmed or read, while its report was +//! read, is replaced by what the report says. +//! - **The fixer is told.** [`brief`]: the failing test, its error, the +//! screenshot and report links, and the comparison with what it means for +//! the fix: red on the base too means the test (or the code it checks) is +//! fixed on this branch and said so, never a revert. + +use serde::{Deserialize, Serialize}; + +/// The run record attribute that keeps the comparisons, as JSON. +pub const FIELD: &str = "ci_repro"; + +/// The marker the comparison script prints around each side's run. +pub const MARK: &str = "CODERHELM_REPRO"; + +/// One side of a comparison: where the test ran and what it counted. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Leg { + /// The address the test ran against, or `ci@` for a check's run. + pub target: String, + /// A real run happened (the browser started, the host answered). + pub ran: bool, + pub passed: u32, + pub failed: u32, + /// Why it didn't run, or the line that says what it found. + #[serde(default)] + pub note: String, +} + +impl Leg { + pub fn red(&self) -> bool { + self.ran && self.failed > 0 + } + + pub fn green(&self) -> bool { + self.ran && self.failed == 0 && self.passed > 0 + } + + fn line(&self, side: &str) -> String { + let at = if self.target.is_empty() { + String::new() + } else { + format!(" ({})", self.target) + }; + if !self.ran { + let why = if self.note.trim().is_empty() { + "no result".to_string() + } else { + crate::truncate_str(self.note.trim(), 200).to_string() + }; + return format!("{side}{at}: didn't run ({why})"); + } + let result = if self.failed > 0 { + format!("failed ({} failed, {} passed)", self.failed, self.passed) + } else { + format!("passed ({} passed)", self.passed) + }; + format!("{side}{at}: {result}") + } +} + +/// A failing check's comparison on one head. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Record { + /// The pull request's head it was made on. + pub head: String, + pub check: String, + /// The failing tests compared (`file › title`); empty for a check. + #[serde(default)] + pub tests: Vec, + /// The base branch's deployment (staging), or the check on its head. + pub base: Leg, + /// The pull request's preview, or the check on this head. + pub change: Leg, + /// `sandbox` (the test was run) or `ci` (the check's own results). + pub source: String, + pub at: String, +} + +/// What a comparison shows. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + /// The test passes on the base and fails with this change. + ThisChange(String), + /// The test fails on the base too: the cause is outside this change. + NotThisChange(String), + /// Nothing is shown yet (a side didn't run, or both passed). + Unproven(String), +} + +impl Record { + fn what(&self) -> String { + match self.tests.first() { + Some(t) => format!("`{t}`"), + None => format!("`{}`", self.check), + } + } + + pub fn verdict(&self) -> Verdict { + let what = self.what(); + if self.base.red() { + return Verdict::NotThisChange(format!( + "{what} fails on the base branch too ({})", + self.base.line("base") + )); + } + if self.base.green() && self.change.red() { + return Verdict::ThisChange(format!( + "{what} passes on the base branch and fails with this change" + )); + } + if self.base.green() && self.change.green() { + return Verdict::Unproven(format!( + "{what} passed on both sides when run again, so the failure didn't reproduce" + )); + } + let missing: Vec = [("base", &self.base), ("this change", &self.change)] + .iter() + .filter(|(_, l)| !l.ran) + .map(|(s, l)| l.line(s)) + .collect(); + Verdict::Unproven(format!( + "{what} has no comparison yet: {}", + if missing.is_empty() { + "the base side didn't fail or pass".to_string() + } else { + missing.join("; ") + } + )) + } + + /// One line for the run page and the pull request. + pub fn line(&self) -> String { + let how = if self.source == "ci" { + "the check's own runs" + } else { + "run again in CoderHelm's sandbox" + }; + let v = match self.verdict() { + Verdict::ThisChange(w) => format!("This change's: {w}."), + Verdict::NotThisChange(w) => format!("Not this change's: {w}."), + Verdict::Unproven(w) => format!("Not shown either way: {w}."), + }; + format!( + "{v} Compared on {} ({how}): {}; {}.", + short(&self.head), + self.base.line("base"), + self.change.line("this change") + ) + } +} + +fn short(sha: &str) -> String { + sha.chars().take(7).collect() +} + +/// The records kept on a run, as JSON. +pub fn to_json(records: &[Record]) -> String { + serde_json::to_string(records).unwrap_or_default() +} + +pub fn from_json(s: &str) -> Vec { + serde_json::from_str(s).unwrap_or_default() +} + +/// The records for `head`, newest kept when a check was compared twice. +pub fn on_head<'a>(records: &'a [Record], head: &str) -> Vec<&'a Record> { + let mut out: Vec<&Record> = Vec::new(); + for r in records.iter().rev() { + if !head.is_empty() && same_sha(&r.head, head) && !out.iter().any(|o| o.check == r.check) { + out.push(r); + } + } + out +} + +fn same_sha(a: &str, b: &str) -> bool { + let (a, b) = (a.trim(), b.trim()); + !a.is_empty() && !b.is_empty() && (a.starts_with(b) || b.starts_with(a)) +} + +/// `records` with `r` in place of an older one for the same head and check. +pub fn upsert(records: &[Record], r: Record) -> Vec { + let mut out: Vec = records + .iter() + .filter(|o| !(same_sha(&o.head, &r.head) && o.check == r.check)) + .cloned() + .collect(); + out.push(r); + // A run keeps a handful: the newest twenty. + let n = out.len(); + if n > 20 { + out.drain(..n - 20); + } + out +} + +/// A check's comparison from its own runs: its result on this head next to +/// its result on the base branch's head (`base_failed`: `None` when it +/// didn't run there). +pub fn from_checks(head: &str, base_sha: &str, check: &str, base_failed: Option) -> Record { + let base = match base_failed { + Some(failed) => Leg { + target: format!("ci@{}", short(base_sha)), + ran: true, + passed: u32::from(!failed), + failed: u32::from(failed), + note: String::new(), + }, + None => Leg { + target: format!("ci@{}", short(base_sha)), + ran: false, + note: format!("`{check}` doesn't run on the base branch's head"), + ..Default::default() + }, + }; + Record { + head: head.to_string(), + check: check.to_string(), + tests: Vec::new(), + base, + change: Leg { + target: format!("ci@{}", short(head)), + ran: true, + passed: 0, + failed: 1, + note: String::new(), + }, + source: "ci".into(), + at: String::new(), + } +} + +// ── The revert gate ───────────────────────────────────────────────────────── + +/// Whether CoderHelm may take its own work out for red checks. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RevertGate { + /// A record on this head shows the change makes a check fail. + Allowed(String), + /// Refused, with why: no record shows it, or one shows the failure is + /// the base branch's too. + Refused(String), +} + +/// The revert gate (see the module's rules). +pub fn may_revert(records: &[Record], head: &str) -> RevertGate { + let here = on_head(records, head); + let not_ours: Vec = here + .iter() + .filter_map(|r| match r.verdict() { + Verdict::NotThisChange(w) => Some(w), + _ => None, + }) + .collect(); + if !not_ours.is_empty() { + return RevertGate::Refused(format!( + "{}: taking this pull request's work out would not make it pass", + not_ours.join("; ") + )); + } + let ours: Vec = here + .iter() + .filter_map(|r| match r.verdict() { + Verdict::ThisChange(w) => Some(w), + _ => None, + }) + .collect(); + if !ours.is_empty() { + return RevertGate::Allowed(ours.join("; ")); + } + let unproven: Vec = here + .iter() + .filter_map(|r| match r.verdict() { + Verdict::Unproven(w) => Some(w), + _ => None, + }) + .collect(); + RevertGate::Refused(if unproven.is_empty() { + format!( + "no comparison of the failing checks with the base branch is on record for {}", + short(head) + ) + } else { + unproven.join("; ") + }) +} + +/// Whether a record on `head` shows a failure is not this change's. +pub fn shows_not_ours(records: &[Record], head: &str) -> bool { + on_head(records, head) + .iter() + .any(|r| matches!(r.verdict(), Verdict::NotThisChange(_))) +} + +// ── What CoderHelm writes about a failure ─────────────────────────────────── + +const BLAME: &[&str] = &[ + "broken on main", + "broken on `main`", + "broken on the base", + "fails on main", + "fails on `main`", + "failing on main", + "failing on `main`", + "red on main", + "red on `main`", + "also fails on", + "also failing on", + "pre-existing", + "preexisting", + "not this change", + "not caused by this", + "isn't caused by this", + "is not caused by this", + "unrelated to this change", + "unrelated to this pull request", + "unrelated failure", + "unrelated test", + "flaky", + "flake", + "outside this change", + "didn't cause", + "did not cause", + "not ours", +]; + +fn sentences(text: &str) -> Vec<(usize, usize)> { + // Spans of sentences: split at ". ", "! ", "? " and line ends. + let b = text.as_bytes(); + let mut out = Vec::new(); + let mut start = 0; + let mut i = 0; + while i < b.len() { + let end = if b[i] == b'\n' { + Some(i) + } else if matches!(b[i], b'.' | b'!' | b'?') && (i + 1 == b.len() || b[i + 1] == b' ') { + Some(i + 1) + } else { + None + }; + if let Some(e) = end { + if e > start { + out.push((start, e)); + } + start = e; + } + i += 1; + } + if start < b.len() { + out.push((start, b.len())); + } + out +} + +/// A sentence that quotes a measured count (`0/40 passed`, `3 of 20 runs`) +/// carries its own evidence. +fn measured(s: &str) -> bool { + let low = s.to_ascii_lowercase(); + let b = low.as_bytes(); + let slash = b + .windows(3) + .any(|w| w[0].is_ascii_digit() && w[1] == b'/' && w[2].is_ascii_digit()); + slash || (low.contains(" of ") && low.contains(" runs") && b.iter().any(u8::is_ascii_digit)) +} + +/// Whether `sentence` says a failure is the base branch's, flaky, +/// pre-existing or not this change's. +pub fn blames(sentence: &str) -> bool { + let low = sentence.to_ascii_lowercase(); + if low.trim_start().starts_with('#') || measured(&low) { + return false; + } + // "Not flaky" says the opposite. + let low = low.replace("not flaky", "").replace("isn't flaky", ""); + // A sentence about fixing a flaky test describes the work, not a blame. + let about_the_work = ["fix", "deflake", "stabil"].iter().any(|w| low.contains(w)); + BLAME + .iter() + .filter(|p| !(about_the_work && matches!(**p, "flaky" | "flake"))) + .any(|p| low.contains(p)) +} + +/// What replaces a blame with no comparison behind it. +pub const BLAME_HELD: &str = "Whether this change caused the failure is not shown yet: no run of \ + the failing test against the base branch is on record."; + +/// `text` with every sentence that blames the base branch, flakiness or +/// something outside this change replaced by [`BLAME_HELD`], unless a +/// record on `head` shows the failure on the base too. Returns whether +/// anything was replaced. +pub fn hold_blame(text: &str, records: &[Record], head: &str) -> (String, bool) { + if shows_not_ours(records, head) { + return (text.to_string(), false); + } + replace_sentences(text, blames, BLAME_HELD) +} + +const UNREAD: &[&str] = &[ + "couldn't confirm", + "could not confirm", + "can't confirm", + "cannot confirm", + "unconfirmed", + "couldn't read", + "could not read", + "can't read", + "wasn't readable", + "isn't readable", + "couldn't see", + "could not see", + "haven't seen", + "have not seen", +]; + +const ABOUT_A_FAILURE: &[&str] = &[ + "test", + "e2e", + "end-to-end", + "check", + " ci", + "ci ", + "failure", + "failing", + "report", + "screenshot", + "playwright", + "log", +]; + +/// Whether `sentence` says a failure couldn't be confirmed or read. +pub fn says_unread(sentence: &str) -> bool { + let low = format!(" {} ", sentence.to_ascii_lowercase()); + UNREAD.iter().any(|p| low.contains(p)) && ABOUT_A_FAILURE.iter().any(|w| low.contains(w)) +} + +/// `text` with every sentence that says a failure couldn't be confirmed or +/// read replaced by what its report says (`read`, one line), when it was +/// read. Returns whether anything was replaced. +pub fn hold_unread(text: &str, read: Option<&str>) -> (String, bool) { + match read.map(str::trim).filter(|r| !r.is_empty()) { + Some(r) => replace_sentences( + text, + says_unread, + &format!("The failure's report says: {r}"), + ), + None => (text.to_string(), false), + } +} + +fn replace_sentences(text: &str, hit: fn(&str) -> bool, with: &str) -> (String, bool) { + let mut out = String::with_capacity(text.len()); + let mut last = 0; + let mut changed = false; + let mut said = false; + for (a, e) in sentences(text) { + let s = &text[a..e]; + out.push_str(&text[last..a]); + if hit(s) { + changed = true; + let lead = &s[..s.len() - s.trim_start().len()]; + let bullet = s.trim_start(); + let prefix: String = bullet + .chars() + .take_while(|c| matches!(c, '-' | '*' | ' ')) + .collect(); + if !said { + out.push_str(lead); + out.push_str(&prefix); + out.push_str(with); + said = true; + } + } else { + out.push_str(s); + } + last = e; + } + out.push_str(&text[last..]); + (out, changed) +} + +// ── The evidence the fixer reads ──────────────────────────────────────────── + +/// What a failure's own report says, for the fixer. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Evidence { + pub check: String, + pub tests: Vec, + pub error: String, + /// Where it was read (`comment on the pull request`, `job log`, ...). + pub source: String, + /// Screenshots linked from the failure comment. + pub shots: Vec, + /// The published report it links to. + pub report: Option, +} + +impl Evidence { + /// One line: the test, the error, the screenshot. + pub fn line(&self) -> String { + let mut s = format!("`{}` failed", self.check); + if let Some(t) = self.tests.first() { + s.push_str(&format!(" in `{t}`")); + } + if !self.error.trim().is_empty() { + s.push_str(&format!( + ": {}", + crate::truncate_str(self.error.trim(), 200).replace('`', "'") + )); + } + if let Some(shot) = self.shots.first() { + s.push_str(&format!(" (screenshot: {shot})")); + } + s + } +} + +/// The image links in a failure comment: Markdown images, `` and +/// links to an image file. +pub fn shots_in(comment: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut push = |u: &str| { + let u = u.trim().trim_matches(|c| c == '"' || c == '\''); + if u.starts_with("https://") && !out.iter().any(|o| o == u) { + out.push(u.to_string()); + } + }; + for (i, _) in comment.match_indices("![") { + let rest = &comment[i..]; + if let Some(open) = rest.find("](") { + let after = &rest[open + 2..]; + if let Some(close) = after.find(')') { + push(&after[..close]); + } + } + } + for (i, _) in comment.match_indices("src=") { + let rest = &comment[i + 4..]; + let q = rest.chars().next().unwrap_or(' '); + if q == '"' || q == '\'' { + if let Some(end) = rest[1..].find(q) { + push(&rest[1..1 + end]); + } + } + } + for (i, _) in comment.match_indices("https://") { + let rest = &comment[i..]; + let end = rest + .find(|c: char| c.is_whitespace() || matches!(c, ')' | '"' | '\'' | '>' | ']')) + .unwrap_or(rest.len()); + let url = &rest[..end]; + let low = url.to_ascii_lowercase(); + let path = low.split(['?', '#']).next().unwrap_or(""); + if [".png", ".jpg", ".jpeg", ".webp", ".gif"] + .iter() + .any(|e| path.ends_with(e)) + { + push(url); + } + } + out.truncate(4); + out +} + +/// The fixer's section about the failure: what its report says and what +/// the comparison shows, with what that means for the fix. +pub fn brief(evidence: Option<&Evidence>, records: &[Record], head: &str) -> String { + let mut s = String::new(); + if let Some(e) = evidence { + s.push_str("\n\n## The failure, as its own report says\n"); + s.push_str(&format!( + "- Check: `{}` (read from the {})\n", + e.check, e.source + )); + for t in e.tests.iter().take(5) { + s.push_str(&format!("- Failing test: `{t}`\n")); + } + if !e.error.trim().is_empty() { + s.push_str(&format!( + "- Error: `{}`\n", + crate::truncate_str(e.error.trim(), 400).replace('`', "'") + )); + } + for shot in &e.shots { + s.push_str(&format!( + "- Screenshot at the failure: {shot} (attached to this message as an image: look at it before deciding)\n" + )); + } + if let Some(r) = &e.report { + s.push_str(&format!("- Report: {r}\n")); + } + s.push_str( + "Read these before you write anything about the failure; never write that it \ + couldn't be confirmed or read.\n", + ); + } + let here = on_head(records, head); + s.push_str("\n## The failing test against the base branch and against this pull request\n"); + if here.is_empty() { + s.push_str( + "- No comparison is on record for this head.\n\ + Before you decide the failure isn't this pull request's, or take any of its work \ + out, run the failing test in the sandbox against the base branch's deployment \ + (staging) and against this pull request's preview (its base URL set to each), and \ + say what each did.\n", + ); + } + for r in &here { + s.push_str(&format!("- {}\n", r.line())); + s.push_str(match r.verdict() { + Verdict::NotThisChange(_) => { + " It fails on the base branch too, so the cause is outside this change \ + (data, a service, the test itself). Fix the test, or the code it checks, on \ + this branch, and say so in one line starting `Fails on the base branch too:` \ + that names the test and what is different outside the change. Never revert \ + this pull request's work for it.\n" + } + Verdict::ThisChange(_) => { + " This change makes it fail: fix the change, or the test when the change \ + means to behave differently.\n" + } + Verdict::Unproven(_) => { + " Nothing is shown either way yet. Reproduce it before deciding: run the \ + failing test against both addresses. Don't write that it is the base \ + branch's, flaky or not this change's: that needs the comparison.\n" + } + }); + } + s +} + +// ── Running the comparison ────────────────────────────────────────────────── + +/// Lines that say a leg never reached the page: a browser that didn't start, +/// a host that didn't answer, a runner that found nothing to run. +const NOT_RUN: &[&str] = &[ + "executable doesn't exist", + "browsertype.launch", + "host system is missing dependencies", + "err_name_not_resolved", + "enotfound", + "getaddrinfo", + "econnrefused", + "err_connection_refused", + "no tests found", + "command not found", + "cannot find module", + "err_internet_disconnected", +]; + +/// One side's result from its output. +pub fn leg_of(target: &str, output: &str) -> Leg { + let low = output.to_ascii_lowercase(); + if let Some(p) = NOT_RUN.iter().find(|p| low.contains(*p)) { + let line = output + .lines() + .find(|l| l.to_ascii_lowercase().contains(p)) + .unwrap_or(p) + .trim(); + return Leg { + target: target.to_string(), + ran: false, + note: crate::truncate_str(line, 200).to_string(), + ..Default::default() + }; + } + let mut leg = Leg { + target: target.to_string(), + ..Default::default() + }; + for l in output.lines() { + let mut w = l.split_whitespace(); + let (Some(n), Some(what)) = (w.next(), w.next()) else { + continue; + }; + let Ok(n) = n.parse::() else { continue }; + match what { + "passed" | "flaky" => { + leg.passed = n; + leg.ran = true; + } + "failed" => { + leg.failed = n; + leg.ran = true; + } + _ => {} + } + } + if !leg.ran { + leg.note = "the run printed no count".into(); + } else if let Some(e) = output.lines().map(str::trim).find(|l| { + let low = l.to_ascii_lowercase(); + low.starts_with("error:") || low.starts_with("expect(") + }) { + leg.note = crate::truncate_str(e, 200).to_string(); + } + leg +} + +fn quote(s: &str) -> Option { + (!s.is_empty() && !s.contains('\'') && !s.contains('\n') && !s.starts_with('-')) + .then(|| format!("'{s}'")) +} + +/// A test title as a `--grep` pattern: its regex characters escaped. +fn grep_of(title: &str) -> String { + let mut out = String::new(); + for c in title.chars() { + if "\\^$.|?*+()[]{}".contains(c) { + out.push('\\'); + } + out.push(c); + } + out +} + +/// The command that runs one Playwright test (`spec` relative to the +/// package folder `dir`, `title` its name) once against `target`. +pub fn leg_cmd(dir: &str, spec: &str, title: &str, target: &str) -> Option { + let host = target + .strip_prefix("https://")? + .split(['/', '?', '#']) + .next() + .unwrap_or(""); + if host.is_empty() + || target.contains("{pr}") + || host + .chars() + .all(|c| c.is_ascii_digit() || c == '.' || c == ':') + { + return None; + } + crate::e2e::report_source::check_target(target).ok()?; + let dir = if dir.is_empty() { "." } else { dir }; + let dir = quote(dir)?; + let spec = quote(spec)?; + let t = quote(target)?; + let grep = if title.trim().is_empty() { + String::new() + } else { + format!(" --grep {}", quote(&grep_of(title.trim()))?) + }; + Some(format!( + "cd {dir} && npx --no-install playwright install --with-deps chromium >/dev/null 2>&1; \ + BASE_URL={t} PLAYWRIGHT_BASE_URL={t} PLAYWRIGHT_TEST_BASE_URL={t} E2E_BASE_URL={t} \ + npx --no-install playwright test {spec}{grep} --retries=0 --workers=1 --reporter=line" + )) +} + +/// One script that runs each side in turn and prints its output between +/// markers. +pub fn script(legs: &[(&str, String)]) -> String { + let mut s = String::new(); + for (side, cmd) in legs { + s.push_str(&format!( + "echo \"{MARK} start {side}\"; ( {cmd} ) > /tmp/ch-repro-{side}.log 2>&1; echo \"{MARK} exit {side} $?\"; tail -c 3000 /tmp/ch-repro-{side}.log; echo; echo \"{MARK} end {side}\"\n" + )); + } + s.push_str("true\n"); + s +} + +/// Each side's output from the script's. +pub fn split(output: &str, side: &str) -> Option { + let start = format!("{MARK} start {side}"); + let end = format!("{MARK} end {side}"); + let a = output.find(&start)? + start.len(); + let b = output[a..] + .find(&end) + .map(|i| a + i) + .unwrap_or(output.len()); + Some(output[a..b].to_string()) +} + +/// The spec file and the title of a failing test named `file › title`. +pub fn spec_and_title(test: &str) -> (String, String) { + match test.split_once(" › ") { + Some((f, t)) => (f.trim().to_string(), t.trim().to_string()), + None => (test.trim().to_string(), String::new()), + } +} + +/// The base branch's deployment for the comparison: a configured test +/// address with no `{pr}` in it, else the first staging address the +/// repository's end-to-end setup names (`texts`: path and content). +pub fn base_target(configured: Option<&str>, texts: &[(String, String)]) -> Option { + if let Some(c) = configured + .map(str::trim) + .filter(|c| !c.is_empty() && !c.contains("{pr}")) + { + return Some(c.to_string()); + } + for (_, text) in texts { + for (i, _) in text.match_indices("https://") { + let rest = &text[i + 8..]; + let host: String = rest + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '.' || *c == '-') + .collect(); + let h = host.to_ascii_lowercase(); + let staging = h + .split(['.', '-']) + .any(|p| matches!(p, "staging" | "stage" | "stg")); + if staging && h.contains('.') && !h.contains("{pr}") { + return Some(format!("https://{host}")); + } + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + fn leg(ran: bool, passed: u32, failed: u32) -> Leg { + Leg { + target: "https://x.example.com".into(), + ran, + passed, + failed, + note: String::new(), + } + } + + fn rec(base: Leg, change: Leg) -> Record { + Record { + head: "abc1234def".into(), + check: "E2E".into(), + tests: vec!["tests/a.spec.ts › adds it to the cart".into()], + base, + change, + source: "sandbox".into(), + at: String::new(), + } + } + + #[test] + fn the_verdict_comes_from_both_sides() { + assert!(matches!( + rec(leg(true, 0, 1), leg(true, 0, 1)).verdict(), + Verdict::NotThisChange(_) + )); + assert!(matches!( + rec(leg(true, 1, 0), leg(true, 0, 1)).verdict(), + Verdict::ThisChange(_) + )); + assert!(matches!( + rec(leg(false, 0, 0), leg(true, 0, 1)).verdict(), + Verdict::Unproven(_) + )); + assert!(matches!( + rec(leg(true, 1, 0), leg(true, 1, 0)).verdict(), + Verdict::Unproven(_) + )); + } + + #[test] + fn a_revert_needs_this_change_on_this_head() { + let ours = vec![rec(leg(true, 1, 0), leg(true, 0, 1))]; + assert!(matches!( + may_revert(&ours, "abc1234"), + RevertGate::Allowed(_) + )); + // Another head's record proves nothing about this one. + assert!(matches!( + may_revert(&ours, "fff0000"), + RevertGate::Refused(_) + )); + let base_red = vec![rec(leg(true, 0, 1), leg(true, 0, 1))]; + match may_revert(&base_red, "abc1234") { + RevertGate::Refused(w) => assert!(w.contains("fails on the base branch too"), "{w}"), + g => panic!("{g:?}"), + } + assert!(matches!(may_revert(&[], "abc1234"), RevertGate::Refused(_))); + } + + #[test] + fn blame_needs_a_record_and_a_count_is_evidence() { + let text = "The fix is in.\n- `summer camp pricing` is broken on main since #12. Nothing else changed."; + let (held, changed) = hold_blame(text, &[], "abc1234"); + assert!(changed); + assert!(!held.contains("broken on main"), "{held}"); + assert!(held.contains(BLAME_HELD), "{held}"); + assert!(held.contains("The fix is in.")); + let base_red = vec![rec(leg(true, 0, 1), leg(true, 0, 1))]; + assert_eq!( + hold_blame(text, &base_red, "abc1234"), + (text.to_string(), false) + ); + assert!(!blames( + "Not flaky: the test failed every run (0/40 passed on the base branch)." + )); + assert!(!blames("It failed 0/640 runs on main, so it is not flaky.")); + assert!(blames("This looks flaky.")); + assert!(!blames("Fixes the flaky `timeofday` test.")); + assert!(!blames("### Why the flaky test failed")); + } + + #[test] + fn read_evidence_is_never_unconfirmed() { + let text = "I couldn't confirm why the e2e test fails. The link is gone."; + let (held, changed) = hold_unread( + text, + Some("`E2E` failed in `a.spec.ts › adds it`: Subtotal$0"), + ); + assert!(changed); + assert!( + held.starts_with("The failure's report says: `E2E` failed"), + "{held}" + ); + assert!(held.contains("The link is gone.")); + assert!(!hold_unread(text, None).1); + assert!(!says_unread("Unconfirmed: the staging page's colour.")); + } + + #[test] + fn a_leg_that_never_reached_the_page_did_not_run() { + let out = "Running 1 test\n 1) [chromium] › a.spec.ts › x\n Error: browserType.launch: Executable doesn't exist at /root/.cache\n 1 failed\n"; + let l = leg_of("https://staging.example.com", out); + assert!(!l.ran, "{l:?}"); + let ok = leg_of( + "https://staging.example.com", + "Running 1 test\n 1 passed (4.1s)\n", + ); + assert!(ok.green()); + let red = leg_of( + "https://staging.example.com", + " 1) a.spec.ts › x\n Error: expect(locator).not.toHaveText(expected) failed\n 1 failed\n", + ); + assert!(red.red()); + assert!(red.note.starts_with("Error: expect"), "{red:?}"); + } + + #[test] + fn the_comparison_command_and_targets() { + let c = leg_cmd( + "e2e", + "tests/browse/camp.spec.ts", + "adds it (AM)", + "https://staging.example.com", + ) + .unwrap(); + assert!(c.contains("--grep 'adds it \\(AM\\)'"), "{c}"); + assert!(c.contains("E2E_BASE_URL='https://staging.example.com'")); + assert_eq!(leg_cmd("e2e", "a.spec.ts", "x", "http://10.0.0.1"), None); + let texts = vec![( + "e2e/playwright.config.ts".to_string(), + "baseURL: process.env.E2E_BASE_URL ?? 'https://staging-shop.example.com/'".to_string(), + )]; + assert_eq!( + base_target(Some("https://pr-{pr}.preview.example.com"), &texts).as_deref(), + Some("https://staging-shop.example.com") + ); + assert_eq!( + base_target(Some("https://qa.example.com"), &texts).as_deref(), + Some("https://qa.example.com") + ); + let s = script(&[("base", "true".into()), ("change", "true".into())]); + let out = format!("{MARK} start base\n1 failed\n{MARK} end base\n{MARK} start change\n1 passed\n{MARK} end change\n"); + assert!(s.contains("ch-repro-base.log")); + assert_eq!(split(&out, "base").unwrap().trim(), "1 failed"); + assert_eq!(split(&out, "change").unwrap().trim(), "1 passed"); + } + + #[test] + fn screenshots_are_found_in_the_failure_comment() { + let c = "## E2E failed\n![failure](https://github.com/user-attachments/assets/abc.png)\n\n[report](https://reports.example.com/pr-1/index.html)"; + assert_eq!( + shots_in(c), + vec![ + "https://github.com/user-attachments/assets/abc.png".to_string(), + "https://reports.example.com/pr-1/data/shot.jpeg".to_string() + ] + ); + } + + #[test] + fn the_check_record_reads_like_the_sandbox_one() { + let r = from_checks("abc1234", "fff9999", "Test Suite", Some(false)); + assert!(matches!(r.verdict(), Verdict::ThisChange(_))); + let r = from_checks("abc1234", "fff9999", "Deploy Preview", None); + assert!(matches!(r.verdict(), Verdict::Unproven(_))); + let all = upsert( + std::slice::from_ref(&r), + from_checks("abc1234", "fff9999", "Deploy Preview", Some(true)), + ); + assert_eq!(all.len(), 1); + assert!(matches!(all[0].verdict(), Verdict::NotThisChange(_))); + assert_eq!(from_json(&to_json(&all)), all); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 31813a1bf..e7776bd2b 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -158,6 +158,11 @@ pub mod knowledge; pub mod repo_read; // The test that every model call site is a metered helper pub mod ci_cover; +/// The lines a pull request carries about its own CI, true for its head. +pub mod ci_lines; +/// A red check reproduced against the base branch before anything is +/// decided about it. +pub mod ci_repro; /// The last check on a pull request description: no section twice, no /// deploy maps, no empty "who this affects". pub mod description_lint; diff --git a/services/worker/src/passes/ci_repro.rs b/services/worker/src/passes/ci_repro.rs new file mode 100644 index 000000000..7ed0b0a19 --- /dev/null +++ b/services/worker/src/passes/ci_repro.rs @@ -0,0 +1,551 @@ +//! A red check, reproduced before anything is decided about it: the +//! failure read from its own report, the failing test run against the base +//! branch's deployment and against the pull request's, and the result kept +//! on the run (`common::ci_repro`, whose module page has the rules). +//! +//! - [`read_failure`] reads what the failure comment, the check's +//! annotations and the job's log say: the failing test, its error, the +//! screenshot and the report link. +//! - [`compare`] runs that test with the head's test code against staging +//! and against the preview in the sandbox, once per head and check, and +//! records both sides on the run (`ci_repro`). +//! - [`from_ci`] records, for each failing check, its result on the base +//! branch's head next to this head's. +//! - [`screenshot`] fetches the failure's screenshot so the fixer sees it. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::ci_repro::{self, Evidence, Leg, Record}; +use common::e2e::test_package; +use tracing::{info, warn}; + +use crate::agent::provider::ModelProvider; +use crate::clients::github::GitHubClient; +use crate::models::TicketMessage; +use crate::WorkerState; + +/// The comparisons kept on the run. +pub(crate) async fn load(state: &WorkerState, team_id: &str, run_id: &str) -> Vec { + state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.to_string())) + .projection_expression("#f") + .expression_attribute_names("#f", ci_repro::FIELD) + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| i.get(ci_repro::FIELD).and_then(|v| v.as_s().ok()).cloned()) + .map(|s| ci_repro::from_json(&s)) + .unwrap_or_default() +} + +/// Keeps `r` on the run (in place of an older one for its head and check), +/// and says it on the run page when `say` (a test run again; a check's own +/// results are kept quietly). +pub(crate) async fn record(state: &WorkerState, team_id: &str, run_id: &str, r: Record, say: bool) { + let line = r.line(); + let all = ci_repro::upsert(&load(state, team_id, run_id).await, r); + let saved = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.to_string())) + .update_expression("SET #f = :v") + .expression_attribute_names("#f", ci_repro::FIELD) + .expression_attribute_values(":v", AttributeValue::S(ci_repro::to_json(&all))) + .send() + .await; + if let Err(e) = saved { + warn!(run_id, error = %e, "Could not keep the failing test's comparison on the run"); + } + if say { + super::add_progress_note( + state, + team_id, + run_id, + &format!("Failing check compared with the base branch: {line}"), + ) + .await; + } +} + +fn is_reporter(c: &serde_json::Value) -> bool { + let login = c["user"]["login"].as_str().unwrap_or(""); + let bot = c["user"]["type"].as_str() == Some("Bot") || login.ends_with("[bot]"); + bot && !super::is_own_login(login) +} + +/// What the failure's own report says: the newest end-to-end comment on the +/// pull request (by a CI reporter), else the job's log (`logs`, which holds +/// the annotations too). `None` when nothing names a failure. +pub(crate) async fn read_failure( + github: &GitHubClient, + owner: &str, + repo: &str, + pr: u64, + check: &str, + logs: &str, +) -> Option { + let comment = github + .list_issue_comments(owner, repo, pr) + .await + .unwrap_or_default() + .iter() + .rev() + .filter(|c| is_reporter(c)) + .map(|c| c["body"].as_str().unwrap_or("").to_string()) + .find(|b| super::e2e_reads::is_e2e_name(b)) + .unwrap_or_default(); + evidence_of(check, &comment, logs) +} + +/// [`read_failure`] from what was read. +pub(crate) fn evidence_of(check: &str, comment: &str, logs: &str) -> Option { + let read = common::e2e::failure_read::read( + check, + &common::e2e::failure_read::Sources { + comment: comment.to_string(), + annotations: Vec::new(), + log: logs.to_string(), + }, + ) + .ok()?; + if read.tests.is_empty() && read.error.trim().is_empty() { + return None; + } + Some(Evidence { + check: check.to_string(), + tests: read.tests, + error: read.error, + source: read.source, + shots: ci_repro::shots_in(comment), + report: super::e2e_reads::comment_verdict(comment).and_then(|v| v.report), + }) +} + +/// For each failing check, its result on the base branch's head next to +/// this head's (`ci` records), kept on the run. +pub(crate) async fn from_ci( + state: &WorkerState, + github: &GitHubClient, + msg: &TicketMessage, + run_id: &str, + head: &str, + failing: &[String], +) -> Vec { + let (owner, repo) = (&msg.repo_owner, &msg.repo_name); + let base = &msg.base_branch; + let base_sha = Some(super::round::branch_head(github, owner, repo, base).await) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| base.clone()); + let Ok(checks) = github.list_ci_for_ref(owner, repo, &base_sha).await else { + return Vec::new(); + }; + let mut out = Vec::new(); + for check in failing { + let base_failed = base_result(&checks, check); + let r = ci_repro::from_checks(head, &base_sha, check, base_failed); + record(state, &msg.team_id, run_id, r.clone(), false).await; + out.push(r); + } + out +} + +/// A check's result on a ref (`Some(true)`: failed), by its name or the +/// workflow it belongs to; `None` when it didn't run there. +fn base_result(checks: &serde_json::Value, name: &str) -> Option { + let runs = checks["check_runs"].as_array()?; + let mut seen = None; + for r in runs { + let n = r["name"].as_str().unwrap_or(""); + if n != name && !n.starts_with(&format!("{name} /")) && !name.starts_with(&format!("{n} /")) + { + continue; + } + match r["conclusion"].as_str().unwrap_or("") { + "failure" | "timed_out" => return Some(true), + "success" => seen = Some(false), + _ => {} + } + } + seen +} + +/// The failing test run with the head's test code against the base +/// branch's deployment and against this pull request's, once per head and +/// check, kept on the run. `None` when the evidence names no test. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn compare( + state: &WorkerState, + msg: &TicketMessage, + github: &GitHubClient, + provider: &ModelProvider, + run_id: &str, + (pr, branch, head): (u64, &str, &str), + ev: &Evidence, +) -> Option { + let test = ev.tests.first()?.clone(); + if let Some(r) = load(state, &msg.team_id, run_id) + .await + .into_iter() + .rev() + .find(|r| r.source == "sandbox" && r.head == head && r.tests.first() == Some(&test)) + { + return Some(r); + } + let (owner, repo) = (&msg.repo_owner, &msg.repo_name); + let mut r = Record { + head: head.to_string(), + check: ev.check.clone(), + tests: vec![test.clone()], + source: "sandbox".into(), + at: chrono::Utc::now().to_rfc3339(), + ..Default::default() + }; + let not_run = |r: &mut Record, why: &str| { + r.base.note = why.to_string(); + r.change.note = why.to_string(); + }; + let (spec, title) = ci_repro::spec_and_title(&test); + let tree: Vec = match github.get_tree(owner, repo, head).await { + Ok(t) => t.into_iter().map(|e| e.path).collect(), + Err(e) => { + not_run(&mut r, &format!("the head's files couldn't be read ({e})")); + record(state, &msg.team_id, run_id, r.clone(), true).await; + return Some(r); + } + }; + let Some(path) = tree + .iter() + .find(|p| p.ends_with(&spec) || p.ends_with(&format!("/{spec}"))) + .cloned() + else { + not_run(&mut r, &format!("`{spec}` isn't a file on the head")); + record(state, &msg.team_id, run_id, r.clone(), true).await; + return Some(r); + }; + // The package the spec lives in, and its runner. + let mut texts: HashMap = HashMap::new(); + let dir = test_package::package_dir(&tree, &path).unwrap_or_default(); + for p in [format!("{dir}/package.json"), "package.json".to_string()] { + let p = p.trim_start_matches('/').to_string(); + if let Ok(t) = github.read_file(owner, repo, &p, head).await { + texts.insert(p, t); + } + } + let pkg = test_package::package_of(&tree, &path, &|p| texts.get(p).cloned()); + let Some(pkg) = pkg.filter(|p| p.runner == Some(test_package::Runner::Playwright)) else { + not_run( + &mut r, + "the spec's runner isn't Playwright, the one CoderHelm runs against an address", + ); + record(state, &msg.team_id, run_id, r.clone(), true).await; + return Some(r); + }; + let rel = path + .strip_prefix(&format!("{}/", pkg.dir)) + .unwrap_or(&path) + .to_string(); + // Where each side runs: the configured test address and the preview, + // else the staging address the repository's end-to-end setup names. + let configured = test_address(state, &msg.team_id, &format!("{owner}/{repo}")).await; + let mut setup: Vec<(String, String)> = Vec::new(); + for p in tree + .iter() + .filter(|p| { + let low = p.to_ascii_lowercase(); + low.contains("playwright.config") + || (low.starts_with(".github/workflows/") + && (low.contains("e2e") || low.contains("playwright"))) + }) + .take(6) + { + if let Ok(t) = github.read_file(owner, repo, p, head).await { + setup.push((p.clone(), t)); + } + } + let base_url = ci_repro::base_target(configured.as_deref(), &setup); + let preview = super::preview::load(state, &msg.team_id, run_id) + .await + .filter(|p| p.head == head && !p.url.trim().is_empty()) + .map(|p| p.url); + let change_url = preview.or_else(|| { + configured + .as_deref() + .filter(|c| c.contains("{pr}")) + .map(|c| c.replace("{pr}", &pr.to_string())) + }); + r.base.target = base_url.clone().unwrap_or_default(); + r.change.target = change_url.clone().unwrap_or_default(); + let Some(base_url) = base_url else { + not_run( + &mut r, + "no address for the base branch's deployment: the Tests settings have none without `{pr}`, and the end-to-end setup names no staging address", + ); + record(state, &msg.team_id, run_id, r.clone(), true).await; + return Some(r); + }; + let mut legs: Vec<(&str, String)> = Vec::new(); + match ci_repro::leg_cmd(&pkg.dir, &rel, &title, &base_url) { + Some(c) => legs.push(("base", c)), + None => r.base.note = format!("`{base_url}` can't be run against"), + } + match change_url + .as_deref() + .and_then(|u| ci_repro::leg_cmd(&pkg.dir, &rel, &title, u)) + { + Some(c) => legs.push(("change", c)), + None => r.change.note = "no preview address for this pull request's head".into(), + } + if legs.is_empty() { + record(state, &msg.team_id, run_id, r.clone(), true).await; + return Some(r); + } + if state.config.sandbox_bucket_name.is_empty() || state.config.sandbox_project_name.is_empty() { + not_run(&mut r, "no sandbox here to run the test"); + record(state, &msg.team_id, run_id, r.clone(), true).await; + return Some(r); + } + // The team's agent permissions decide whether the commands may run. + let gate = crate::agent::policy::gate( + state, + provider.scope.ctx(common::agent_policy::Agent::Coder), + None, + ); + let install = test_package::install_cmd(&pkg); + let mut steps: Vec<(&str, String)> = vec![("install", install)]; + steps.extend(legs); + for (side, cmd) in &steps { + if !matches!( + gate.check_command( + cmd, + "Run the failing test against the base branch and the preview" + ) + .await, + common::agent_policy::Outcome::Run { .. } + ) { + not_run( + &mut r, + &format!("the team's agent permissions don't allow the {side} command"), + ); + record(state, &msg.team_id, run_id, r.clone(), true).await; + return Some(r); + } + } + let sandbox = crate::clients::sandbox::SandboxClient::new( + &state.codebuild, + &state.s3, + &state.logs, + &state.config.sandbox_bucket_name, + &state.config.sandbox_project_name, + ) + .with_egress(crate::agent::policy::sandbox_egress(state, &msg.team_id).await); + let source = match sandbox + .ensure_source(run_id, head, || github.download_tarball(owner, repo, head)) + .await + { + Ok(k) => k, + Err(e) => { + not_run( + &mut r, + &format!("the branch couldn't be prepared in the sandbox ({e})"), + ); + record(state, &msg.team_id, run_id, r.clone(), true).await; + return Some(r); + } + }; + let script = ci_repro::script(&steps); + let node = super::detect_node_version(github, owner, repo, branch).await; + match sandbox + .run_checks(&source, &script, node.as_deref(), None, None) + .await + { + Ok(o) if o.ran => { + for (side, leg) in [("base", &mut r.base), ("change", &mut r.change)] { + let target = leg.target.clone(); + if let Some(out) = ci_repro::split(&o.output, side) { + *leg = ci_repro::leg_of(&target, &out); + } else if leg.note.is_empty() { + *leg = Leg { + target, + note: "no output".into(), + ..Default::default() + }; + } + } + } + Ok(o) => not_run( + &mut r, + &format!("the sandbox gave no result ({})", o.reason), + ), + Err(e) => not_run(&mut r, &format!("the sandbox couldn't run ({e})")), + } + info!(run_id, verdict = ?r.verdict(), "Failing test compared with the base branch"); + record(state, &msg.team_id, run_id, r.clone(), true).await; + Some(r) +} + +/// The team's test address for the repository (Tests settings), as set. +async fn test_address(state: &WorkerState, team_id: &str, repo: &str) -> Option { + let st = common::e2e::store::Store::new(&state.dynamo, &state.config.tests_table_name); + if !st.enabled() { + return None; + } + let s = st.settings(team_id).await.ok()?; + let t = s.report_source(repo)?.target_url.trim().to_string(); + (!t.is_empty()).then_some(t) +} + +/// Whether CoderHelm fetches an image from `host`: GitHub's attachment and +/// user content hosts, and the team's own domains. +pub(crate) fn image_host_allowed(host: &str, path: &str, team_domains: &[String]) -> bool { + let h = host.to_ascii_lowercase(); + (h == "github.com" && path.starts_with("/user-attachments/")) + || h.ends_with(".githubusercontent.com") + || team_domains + .iter() + .any(|d| h == *d || h.ends_with(&format!(".{d}"))) +} + +/// The failure's screenshot, kept in the run's own storage so the fixer's +/// first message carries it as an image. `None` when it can't be fetched +/// (an unknown host, not an image, too large). +pub(crate) async fn screenshot( + state: &WorkerState, + team_id: &str, + run_id: &str, + url: &str, +) -> Option { + let (u, host) = super::web_check::vet_url(url).ok()?; + let domains = super::web_check::team_domains(state, team_id).await; + if !image_host_allowed(&host, u.path(), &domains) { + info!(run_id, %host, "The failure's screenshot is on a host CoderHelm doesn't fetch from; its link goes to the fixer"); + return None; + } + let addrs = tokio::net::lookup_host((host.as_str(), 443)).await.ok()?; + let addrs: Vec<_> = addrs.collect(); + if addrs.is_empty() || !addrs.iter().all(|a| super::web_check::is_public_ip(a.ip())) { + return None; + } + let resp = tokio::time::timeout( + std::time::Duration::from_secs(20), + state.http.get(u.as_str()).send(), + ) + .await + .ok()? + .ok()?; + if !resp.status().is_success() { + return None; + } + let media = resp + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .split(';') + .next() + .unwrap_or("") + .trim() + .to_string(); + if !matches!( + media.as_str(), + "image/png" | "image/jpeg" | "image/webp" | "image/gif" + ) { + return None; + } + let bytes = resp.bytes().await.ok()?; + if bytes.is_empty() || bytes.len() > 5 * 1024 * 1024 { + return None; + } + let ext = media.trim_start_matches("image/"); + let key = format!( + "ci-evidence/{team_id}/{run_id}/{}.{ext}", + chrono::Utc::now().timestamp_millis() + ); + state + .s3 + .put_object() + .bucket(&state.config.bucket_name) + .key(&key) + .content_type(&media) + .body(bytes.to_vec().into()) + .send() + .await + .ok()?; + Some(crate::models::ImageAttachment { + s3_key: key, + media_type: media, + filename: "failure-screenshot".into(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn the_failure_comment_gives_the_test_the_error_and_the_screenshot() { + let comment = "## Playwright E2E results for eb32df1\n\n1 failed, 40 passed\n\n 1) [chromium] › tests/browse/camp-registration.spec.ts:88:7 › Camp registration › selecting a camp adds it to the cart while registration is open\n\n Error: expect(locator).not.toHaveText(expected) failed\n Received: Subtotal$0\n\n![failure](https://github.com/user-attachments/assets/shot.png)\n\n[Full report](https://reports.example.com/pr-12/index.html)"; + let ev = evidence_of("E2E on preview", comment, "").unwrap(); + assert_eq!( + ev.tests, + vec!["tests/browse/camp-registration.spec.ts › selecting a camp adds it to the cart while registration is open".to_string()] + ); + assert!(ev + .error + .starts_with("Error: expect(locator).not.toHaveText")); + assert_eq!( + ev.shots, + vec!["https://github.com/user-attachments/assets/shot.png".to_string()] + ); + assert_eq!( + ev.report.as_deref(), + Some("https://reports.example.com/pr-12/index.html") + ); + assert!(evidence_of("x", "", "").is_none()); + } + + #[test] + fn a_check_on_the_base_is_found_by_name_or_workflow() { + let checks = json!({"check_runs": [ + {"name": "Test Suite", "conclusion": "success"}, + {"name": "E2E after staging deploy / Playwright e2e (all tests)", "conclusion": "failure"} + ]}); + assert_eq!(base_result(&checks, "Test Suite"), Some(false)); + assert_eq!(base_result(&checks, "E2E after staging deploy"), Some(true)); + assert_eq!(base_result(&checks, "Deploy Preview"), None); + } + + #[test] + fn images_come_only_from_known_hosts() { + let team = vec!["example.com".to_string()]; + assert!(image_host_allowed( + "github.com", + "/user-attachments/assets/x", + &team + )); + assert!(image_host_allowed( + "private-user-images.githubusercontent.com", + "/x.png", + &team + )); + assert!(image_host_allowed( + "reports.example.com", + "/pr-1/a.png", + &team + )); + assert!(!image_host_allowed( + "github.com", + "/acme/site/pull/1", + &team + )); + assert!(!image_host_allowed("evil.test", "/a.png", &team)); + } +} diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index 3ff00e23b..8d82ce8d0 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -425,6 +425,11 @@ fn same_head(stamped: &str, head: &str) -> bool { /// the writer version is never current: an upgrade rebuilds it. A stamp /// from before the digest answers for its head and writer alone. pub fn is_current(body: &str, head: &str) -> bool { + // A "CI is failing" section is checked against the head's checks on + // every look (`common::ci_lines`): it goes once they show no failure. + if common::ci_lines::failing_head(body).is_some() { + return false; + } match stamp_all(body) { Some(s) => { !head.is_empty() @@ -892,6 +897,7 @@ async fn build( None if fresh => (fresh_base(&body), None), None => (body.clone(), None), }; + let base = ci_lines_for_head(state, github, team_id, owner, repo, number, &head, &base).await; // The facts of this head, and the description as a view of them: every // written sentence checked, the lead rendered, the rest collapsed. let next = match gather(state, github, team_id, owner, repo, number).await { @@ -951,6 +957,60 @@ async fn build( } } +/// The lines CoderHelm wrote about the pull request's CI, true for `head` +/// (`common::ci_lines::reconcile`): "CI is failing" goes once the head moved +/// or its checks show no failure, a revert's "Deferred" line once its work +/// is back. When the run's failures were compared, no sentence calls one +/// the base branch's, flaky or not this change's without a comparison on +/// this head that shows it (`common::ci_repro::hold_blame`). +#[allow(clippy::too_many_arguments)] +async fn ci_lines_for_head( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + owner: &str, + repo: &str, + number: u64, + head: &str, + body: &str, +) -> String { + let checks = github.list_ci_for_ref(owner, repo, head).await.ok(); + let ci = common::ci_lines::HeadCi { + head: head.to_string(), + read: checks.is_some(), + failing: checks + .as_ref() + .map(|c| super::resume::failing_check_names(c).into_iter().collect()) + .unwrap_or_default(), + }; + let mut undone: std::collections::HashSet = std::collections::HashSet::new(); + for m in common::ci_lines::reverts_in(body) { + if let Ok(changed) = github.compare_changed_files(owner, repo, &m.to, head).await { + if m.paths.iter().any(|p| changed.contains(p)) { + undone.insert(m.to.clone()); + } + } + } + let out = common::ci_lines::reconcile(body, &ci, &|m| undone.contains(&m.to)); + let Some(run_id) = + super::review_pr::lookup_run_by_pr(state, team_id, owner, repo, number).await + else { + return out; + }; + let records = super::ci_repro::load(state, team_id, &run_id).await; + if records.is_empty() { + return out; + } + let (held, changed) = common::ci_repro::hold_blame(&out, &records, head); + if changed { + warn!( + pr_number = number, + "The description blamed a failure on the base branch with no comparison on record; that sentence was replaced" + ); + } + held +} + /// The catch-up's rebuild of a run's pull request after an upgrade: when /// the description is wholly CoderHelm's ([`catch_up`] says Rebuild), it is /// built again from the facts of the head alone and nothing of the earlier diff --git a/services/worker/src/passes/incidents/cr_red_on_every_branch.rs b/services/worker/src/passes/incidents/cr_red_on_every_branch.rs new file mode 100644 index 000000000..5d309563c --- /dev/null +++ b/services/worker/src/passes/incidents/cr_red_on_every_branch.rs @@ -0,0 +1,219 @@ +//! cr. A pull request that removed a link from a camp registration page +//! had its end-to-end check fail on a test it had edited: "selecting a camp +//! adds it to the cart while registration is open". The vendor portal the +//! page embeds had just opened registration, and a visitor who isn't signed +//! in gets the vendor's sign-in drawer instead of a cart line, so the test +//! was red on every branch, the base branch's staging deployment included. +//! The failure comment on the pull request named the test, its error +//! (`Subtotal$0`) and had a screenshot of the drawer. +//! +//! The run never compared the test with the base branch. A fix attempt +//! wrote that a different spec was "broken on main"; with the check still +//! red, the supervisor reverted seven of the pull request's own files to an +//! older head whose checks had passed, and the check failed the same way on +//! the result. The pull request said "CI is failing" with a lint warning +//! and a line of the workflow script as the error, "Deferred: reverted 7 +//! file(s)" after the work had come back, and the run wrote that it +//! couldn't confirm what the test saw. Four other runs that week reverted +//! their own work the same way with no comparison, one of them for a cloud +//! account's load balancer limit in the preview deploy. +//! +//! Guarantee: before a CI fix round the failure is read from its own report +//! (the failing test, its error, the screenshot, the report link), the +//! failing test is run with the head's test code against the base branch's +//! deployment and against the pull request's preview, and both results are +//! kept on the run (`common::ci_repro`); each failing check's result on the +//! base branch's head is kept next to this head's. The fixer gets all of it, +//! the screenshot as an image. A revert of CoderHelm's own work needs a +//! record on the head that shows the change makes a check fail; a failure +//! red on the base too is fixed on the branch (the test or the code it +//! checks) and said, never reverted. No sentence CoderHelm writes calls a +//! failure the base branch's, flaky or not this change's without that +//! record, and none says a failure couldn't be confirmed while its report +//! was read. The "CI is failing" section names its head and goes once the +//! head moves or its checks show no failure; a revert's "Deferred" line goes +//! once its files are back. + +use super::fixture::fn_src; +use crate::passes::{ci_repro, resume}; +use common::ci_lines::{self, HeadCi}; +use common::ci_repro::{self as repro, Leg, Record, RevertGate, Verdict}; + +const HEAD: &str = "eb32df14230678e5"; +const TEST: &str = "tests/browse/camp-registration.spec.ts › selecting a camp adds it to the cart while registration is open"; + +/// The e2e reporter's comment on the pull request, as it was posted. +fn failure_comment() -> String { + [ + "## Playwright E2E results for eb32df1", + "", + "1 failed, 52 passed", + "", + " 1) [chromium] › tests/browse/camp-registration.spec.ts:141:7 › Camp registration › selecting a camp adds it to the cart while registration is open", + "", + " Error: Choosing \"Acme Mini-Camp (AM session)\" did not add it to the portal's Order Summary", + " expect(locator).not.toHaveText(expected) failed", + " Received: Subtotal$0", + "", + "![failure](https://github.com/user-attachments/assets/0b7a-camp-drawer.png)", + "", + "[Full report](https://e2e-reports.example.com/pr-12/index.html)", + ] + .join("\n") +} + +/// What the sandbox printed for each side: red on staging and on the +/// preview alike. +fn compared() -> Record { + let red = "Running 1 test using 1 worker\n 1) [chromium] › tests/browse/camp-registration.spec.ts:141:7 › selecting a camp\n Error: expect(locator).not.toHaveText(expected) failed\n Received: Subtotal$0\n 1 failed\n"; + Record { + head: HEAD.into(), + check: "Deploy Preview".into(), + tests: vec![TEST.into()], + base: repro::leg_of("https://staging-shop.example.com", red), + change: repro::leg_of("https://pr-12.preview.example.com", red), + source: "sandbox".into(), + at: String::new(), + } +} + +#[test] +fn the_failure_is_read_from_its_report_and_compared_with_the_base() { + let ev = ci_repro::evidence_of("Deploy Preview", &failure_comment(), "").expect("read"); + assert_eq!(ev.tests, vec![TEST.to_string()]); + assert!(ev.error.contains("did not add it to the portal's Order Summary"), "{ev:?}"); + assert_eq!( + ev.shots, + vec!["https://github.com/user-attachments/assets/0b7a-camp-drawer.png".to_string()] + ); + assert!(ci_repro::image_host_allowed("github.com", "/user-attachments/assets/0b7a-camp-drawer.png", &[])); + // The test runs against both addresses with the head's test code. + let (spec, title) = repro::spec_and_title(TEST); + let cmd = repro::leg_cmd("e2e", &spec, &title, "https://staging-shop.example.com").unwrap(); + assert!(cmd.contains("--grep 'selecting a camp adds it to the cart while registration is open'"), "{cmd}"); + assert!(cmd.contains("--retries=0")); + + let r = compared(); + assert!(r.base.red() && r.change.red()); + assert!(matches!(r.verdict(), Verdict::NotThisChange(_))); + + // The fixer reads the error, sees the screenshot and is told what a + // failure red on the base means for the fix. + let brief = repro::brief(Some(&ev), std::slice::from_ref(&r), HEAD); + assert!(brief.contains("Subtotal$0") || brief.contains("Order Summary"), "{brief}"); + assert!(brief.contains("0b7a-camp-drawer.png"), "{brief}"); + assert!(brief.contains("attached to this message as an image")); + assert!(brief.contains("Fix the test, or the code it checks, on this branch"), "{brief}"); + assert!(brief.contains("Never revert this pull request's work for it")); +} + +#[test] +fn nothing_is_reverted_without_a_comparison_that_shows_the_change_caused_it() { + // Red on the base too: the seven files stay. + match repro::may_revert(&[compared()], HEAD) { + RevertGate::Refused(why) => assert!(why.contains("fails on the base branch too"), "{why}"), + g => panic!("reverted: {g:?}"), + } + // No comparison at all (the check that failed doesn't run on the base, + // as a preview deploy that hit the cloud account's limit): nothing comes + // out either. + let infra = repro::from_checks(HEAD, "121ea38c", "Deploy Preview", None); + assert!(matches!(repro::may_revert(&[infra], HEAD), RevertGate::Refused(_))); + // A comparison on an older head proves nothing about this one. + let ours = Record { + base: Leg { target: "s".into(), ran: true, passed: 1, failed: 0, note: String::new() }, + ..compared() + }; + assert!(matches!(repro::may_revert(std::slice::from_ref(&ours), HEAD), RevertGate::Allowed(_))); + assert!(matches!(repro::may_revert(&[ours], "b66dfd3d06d9"), RevertGate::Refused(_))); + + // The pipeline: the gate comes before anything is chosen to come out, + // and a refusal returns before a write. + let src = include_str!("../resume.rs"); + let revert = fn_src(src, "async fn revert_to_green("); + let gate = revert.find("ci_repro::may_revert(").expect("the revert asks the gate"); + assert!(gate < revert.find("sup::revert_for(").unwrap()); + assert!(gate < revert.find("apply_revert(").unwrap()); + assert!(revert.find("revert_dep_commit(").unwrap() < gate, "a dependency run keeps its own revert"); +} + +#[test] +fn blame_and_unconfirmed_need_the_record_and_the_report() { + // The first attempt's account, before anything was compared. + let said = "The `summer camp pricing` spec is broken on main since #1545; nothing in this diff touches it."; + let held = resume::held_tried(&[said.to_string()], &[], HEAD, ""); + assert!(!held[0].contains("broken on main"), "{held:?}"); + assert!(held[0].contains(repro::BLAME_HELD)); + // With the comparison on record, the line that says so stays. + let shown = "Fails on the base branch too: the test fails on staging as well."; + assert_eq!(resume::held_tried(&[shown.to_string()], &[compared()], HEAD, ""), vec![shown.to_string()]); + + // "Couldn't confirm" while the report was read is replaced by it. + let ev = ci_repro::evidence_of("Deploy Preview", &failure_comment(), "").unwrap(); + let unsure = "I couldn't confirm what the e2e test saw on the portal."; + let held = resume::held_tried(&[unsure.to_string()], &[compared()], HEAD, &ev.line()); + assert!(held[0].starts_with("The failure's report says: `Deploy Preview` failed in `tests/browse/camp-registration.spec.ts"), "{held:?}"); + assert!(held[0].contains("screenshot: https://github.com/user-attachments/assets/0b7a-camp-drawer.png")); + + // The pipeline: every account goes through the hold before the pull + // request, and the fixer's message carries the brief and the shot. + let src = include_str!("../resume.rs"); + let hand = fn_src(src, "async fn hand_off_red_ci("); + assert!(hand.find("held_tried(").unwrap() < hand.find("ci_failing_section(").unwrap()); + assert!(src.contains("Failure summary:\\n{failure_logs}{repro_brief}")); + assert!(src.contains("super::ci_repro::compare(")); + assert!(src.contains("super::ci_repro::screenshot(")); + assert!(src.contains("let e2e_on_base = on_base.iter().any(|c| super::e2e_reads::is_e2e_name(c));")); +} + +#[test] +fn the_error_quoted_is_the_tests_never_the_workflow_script() { + let logs = [ + "2026-11-17T04:36:58.1Z ✖ 1 problem (0 errors, 1 warning)", + "2026-11-17T04:36:58.2Z 0 errors and 1 warning potentially fixable with the `--fix` option.", + "2026-11-17T04:37:00.7683325Z \u{1b}[36;1m# With a build ID, also wait until the page is served by that build\u{1b}[0m", + "2026-11-17T15:22:44.6320006Z Error: Choosing \"Acme Mini-Camp (AM session)\" did not add it to the portal's Order Summary", + "2026-11-17T15:22:44.6320874Z expect(locator).not.toHaveText(expected) failed", + ] + .join("\n"); + let e = resume::failure_excerpt(&logs); + assert!(e.starts_with("Error: Choosing"), "{e}"); +} + +#[test] +fn the_ci_lines_are_true_for_the_head() { + let section = resume::ci_failing_section( + "43f1bdd46cc6", + &["Deploy Preview".to_string()], + "Error: Choosing a camp did not add it", + &[], + "CoderHelm fixes the test on this branch.", + ); + let body = format!( + "Source ticket: SHOP-12\n\n{section}\n\nRemoves the new-tab link.\n\n## Deferred\n{}", + ci_lines::revert_line( + "CI stayed red: reverted 7 file(s) to b66dfd3.", + "b66dfd3d06d95895", + &["apps/web/src/components/blocks/portal-embed.tsx".to_string()], + ) + ); + // The work came back on a later head and its checks are running: both + // lines go. + let later = HeadCi { + head: HEAD.into(), + read: true, + failing: vec![], + }; + let out = ci_lines::reconcile(&body, &later, &|m| { + m.paths.iter().any(|p| p.ends_with("portal-embed.tsx")) + }); + assert!(!out.contains("CI is failing"), "{out}"); + assert!(!out.contains("reverted 7 file(s)"), "{out}"); + assert!(!out.contains("## Deferred"), "{out}"); + assert!(out.contains("Removes the new-tab link.")); + // Every build runs it, and a failing section is never "current". + let src = include_str!("../description.rs"); + let build = fn_src(src, "async fn build("); + assert!(build.find("ci_lines_for_head(").unwrap() < build.find("gather(").unwrap()); + assert!(!crate::passes::description::is_current(&body, "43f1bdd46cc6")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 136c0d72d..e02bf13a4 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1258,6 +1258,7 @@ pub mod base_images; pub mod bedrock_sync; mod branch_update; mod checks; +pub(crate) mod ci_repro; pub mod code_graph; mod completeness; pub mod conventions; diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 6075a29f5..acae5078d 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -710,7 +710,7 @@ mod stale_ci_event_tests { } /// Names of the checks that concluded failure or timed_out. -fn failing_check_names(checks: &Value) -> std::collections::BTreeSet { +pub(crate) fn failing_check_names(checks: &Value) -> std::collections::BTreeSet { checks["check_runs"] .as_array() .map(|rs| { @@ -825,6 +825,12 @@ pub(crate) fn failure_excerpt(logs: &str) -> String { let clean = |l: &str| -> String { // GitHub's timestamp prefix (`2026-11-11T19:52:01.1234567Z `). let t = l.trim(); + // A step's command echoed back (`\u{1b}[36;1m...`) is the script, + // never what failed: a pull request once quoted a comment line of + // the workflow as its error. + if t.contains("\u{1b}[36;1m") || t.contains("[36;1m") { + return String::new(); + } let t = match t.split_once(' ') { Some((ts, rest)) if ts.len() >= 20 && ts.as_bytes()[4] == b'-' && ts.ends_with('Z') => { rest @@ -843,6 +849,8 @@ pub(crate) fn failure_excerpt(logs: &str) -> String { MARKS.iter().any(|m| low.contains(m)) && !low.contains("0 failed") && !low.contains("failed: 0") + && !zero_errors(&low) + && !low.contains("potentially fixable") }) else { return String::new(); }; @@ -850,6 +858,13 @@ pub(crate) fn failure_excerpt(logs: &str) -> String { common::truncate_str(&joined, 400).to_string() } +/// A summary that counts no errors (`0 errors and 1 warning`, `(0 errors,`) +/// says nothing failed. +fn zero_errors(low: &str) -> bool { + low.match_indices("0 error") + .any(|(i, _)| i == 0 || !low.as_bytes()[i - 1].is_ascii_digit()) +} + /// Whether a pull request comment is a CI reporter's (a bot that isn't /// CoderHelm): end-to-end and coverage reporters post the failing test's /// name and error there, where the job's own log only says it uploaded them. @@ -1035,9 +1050,11 @@ pub(crate) fn next_attempt_feedback( only shows an upload step.\n\ 3. If a test this pull request added or changed fails, read that test and the code it \ drives, and fix whichever is wrong.\n\ - 4. Only if the failure truly isn't this pull request's (a service outside the repository \ - is down, a secret is missing), write one line starting `Not this change:` naming the \ - check, the error line, and what a person must do.\n\n\ + 4. Never call the failure the base branch's, flaky or not this pull request's unless the \ + comparison of the failing test against the base branch (above) shows it fails there \ + too; then fix the test, or the code it checks, on this branch and say so in one line \ + starting `Fails on the base branch too:`. Never take this pull request's work out to \ + make a check pass.\n\n\ Fresh evidence:\n{fresh}", tried.join("\n") ) @@ -1045,10 +1062,13 @@ pub(crate) fn next_attempt_feedback( /// The pull request's section while CI fails and CoderHelm stopped fixing /// it: the checks, the error, what was tried, what is needed. -pub(crate) const CI_FAILING_START: &str = ""; -pub(crate) const CI_FAILING_END: &str = ""; +pub(crate) const CI_FAILING_START: &str = common::ci_lines::FAILING_START; +/// The section names the head it was written on (`common::ci_lines`): every +/// build of the description takes it out once the head moved or its checks +/// show no failure. pub(crate) fn ci_failing_section( + head: &str, checks: &[String], excerpt: &str, tried: &[String], @@ -1076,22 +1096,13 @@ pub(crate) fn ci_failing_section( lines.push(format!("- **Tried:** {}", tried.join("; "))); } lines.push(format!("- **Needed:** {}", needed.trim())); - format!( - "{CI_FAILING_START}\n## CI is failing\n{}\n{CI_FAILING_END}", - lines.join("\n") - ) + common::ci_lines::failing_section(head, &format!("## CI is failing\n{}", lines.join("\n"))) } /// The description with the CI failing section in place (replacing an older /// one), right after the ticket line. pub(crate) fn with_ci_failing(body: &str, section: &str) -> String { - let mut rest = body.to_string(); - if let (Some(a), Some(b)) = (rest.find(CI_FAILING_START), rest.find(CI_FAILING_END)) { - if b > a { - rest.replace_range(a..b + CI_FAILING_END.len(), ""); - } - } - let rest = rest.replace("\n\n\n\n", "\n\n"); + let rest = common::ci_lines::without_failing(body); let first = rest.lines().next().unwrap_or("").trim().to_string(); let ticket_first = first.starts_with("Source ticket:") || first.starts_with("Closes #") @@ -1320,13 +1331,14 @@ mod ci_triage_tests { let checks = vec!["Deploy Preview".to_string()]; let excerpt = "Error: expect(received).toBeLessThanOrEqual(expected) / Expected: <= 1"; let section = ci_failing_section( + "abc1234", &checks, excerpt, &["3 attempts changed nothing".into()], "a person reads the end-to-end report", ); let body = with_ci_failing("Source ticket: WEB-14\n\n## Summary\nx", §ion); - assert!(body.starts_with("Source ticket: WEB-14\n\n\n## CI is failing\n**CI is failing:** `Deploy Preview`."), "{body}"); + assert!(body.starts_with("Source ticket: WEB-14\n\n\n## CI is failing\n**CI is failing:** `Deploy Preview`."), "{body}"); assert!(body.contains("- **Error:** `Error: expect(received)")); assert!(body.contains("## Summary\nx")); // Written again, it replaces the old section. @@ -1993,7 +2005,13 @@ pub async fn run( }; let (own, base) = split_base_failures(&head_failing, &base_failing); on_base = base; - red_on_base_only = own.is_empty() && !on_base.is_empty(); + // An end-to-end check red on the base too names a + // check, not a test: a different test can fail + // there. It is compared test by test in the fix + // round (`ci_repro`) before anything is called not + // this change's. + let e2e_on_base = on_base.iter().any(|c| super::e2e_reads::is_e2e_name(c)); + red_on_base_only = own.is_empty() && !on_base.is_empty() && !e2e_on_base; if !red_on_base_only && try_rerun_once( state, @@ -2094,7 +2112,7 @@ pub async fn run( } let FixContext { - ticket_msg, + mut ticket_msg, provider, github, mut usage, @@ -2161,7 +2179,12 @@ pub async fn run( } if red_on_base_only { // Every failing check fails on the base branch too: red before - // this PR. Not a fix attempt, and not Coderhelm's to "fix". + // this PR. Not a fix attempt, and not Coderhelm's to "fix". The + // comparison is kept on the run first (`ci_repro`). + if let Some(h) = branch_head.as_deref().filter(|h| !h.is_empty()) { + super::ci_repro::from_ci(state, &github, &ticket_msg, &msg.run_id, h, &on_base) + .await; + } info!( run_id = msg.run_id, checks = ?on_base, @@ -2451,6 +2474,67 @@ pub async fn run( } } + // The failure as its own report says (the failing test, its error, + // the screenshot), and the failing test run against the base + // branch's deployment and this pull request's: on record before any + // fix, revert or "not this change's" (`ci_repro`). + let repro_head = branch_head.clone().unwrap_or_default(); + let evidence = match failing_wf.first() { + Some(check) => { + super::ci_repro::read_failure( + &github, + &repo_owner, + &repo_name, + pr_number, + check, + &logs, + ) + .await + } + None => None, + }; + if !repro_head.is_empty() { + if let Some(ev) = evidence.as_ref().filter(|e| !e.tests.is_empty()) { + if super::round::may_start(start, std::time::Instant::now()) { + super::ci_repro::compare( + state, + &ticket_msg, + &github, + &provider, + &msg.run_id, + (pr_number, &branch, &repro_head), + ev, + ) + .await; + } + } + super::ci_repro::from_ci( + state, + &github, + &ticket_msg, + &msg.run_id, + &repro_head, + &failing_wf, + ) + .await; + } + let repro = super::ci_repro::load(state, &msg.team_id, &msg.run_id).await; + let repro_brief = common::ci_repro::brief(evidence.as_ref(), &repro, &repro_head); + // What the pull request and the run say fails: the report's test and + // error when it was read, never a line of the workflow script. + let excerpt_line = evidence + .as_ref() + .map(|e| e.line()) + .unwrap_or_else(|| failure_excerpt(&logs)); + // The screenshot the failure comment carries is the fixer's to see. + if let Some(shot) = evidence.as_ref().and_then(|e| e.shots.first()) { + if let Some(img) = + super::ci_repro::screenshot(state, &msg.team_id, &msg.run_id, shot).await + { + ticket_msg.image_attachments.push(img); + } + } + // Load checkpoint for review cycle count let cycle = load_cycle_from_checkpoint(state, &msg.team_id, &msg.run_id).await; @@ -2460,7 +2544,7 @@ pub async fn run( state, &msg.team_id, &msg.run_id, - &lock_cause.clone().unwrap_or_else(|| failure_excerpt(&logs)), + &lock_cause.clone().unwrap_or_else(|| excerpt_line.clone()), ) .await; // A lockfile out of sync with its manifest is repaired by code: @@ -2558,7 +2642,7 @@ pub async fn run( wall_clock_secs(created_at, &start), &events, super::GaveUp::Budget, - &failure_excerpt(&logs), + &excerpt_line, &[format!("{cycle} fix cycle(s) on this pull request")], "CoderHelm's fix budget for this run is spent: fix the failing check on this branch, or re-run it if it isn't the change's.", ) @@ -2590,7 +2674,7 @@ pub async fn run( wall_clock_secs(created_at, &start), &events, super::GaveUp::Stalled, - &failure_excerpt(&logs), + &excerpt_line, &["the same failure came back after each fix".to_string()], "A person looks at the failing check: CoderHelm's fixes keep meeting the same failure.", ) @@ -2635,13 +2719,23 @@ pub async fn run( } else { format!("\n\nPR review comments (also address if relevant):\n{review_feedback}") }; - let base_note = if on_base.is_empty() { + // A check red on the base too is left alone, except an end-to-end + // one: its failing test is compared with the base below. + let base_plain: Vec<&String> = on_base + .iter() + .filter(|c| !super::e2e_reads::is_e2e_name(c)) + .collect(); + let base_note = if base_plain.is_empty() { String::new() } else { format!( "\n\nThese checks also fail on {base_branch}, so this PR did not cause them. \ Leave them alone: {}.", - on_base.join(", ") + base_plain + .iter() + .map(|c| c.as_str()) + .collect::>() + .join(", ") ) }; @@ -2659,7 +2753,7 @@ pub async fn run( - NEVER replace a real file with a stub or placeholder to make an error go away — write the complete, working implementation. If you broke a file, use restore_file to recover it, then fix it properly.\n\ - Before you finish, call run_checks to verify your fix builds and type-checks against real output. Do not finish on a red result if run_checks is available.\n\ - You may create new test files or edit existing ones if needed.\n\n\ - Failure summary:\n{failure_logs}\n\n\ + Failure summary:\n{failure_logs}{repro_brief}\n\n\ Full logs:\n{logs}{review_context}{base_note}{lock_context}" ); @@ -2824,7 +2918,7 @@ pub async fn run( wall_clock_secs(created_at, &start), &events, super::GaveUp::Budget, - &failure_excerpt(&logs), + &excerpt_line, &tried, "The failing check needs a change CoderHelm's fix rounds didn't reach in their time: fix it on this branch, or press Retry to give the run a new budget.", ) @@ -2895,9 +2989,14 @@ pub async fn run( .map(str::trim) .find(|l| !l.is_empty()) .unwrap_or("no explanation"); + // Its account goes on the pull request only as + // far as the record bears it out. + let said = + held_tried(&[said.to_string()], &repro, &repro_head, &excerpt_line) + .remove(0); tried.push(format!( "attempt {attempt} changed nothing ({})", - common::truncate_str(said, 240) + common::truncate_str(&said, 240) )); if attempt < max_attempts && super::round::may_start(start, std::time::Instant::now()) @@ -3000,7 +3099,7 @@ pub async fn run( wall_clock_secs(created_at, &start), &events, super::GaveUp::NoChange, - &failure_excerpt(&logs), + &excerpt_line, &tried, "A person reads the failing check's report (its test name and error are above) and fixes it on this branch, or re-runs it if the failure isn't this change's.", ) @@ -3134,7 +3233,7 @@ pub async fn run( wall_clock_secs(created_at, &start), &events, super::GaveUp::FixError, - &failure_excerpt(&logs), + &excerpt_line, &tried, "Retry the run from its page, or fix the failing check on this branch.", ) @@ -3181,7 +3280,7 @@ pub async fn run( wall_clock_secs(created_at, &start), &events, super::GaveUp::NoProgress, - &failure_excerpt(&logs), + &excerpt_line, &["fixes stopped changing the code (same files, same bytes)".to_string()], "A person looks at the failing check: CoderHelm's fixes stopped changing the code.", ) @@ -6896,6 +6995,27 @@ fn failing_workflows(events: &[RunEvent]) -> Vec { .collect() } +/// What the fix attempts said, as far as the record bears it out: a line +/// that calls the failure the base branch's, flaky or not this change's +/// with no comparison on this head that shows it, or that says the failure +/// couldn't be confirmed while its report was read (`excerpt`), is +/// replaced (`common::ci_repro::hold_blame`, `hold_unread`). +pub(crate) fn held_tried( + tried: &[String], + records: &[common::ci_repro::Record], + head: &str, + excerpt: &str, +) -> Vec { + let read = Some(excerpt).filter(|e| !e.trim().is_empty()); + tried + .iter() + .map(|t| { + let (t, _) = common::ci_repro::hold_blame(t, records, head); + common::ci_repro::hold_unread(&t, read).0 + }) + .collect() +} + /// The one way a run stops fixing a red CI: the pull request says what /// fails (the check, the error, what was tried, what is needed), stays a /// draft through the one ready decision (`ready::decide` holds on a failing @@ -6967,7 +7087,12 @@ async fn hand_off_red_ci( ) .await; } - let section = ci_failing_section(&checks, excerpt, tried, needed); + // What the fix rounds said goes on the pull request only as far as the + // record bears it out (`common::ci_repro`). + let head = super::round::branch_head(github, pr.owner, pr.repo, pr.branch).await; + let records = super::ci_repro::load(state, &msg.team_id, &msg.run_id).await; + let tried = held_tried(tried, &records, &head, excerpt); + let section = ci_failing_section(&head, &checks, excerpt, &tried, needed); match github.get_pull_request(pr.owner, pr.repo, pr.number).await { Ok(p) => { let body = with_ci_failing(p["body"].as_str().unwrap_or(""), §ion); @@ -7061,10 +7186,14 @@ pub(crate) async fn end_red_ci_rounds( checks.to_vec() }; let ending = super::supervisor::end_of_rounds(&[], &tried.join("; "), &failing); + let head = super::round::branch_head(github, pr.owner, pr.repo, branch).await; + let records = super::ci_repro::load(state, &msg.team_id, run_id).await; + let held = held_tried(tried, &records, &head, excerpt); let section = ci_failing_section( + &head, checks, excerpt, - tried, + &held, "Nothing on this branch can come out to make these checks pass, so the run ended \ failed with this cause; the pull request stays a draft while they fail.", ); @@ -7146,7 +7275,8 @@ async fn finish_security_red( excerpt: &str, tried: &[String], ) -> Result<(), Box> { - let section = ci_failing_section(checks, excerpt, tried, SECURITY_RED_NEEDED); + let head = super::round::branch_head(github, pr.owner, pr.repo, pr.branch).await; + let section = ci_failing_section(&head, checks, excerpt, tried, SECURITY_RED_NEEDED); match github.get_pull_request(pr.owner, pr.repo, pr.number).await { Ok(p) => { let body = with_ci_failing(p["body"].as_str().unwrap_or(""), §ion); @@ -7213,6 +7343,38 @@ async fn revert_to_green( if let Some(note) = revert_dep_commit(state, msg, ticket_msg, github, pr, excerpt).await { return Some(note); } + // Nothing comes out without a comparison on this head that shows this + // change makes a check fail (`common::ci_repro::may_revert`): a failure + // red on the base branch too, or one nobody compared, is not a reason + // to take the pull request's work out. The checks' own results on the + // base branch are compared here when nothing else is on record. + let head = super::round::branch_head(github, pr.owner, pr.repo, pr.branch).await; + let mut records = super::ci_repro::load(state, &msg.team_id, &msg.run_id).await; + if common::ci_repro::on_head(&records, &head).is_empty() && !head.is_empty() { + let failing: Vec = match github.list_ci_for_ref(pr.owner, pr.repo, &head).await { + Ok(c) => failing_check_names(&c).into_iter().collect(), + Err(_) => Vec::new(), + }; + super::ci_repro::from_ci(state, github, ticket_msg, &msg.run_id, &head, &failing).await; + records = super::ci_repro::load(state, &msg.team_id, &msg.run_id).await; + } + let shown = match common::ci_repro::may_revert(&records, &head) { + common::ci_repro::RevertGate::Allowed(why) => why, + common::ci_repro::RevertGate::Refused(why) => { + super::add_progress_note( + state, + &msg.team_id, + &msg.run_id, + &format!( + "Not reverted: {why}. CoderHelm takes its own work out for a red check only \ + after the failing test is shown to pass on the base branch and fail with \ + this change." + ), + ) + .await; + return None; + } + }; let reverts = run_number(state, &msg.team_id, &msg.run_id, "sup_reverts").await; // Earlier heads of the pull request, newest first, and whether their // checks passed (at most ten are read). @@ -7267,9 +7429,11 @@ async fn revert_to_green( common::truncate_str(excerpt.trim(), 200) ) }; + let mut reverted_to: Option = None; let (files, deferred, note): Reverted = match sup::revert_for(&heads, &done, reverts) { Revert::Nothing => return None, Revert::ToHead(sha) => { + reverted_to = Some(sha.clone()); let changed = github .compare_changed_files(pr.owner, pr.repo, &sha, pr.branch) .await @@ -7319,9 +7483,10 @@ async fn revert_to_green( files, deferred, format!( - "CI stayed red after the fix attempts: reverted {} file(s) to {short}, the \ - last head of this pull request whose checks passed, and deferred what \ - came after it. CI decides again.", + "CI stayed red after the fix attempts and the comparison shows this change \ + caused it ({shown}): reverted {} file(s) to {short}, the last head of \ + this pull request whose checks passed, and deferred what came after it. \ + CI decides again.", changed.len() ), ) @@ -7341,14 +7506,29 @@ async fn revert_to_green( vec![(path.clone(), was)], deferred, format!( - "CI stayed red after the fix attempts: took out the last planned task \ - (`{path}`: {}) and deferred it. CI decides again.", + "CI stayed red after the fix attempts and the comparison shows this change \ + caused it ({shown}): took out the last planned task (`{path}`: {}) and \ + deferred it. CI decides again.", common::truncate_str(&task, 160) ), ) } }; - apply_revert(state, msg, github, pr, files, ¬e).await?; + let back_to = match &reverted_to { + Some(sha) => sha.clone(), + None => ticket_msg.base_branch.clone(), + }; + let paths: Vec = files.iter().map(|(p, _)| p.clone()).collect(); + apply_revert( + state, + msg, + github, + pr, + files, + ¬e, + Some((&back_to, &paths)), + ) + .await?; if let Some(mut p) = plan { if !deferred.is_empty() { p.tasks = super::plan_coverage::with_deferred(&p.tasks, &deferred); @@ -7420,7 +7600,7 @@ async fn revert_dep_commit( files.push((path.clone(), was)); } let note = dep_revert_note(&out.lines, run.commits.len()); - apply_revert(state, msg, github, pr, files, ¬e).await?; + apply_revert(state, msg, github, pr, files, ¬e, None).await?; super::dep_fix::save(state, ticket_msg, &msg.run_id, &run).await; super::dep_fix::settle(state, ticket_msg, &run).await; // The head lost a set of bumps: the table and the headline say what it @@ -7484,7 +7664,7 @@ pub(crate) async fn take_out_dep_set( number: pr_number, url: "", }; - apply_revert(state, &msg, github, &pr, files, ¬e).await?; + apply_revert(state, &msg, github, &pr, files, ¬e, None).await?; super::dep_fix::save(state, ticket_msg, run_id, &run).await; super::dep_fix::settle(state, ticket_msg, &run).await; Some(note) @@ -7520,6 +7700,9 @@ pub(crate) fn dep_revert_note(lines: &[String], commits_left: usize) -> String { /// Writes a revert as one commit and names it under "Deferred" on the pull /// request. `None` when there is nothing to write or GitHub refused it. +/// `mark`: the ref the files went back to and the files, kept on the line +/// so the description drops it once that work is back +/// (`common::ci_lines::reconcile`). async fn apply_revert( state: &WorkerState, msg: &ResumeMessage, @@ -7527,6 +7710,7 @@ async fn apply_revert( pr: &PrRef<'_>, files: Vec<(String, Option)>, note: &str, + mark: Option<(&str, &[String])>, ) -> Option<()> { use crate::clients::github::FileOp; if files.is_empty() { @@ -7555,7 +7739,10 @@ async fn apply_revert( add_run_number(state, &msg.team_id, &msg.run_id, "sup_reverts").await; if let Ok(p) = github.get_pull_request(pr.owner, pr.repo, pr.number).await { let body = p["body"].as_str().unwrap_or(""); - let line = format!("- {note}"); + let line = match mark { + Some((to, paths)) => common::ci_lines::revert_line(note, to, paths), + None => format!("- {note}"), + }; let now = if body.contains("## Deferred") { format!("{}\n{line}", body.trim_end()) } else { From 9486424ca6eade0fa1bf08e43904866346c7b1db Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 17 Nov 2026 11:33:58 -0500 Subject: [PATCH 2/7] Format the incident files --- .../incidents/cr_red_on_every_branch.rs | 76 +++++++++++++++---- 1 file changed, 61 insertions(+), 15 deletions(-) diff --git a/services/worker/src/passes/incidents/cr_red_on_every_branch.rs b/services/worker/src/passes/incidents/cr_red_on_every_branch.rs index 5d309563c..6bf18866e 100644 --- a/services/worker/src/passes/incidents/cr_red_on_every_branch.rs +++ b/services/worker/src/passes/incidents/cr_red_on_every_branch.rs @@ -81,16 +81,27 @@ fn compared() -> Record { fn the_failure_is_read_from_its_report_and_compared_with_the_base() { let ev = ci_repro::evidence_of("Deploy Preview", &failure_comment(), "").expect("read"); assert_eq!(ev.tests, vec![TEST.to_string()]); - assert!(ev.error.contains("did not add it to the portal's Order Summary"), "{ev:?}"); + assert!( + ev.error + .contains("did not add it to the portal's Order Summary"), + "{ev:?}" + ); assert_eq!( ev.shots, vec!["https://github.com/user-attachments/assets/0b7a-camp-drawer.png".to_string()] ); - assert!(ci_repro::image_host_allowed("github.com", "/user-attachments/assets/0b7a-camp-drawer.png", &[])); + assert!(ci_repro::image_host_allowed( + "github.com", + "/user-attachments/assets/0b7a-camp-drawer.png", + &[] + )); // The test runs against both addresses with the head's test code. let (spec, title) = repro::spec_and_title(TEST); let cmd = repro::leg_cmd("e2e", &spec, &title, "https://staging-shop.example.com").unwrap(); - assert!(cmd.contains("--grep 'selecting a camp adds it to the cart while registration is open'"), "{cmd}"); + assert!( + cmd.contains("--grep 'selecting a camp adds it to the cart while registration is open'"), + "{cmd}" + ); assert!(cmd.contains("--retries=0")); let r = compared(); @@ -100,10 +111,16 @@ fn the_failure_is_read_from_its_report_and_compared_with_the_base() { // The fixer reads the error, sees the screenshot and is told what a // failure red on the base means for the fix. let brief = repro::brief(Some(&ev), std::slice::from_ref(&r), HEAD); - assert!(brief.contains("Subtotal$0") || brief.contains("Order Summary"), "{brief}"); + assert!( + brief.contains("Subtotal$0") || brief.contains("Order Summary"), + "{brief}" + ); assert!(brief.contains("0b7a-camp-drawer.png"), "{brief}"); assert!(brief.contains("attached to this message as an image")); - assert!(brief.contains("Fix the test, or the code it checks, on this branch"), "{brief}"); + assert!( + brief.contains("Fix the test, or the code it checks, on this branch"), + "{brief}" + ); assert!(brief.contains("Never revert this pull request's work for it")); } @@ -118,23 +135,43 @@ fn nothing_is_reverted_without_a_comparison_that_shows_the_change_caused_it() { // as a preview deploy that hit the cloud account's limit): nothing comes // out either. let infra = repro::from_checks(HEAD, "121ea38c", "Deploy Preview", None); - assert!(matches!(repro::may_revert(&[infra], HEAD), RevertGate::Refused(_))); + assert!(matches!( + repro::may_revert(&[infra], HEAD), + RevertGate::Refused(_) + )); // A comparison on an older head proves nothing about this one. let ours = Record { - base: Leg { target: "s".into(), ran: true, passed: 1, failed: 0, note: String::new() }, + base: Leg { + target: "s".into(), + ran: true, + passed: 1, + failed: 0, + note: String::new(), + }, ..compared() }; - assert!(matches!(repro::may_revert(std::slice::from_ref(&ours), HEAD), RevertGate::Allowed(_))); - assert!(matches!(repro::may_revert(&[ours], "b66dfd3d06d9"), RevertGate::Refused(_))); + assert!(matches!( + repro::may_revert(std::slice::from_ref(&ours), HEAD), + RevertGate::Allowed(_) + )); + assert!(matches!( + repro::may_revert(&[ours], "b66dfd3d06d9"), + RevertGate::Refused(_) + )); // The pipeline: the gate comes before anything is chosen to come out, // and a refusal returns before a write. let src = include_str!("../resume.rs"); let revert = fn_src(src, "async fn revert_to_green("); - let gate = revert.find("ci_repro::may_revert(").expect("the revert asks the gate"); + let gate = revert + .find("ci_repro::may_revert(") + .expect("the revert asks the gate"); assert!(gate < revert.find("sup::revert_for(").unwrap()); assert!(gate < revert.find("apply_revert(").unwrap()); - assert!(revert.find("revert_dep_commit(").unwrap() < gate, "a dependency run keeps its own revert"); + assert!( + revert.find("revert_dep_commit(").unwrap() < gate, + "a dependency run keeps its own revert" + ); } #[test] @@ -146,14 +183,18 @@ fn blame_and_unconfirmed_need_the_record_and_the_report() { assert!(held[0].contains(repro::BLAME_HELD)); // With the comparison on record, the line that says so stays. let shown = "Fails on the base branch too: the test fails on staging as well."; - assert_eq!(resume::held_tried(&[shown.to_string()], &[compared()], HEAD, ""), vec![shown.to_string()]); + assert_eq!( + resume::held_tried(&[shown.to_string()], &[compared()], HEAD, ""), + vec![shown.to_string()] + ); // "Couldn't confirm" while the report was read is replaced by it. let ev = ci_repro::evidence_of("Deploy Preview", &failure_comment(), "").unwrap(); let unsure = "I couldn't confirm what the e2e test saw on the portal."; let held = resume::held_tried(&[unsure.to_string()], &[compared()], HEAD, &ev.line()); assert!(held[0].starts_with("The failure's report says: `Deploy Preview` failed in `tests/browse/camp-registration.spec.ts"), "{held:?}"); - assert!(held[0].contains("screenshot: https://github.com/user-attachments/assets/0b7a-camp-drawer.png")); + assert!(held[0] + .contains("screenshot: https://github.com/user-attachments/assets/0b7a-camp-drawer.png")); // The pipeline: every account goes through the hold before the pull // request, and the fixer's message carries the brief and the shot. @@ -163,7 +204,9 @@ fn blame_and_unconfirmed_need_the_record_and_the_report() { assert!(src.contains("Failure summary:\\n{failure_logs}{repro_brief}")); assert!(src.contains("super::ci_repro::compare(")); assert!(src.contains("super::ci_repro::screenshot(")); - assert!(src.contains("let e2e_on_base = on_base.iter().any(|c| super::e2e_reads::is_e2e_name(c));")); + assert!( + src.contains("let e2e_on_base = on_base.iter().any(|c| super::e2e_reads::is_e2e_name(c));") + ); } #[test] @@ -215,5 +258,8 @@ fn the_ci_lines_are_true_for_the_head() { let src = include_str!("../description.rs"); let build = fn_src(src, "async fn build("); assert!(build.find("ci_lines_for_head(").unwrap() < build.find("gather(").unwrap()); - assert!(!crate::passes::description::is_current(&body, "43f1bdd46cc6")); + assert!(!crate::passes::description::is_current( + &body, + "43f1bdd46cc6" + )); } From 87a27662c2e90bc5a90472105b63f02c89b0621e Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 17 Nov 2026 13:13:29 -0500 Subject: [PATCH 3/7] A CI fix is pushed only after its own checks pass, and red CI stops named instead of rolling back - run_checks runs the owning package's own scripts: its whole unit suite when a non-test file changed, only the touched test files otherwise, and its type check and lint. The test line taken from the first workflow (another package's suite with --passWithNoTests) no longer stands in. - A CI fix round's commit is held when its checks are red or never ran on its last edit, and when it removes a definition a test still names; one the sandbox couldn't check is pushed with an Unverified: line and what ran. - Every round's commit message is checked against its diff and rewritten from it when they disagree. - Two pushed fixes per failing test, kept on the run; then the rounds stop with the test and its error named. Red checks never roll a ticket run's branch back to an older green head or take a planned task out; only a dependency run's newest set of bumps comes out. - An unreadable CI log gets the package's commands to reproduce it locally. - The habits check sends back fixture ids invented while the run looked up real ones, and test cases that differ only in their values. - Incidents ga and gb replay both pull requests; docs/coder-loop.md step 7. --- docs/coder-loop.md | 51 + docs/incidents/ga_fix_pushed_unchecked.md | 5 + docs/incidents/gb_red_ci_stops_named.md | 5 + services/common/src/fixture_ids.rs | 126 +++ services/common/src/lib.rs | 4 + services/common/src/push_gate.rs | 999 ++++++++++++++++++ services/worker/src/passes/habits_check.rs | 5 + services/worker/src/passes/implement.rs | 14 +- .../src/passes/incidents/ae_budget_rounds.rs | 20 +- .../incidents/af_lockfiles_out_of_sync.rs | 7 +- .../incidents/ag_red_ci_ships_what_passes.rs | 56 +- .../bv_no_limit_hands_to_a_person.rs | 2 +- .../passes/incidents/bx_person_lines_kept.rs | 37 +- .../passes/incidents/by_scope_churn_folded.rs | 31 +- .../incidents/cr_red_on_every_branch.rs | 18 +- .../incidents/ga_fix_pushed_unchecked.rs | 273 +++++ .../passes/incidents/gb_red_ci_stops_named.rs | 95 ++ services/worker/src/passes/minimal_change.rs | 82 +- services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/push_checks.rs | 400 +++++++ services/worker/src/passes/resume.rs | 418 ++++---- services/worker/src/passes/review_rules.rs | 2 +- services/worker/src/passes/round.rs | 33 +- services/worker/src/passes/supervisor.rs | 178 +--- 24 files changed, 2377 insertions(+), 485 deletions(-) create mode 100644 docs/incidents/ga_fix_pushed_unchecked.md create mode 100644 docs/incidents/gb_red_ci_stops_named.md create mode 100644 services/common/src/fixture_ids.rs create mode 100644 services/common/src/push_gate.rs create mode 100644 services/worker/src/passes/incidents/ga_fix_pushed_unchecked.rs create mode 100644 services/worker/src/passes/incidents/gb_red_ci_stops_named.rs create mode 100644 services/worker/src/passes/push_checks.rs diff --git a/docs/coder-loop.md b/docs/coder-loop.md index dbc1a5a98..0e8cbcce6 100644 --- a/docs/coder-loop.md +++ b/docs/coder-loop.md @@ -111,6 +111,57 @@ The causes were in the loop, not only in prompt wording: coder, and the coder quotes the run's output in its Evidence. End-to-end code against another company's page uses only what a probe observed (#734). +7. **Commit and push.** + Each gate runs where the commit is made, not as a line in the prompt + (`common::push_gate`, `passes/push_checks.rs`). + + - **The checks come from the repository.** `run_checks` adds the scripts + of each package that owns a touched file: its test script, its type + check (`check-types`, `typecheck`) and its lint. When a non-test file + changed, the package's whole unit suite runs, because a shared helper + breaks callers outside the diff. Only a change to nothing but test + files runs just those files. This step replaces the test line taken + from the first workflow that had one. On one pull request that line was + another package's `npm test --passWithNoTests`: it reported "2 of 2 + checks passed" while `vitest` on the touched files exited 1. + - **Checks before every push** (`push_checks::before_push`, in the CI fix + round before `round::land`). If the checks ran on the fix's last edit + and passed, the fix is pushed and the commit records what ran. If they + failed, or never ran on the last edit, the fix is not pushed: the next + attempt continues on the same edits with the failing output. If the + sandbox couldn't run them (the install failed, or there is no sandbox), + the fix is pushed with an `Unverified:` line saying why and what ran. + - **The message matches the diff** (`round::land`, + `push_gate::true_message`). A message is rewritten from the diff when + it says revert, remove or drop while the diff adds test lines or more + than it removes, when it says add while the diff only removes, or when + it names a file the commit doesn't touch. + - **A revert takes its tests with it** (`push_gate::removed_symbols`, + `still_expected`). A commit that removes a definition a test still + names is held until that test is reverted or updated in the same + commit. + - **Two fixes per failing test** (`push_gate::FixLedger`, kept on the run + as `ci_test_fixes`). The failing tests are read from the failure report + or the log (vitest, jest, Playwright, pytest, cargo, go), or, when they + can't be, the failing checks are used. After two pushed fixes a test that + is still red stops the rounds: the pull request and the run name the + test and its error, and nothing more is pushed. The branch is never + rolled back to an older green head, and a planned task is never taken + out to turn CI green. Only a dependency run's newest set of bumps comes + out (`resume::take_out_failing_bumps`). Five of 53 runs had rolled back, + two of them with tests left behind that expected the reverted code. + - **No log is no reason to stop** (`push_gate::logs_unread_brief`, + `hold_no_logs`). When CI's job log can't be read, the fix brief gives + the owning package's commands so the fixer reproduces the failure in the + sandbox. Any sentence that blames the missing log is replaced. + - **Fixtures use looked-up ids, and tests are sized to the behaviour** + (`minimal_change::made_up_ids`, `repeated_cases`, in the habits check). + Ids like `sport-a` or `id-1` are sent back when the run's lookups + returned real ids. Three or more added cases that differ only in their + values are sent back as one case per behaviour. The size check (test + lines against code lines) runs too; it fires on the roughly 415 test + lines one run added for 50 lines of code. + ## What is deterministic Everything above except the model's own writing: the searches, section checks, diff --git a/docs/incidents/ga_fix_pushed_unchecked.md b/docs/incidents/ga_fix_pushed_unchecked.md new file mode 100644 index 000000000..1cccb0381 --- /dev/null +++ b/docs/incidents/ga_fix_pushed_unchecked.md @@ -0,0 +1,5 @@ +# ga. `ga_fix_pushed_unchecked` + +**What happened:** A pull request that removed a duplicated filter chip changed a shared slug helper and added about 415 lines of unit tests for about 50 lines of code, with fixture ids `sport-a` and `sport-b` although the run had looked up the two real records. CI went red on a test outside the diff. Every CI fix round's sandbox said "2 of 2 checks passed": its test step was another package's `npm test` with `--passWithNoTests`, so no touched test ran, while the coder's own `vitest run` of the touched files exited 1 four times. The fixes were pushed anyway. After four attempts the supervisor put a source file back to an older green head in a commit titled "Revert the change that broke CI" and left the tests that expected the reverted helper in place. + +**The guarantee:** The sandbox runs the owning package's own scripts: its whole unit suite when a non-test file changed, only the touched test files when nothing but tests changed, and its type check and lint (`common::push_gate::package_steps`). A CI fix is pushed only when those ran on its last edit and passed; one the sandbox couldn't check is pushed with `Unverified:` and what ran (`push_checks::before_push`). A commit message that disagrees with its diff is rewritten from it (`round::land`). A commit that removes a definition a test still names is held until the test goes with it. A failing test gets two pushed fixes; then the rounds stop with the test and its error named, and nothing is rolled back. Invented fixture ids and three or more test cases that differ only in their values go back to the coder (`minimal_change`). diff --git a/docs/incidents/gb_red_ci_stops_named.md b/docs/incidents/gb_red_ci_stops_named.md new file mode 100644 index 000000000..fadd8219e --- /dev/null +++ b/docs/incidents/gb_red_ci_stops_named.md @@ -0,0 +1,5 @@ +# gb. `gb_red_ci_stops_named` + +**What happened:** A pull request's end-to-end check failed on "selecting a camp adds it to the cart while registration is open" with `Subtotal$0`. After three fix attempts the supervisor rolled seven of the pull request's files back to an older green head. The test failed the same way on the result: the vendor portal had opened registration, so it was red on every branch. Five of the last 53 runs rolled their branch back the same way. + +**The guarantee:** Red checks never roll a ticket run's branch back to an older head or take a planned task out; only a dependency run's newest set of bumps comes out (`resume::take_out_failing_bumps`). A failing test gets at most two pushed fixes (`common::push_gate::FixLedger`, kept on the run as `ci_test_fixes`). Then the rounds stop, nothing more is pushed, and the pull request and the run name the test and its error. When CI's job log can't be read, the fixer reproduces the failure with the owning package's own commands in the sandbox, and a sentence that blames the unreadable log is replaced. diff --git a/services/common/src/fixture_ids.rs b/services/common/src/fixture_ids.rs new file mode 100644 index 000000000..63b806ebf --- /dev/null +++ b/services/common/src/fixture_ids.rs @@ -0,0 +1,126 @@ +//! A test fixture uses the ids the run looked up, not made-up ones. +//! +//! A run queried the production database, found the two records behind a +//! duplicated filter and quoted their ids in its evidence, then wrote test +//! fixtures with `sport-a` and `sport-b`. The test passed on data that +//! doesn't exist, and nobody could tell from it which records the bug was +//! about. +//! +//! [`looked_up_ids`] reads the ids out of the run's lookups (UUIDs, their +//! eight-character prefixes, long hex and numeric ids); [`made_up`] finds an +//! id-like value in a test's added lines that looks invented (`sport-a`, +//! `id-1`, `test-id`, `fake_user`) while real ids are on record. The check +//! of the change against the plan (`habits_check`) sends each one back. + +/// Ids a run's lookups returned, in order, each once. +pub fn looked_up_ids(lines: &[String]) -> Vec { + let re = regex::Regex::new( + r"\b(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8}(?:…|\.\.\.)|[0-9a-f]{24,40})", + ) + .expect("valid regex"); + let mut out: Vec = Vec::new(); + for l in lines { + // Only what came back: the question may hold ids typed by hand. + let got = l.split("Came back:").nth(1).unwrap_or(""); + for m in re.find_iter(got) { + let id = m.as_str().trim_end_matches('…').trim_end_matches("..."); + if id.chars().any(|c| c.is_ascii_digit()) && !out.iter().any(|o| o == id) { + out.push(id.to_string()); + } + } + } + out +} + +/// Whether a fixture value looks invented rather than read. +pub fn looks_made_up(value: &str) -> bool { + let v = value.to_lowercase(); + let letter_or_digit = regex::Regex::new(r"^[a-z]+[-_][a-z0-9]$").expect("valid regex"); + let numbered = regex::Regex::new(r"^(?:id|item|row|rec)[-_]?\d{1,3}$").expect("valid regex"); + let filler = regex::Regex::new( + r"^(?:test|fake|mock|dummy|placeholder|sample|some|foo|bar)(?:[-_][a-z0-9-_]*)?$", + ) + .expect("valid regex"); + letter_or_digit.is_match(&v) || numbered.is_match(&v) || filler.is_match(&v) +} + +/// One invented fixture id. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MadeUp { + pub path: String, + pub value: String, +} + +/// Invented id values on the added lines of test files (`diff`: path, +/// status, patch), when the run looked up real ids (`looked`). An id-like +/// key: `id`, `…Id`, `…_id`, `ids`. +pub fn made_up(diff: &[(String, String, String)], looked: &[String]) -> Vec { + if looked.is_empty() { + return Vec::new(); + } + let key = + regex::Regex::new(r#"(?i)\b[a-z_]*(?:id|ids)\s*[:=]\s*\[?\s*["'`]([^"'`]{1,40})["'`]"#) + .expect("valid regex"); + let mut out: Vec = Vec::new(); + for (path, _, patch) in diff + .iter() + .filter(|(p, _, _)| crate::push_gate::is_test_file(p)) + { + for line in patch + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + { + for c in key.captures_iter(line) { + let value = c[1].to_string(); + if looks_made_up(&value) + && !looked.iter().any(|l| l == &value) + && !out.iter().any(|m| m.path == *path && m.value == value) + { + out.push(MadeUp { + path: path.clone(), + value, + }); + } + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn made_up_ids_are_found_only_when_real_ones_were_looked_up() { + let lines = vec![ + "- [L1] Asked Production database: SELECT id FROM sport WHERE ... Came back: 4c2d9e10-1111-4a2b-8c3d-0a2b3c4d5e6f 'Multi-sport'; b7f3a2c8… 'Multi-Sport'".to_string(), + "- [L2] Asked it: SELECT 9f8e7d6c-0000-0000-0000-000000000000 Came back EMPTY".to_string(), + ]; + let ids = looked_up_ids(&lines); + assert_eq!( + ids, + vec!["4c2d9e10-1111-4a2b-8c3d-0a2b3c4d5e6f", "b7f3a2c8"] + ); + let diff = vec![ + ( + "src/test/filters.test.ts".to_string(), + "modified".to_string(), + "+ { id: 'sport-a', name: 'Multi-sport' },\n+ { id: \"sport-b\", name: 'Multi-Sport' },\n+ { sportId: '4c2d9e10-1111-4a2b-8c3d-0a2b3c4d5e6f' },\n- { id: 'old-1' }".to_string(), + ), + ( + "src/utils/filters.ts".to_string(), + "modified".to_string(), + "+const id = 'sport-a';".to_string(), + ), + ]; + let found = made_up(&diff, &ids); + assert_eq!( + found.iter().map(|m| m.value.as_str()).collect::>(), + vec!["sport-a", "sport-b"] + ); + assert!(made_up(&diff, &[]).is_empty()); + assert!(looks_made_up("id-1") && looks_made_up("test-id") && looks_made_up("fake_user")); + assert!(!looks_made_up("multi-sport") && !looks_made_up("4c2d9e10")); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index e7776bd2b..680c0dbe0 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -166,6 +166,8 @@ pub mod ci_repro; /// The last check on a pull request description: no section twice, no /// deploy maps, no empty "who this affects". pub mod description_lint; +/// A test fixture uses the ids the run looked up, not made-up ones. +pub mod fixture_ids; #[cfg(test)] mod model_call_sites; /// Which pull requests CoderHelm may push to, edit or close: its own. @@ -199,6 +201,8 @@ pub mod pr_steps; /// A repository's pull request template as the description's structure. pub mod pr_template; pub mod preview; +/// What a fix must show before it is committed and pushed. +pub mod push_gate; pub mod run_prs; pub mod waiting_line; // review_stats: time-ordered review records for analytics diff --git a/services/common/src/push_gate.rs b/services/common/src/push_gate.rs new file mode 100644 index 000000000..689dec2ea --- /dev/null +++ b/services/common/src/push_gate.rs @@ -0,0 +1,999 @@ +//! What a fix must show before it is committed and pushed, read from the +//! commit itself, never from what the coder says about it. +//! +//! Three pull requests went wrong the same way. A CI fix round pushed while +//! the coder's own run of the touched tests failed: the sandbox's test step +//! ran another package's suite with `--passWithNoTests`, so "2 of 2 checks +//! passed" while `vitest` on the changed files exited 1, four times. A commit +//! titled "Revert the change that broke CI" put a source file back and left +//! the tests that expected the reverted behaviour in place. Twice the branch +//! was rolled back to an older green head as the "fix". +//! +//! The gates, each a function here and each called where the commit is made: +//! +//! - **Checks before every push** ([`verdict`], [`package_steps`]): the +//! commands come from the repository itself, the scripts of the package +//! that owns each touched test file and the steps its CI runs. A red +//! result holds the push; a fix nothing ran on is not pushed; a sandbox +//! that could not install pushes with an `Unverified:` line in the commit. +//! - **A commit message matches its diff** ([`message_problems`], +//! [`true_message`]): a message that says revert, remove or drop and adds +//! test lines, one that says add and only deletes, or one that names a +//! file the commit doesn't touch, is rewritten from the diff. +//! - **A revert takes its tests with it** ([`removed_symbols`], +//! [`still_expected`]): a definition the commit removes that a test still +//! names holds the push until the test goes in the same commit. +//! - **Two fixes per failing test** ([`FixLedger`]): a test still red after +//! two pushed fixes stops the fix rounds with the test and its error named. +//! Never a rollback to an older head. +//! - **No logs is no reason to stop** ([`logs_unread_brief`], +//! [`hold_no_logs`]): when CI's job log can't be read, the fixer is given +//! the repository's own commands to reproduce the failure locally, and a +//! sentence that blames the missing log is replaced. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +// ── Checks before every push ─────────────────────────────────────────────── + +/// What the sandbox's last check run on the commit's tree came to. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Checked { + /// A sandbox can run the repository's checks for this run. + pub sandbox: bool, + /// The commit touches test files. + pub touched_tests: bool, + pub tests_ran: bool, + pub tests_passed: bool, + pub types_ran: bool, + pub types_passed: bool, + /// Why the last attempt gave no result (the install failed, the build + /// had no result). + pub failure: Option, + /// The tree changed after the last check run, or none ran. + pub owed: bool, +} + +/// Whether a fix may be pushed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + /// The checks ran on this tree and passed. + Verified, + /// The checks ran on this tree and failed: never pushed. + Red(String), + /// The checks could not run (no sandbox, the install failed): pushed + /// with an `Unverified:` line in the commit saying why. + Unverified(String), + /// The tree changed after the last check run: the checks run first. + Owed, +} + +/// The push verdict for a fix, from its last check run. +pub fn verdict(c: &Checked) -> Verdict { + if !c.sandbox { + return Verdict::Unverified("no sandbox could run the repository's checks".into()); + } + if let Some(why) = c.failure.as_deref().filter(|w| !w.trim().is_empty()) { + return Verdict::Unverified(format!("the sandbox gave no result ({})", why.trim())); + } + if c.owed { + return Verdict::Owed; + } + let mut red = Vec::new(); + if c.types_ran && !c.types_passed { + red.push("the type check"); + } + if c.tests_ran && !c.tests_passed { + red.push("the touched tests"); + } + if !red.is_empty() { + return Verdict::Red(format!("{} failed in the sandbox", red.join(" and "))); + } + if c.touched_tests && !c.tests_ran { + return Verdict::Unverified( + "no unit suite of the repository ran for this change (no test script covers the \ + changed package)" + .into(), + ); + } + Verdict::Verified +} + +/// The line an unverified commit carries. +pub fn unverified_line(why: &str) -> String { + format!( + "Unverified: {}. CI is the first run of this change.", + why.trim() + ) +} + +/// A check the sandbox runs before a push, from the repository's own files. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PkgStep { + /// `tests`, `types` or `lint`. + pub kind: &'static str, + /// The package folder ("" for the root). + pub dir: String, + pub cmd: String, +} + +/// A unit or component test file, by its name. +pub fn is_test_file(path: &str) -> bool { + let p = path.to_lowercase(); + let base = p.rsplit('/').next().unwrap_or(&p); + base.contains(".test.") || base.contains(".spec.") || p.contains("__tests__/") +} + +/// A test that needs a browser or deployed services: never a sandbox step. +fn is_browser_test(path: &str, script: &str) -> bool { + let p = path.to_lowercase(); + let s = script.to_lowercase(); + p.starts_with("e2e/") + || p.contains("/e2e/") + || ["playwright", "cypress", "e2e"] + .iter() + .any(|w| s.contains(w)) +} + +/// A source file a unit suite can cover (not a doc, an asset or a config). +pub fn is_code_file(path: &str) -> bool { + let p = path.to_lowercase(); + [ + ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".vue", ".svelte", + ] + .iter() + .any(|e| p.ends_with(e)) +} + +/// The package manager the repository's lockfiles name. +pub fn package_manager(root_files: &[String]) -> &'static str { + let has = |f: &str| root_files.iter().any(|p| p == f); + if has("pnpm-lock.yaml") { + "pnpm" + } else if has("yarn.lock") { + "yarn" + } else if has("bun.lockb") || has("bun.lock") { + "bun" + } else { + "npm" + } +} + +/// `run