diff --git a/docs/incidents/xe_test_fix_from_evidence.md b/docs/incidents/xe_test_fix_from_evidence.md new file mode 100644 index 00000000..a8cae106 --- /dev/null +++ b/docs/incidents/xe_test_fix_from_evidence.md @@ -0,0 +1,5 @@ +# xe. `xe_test_fix_from_evidence` + +**What happened:** Runs that fixed a team's failing end-to-end tests guessed. Most fix pull requests were opened on a cause the run itself called inferred and not reproduced, and several only added messages for the next failure. Waits went into page objects for causes outside the test. A test failing every run was filed as flaky, and runs the sandbox's network refused were counted as the test failing. One failure got a run per test and another weeks later, a merged fix whose test failed again was never looked at, and every proof was twenty runs whatever the test's failure rate. + +**The guarantee:** A fix follows the evidence (`common::e2e::fix_evidence`). No code change without a reproduction: a repeat run failing, or a kept report with the exact error and its trace, screenshot or page; runs that never reached the page don't count. One class from a closed set (app bug, test bug, test data or environment, timing race, CI infrastructure, third party), which must fit the evidence, decides where the fix goes: an app bug in the app and never in the test, infrastructure and third parties to quarantine with an owner, reason, ticket and expiry. A sleep, a raised timeout, retries, a loosened assertion, a skip or a broadened selector is refused unless a quoted trace line justifies it, and a sleep never is. The description names the cause, the class, the trace lines, why the change fixes it and the pass rates. The repeat count follows the measured failure rate, on the head and the target that failed. A sibling failure joins the open run, and a failure after the merge reopens the same run. diff --git a/services/common/src/e2e/fix_evidence.rs b/services/common/src/e2e/fix_evidence.rs new file mode 100644 index 00000000..eb5f055b --- /dev/null +++ b/services/common/src/e2e/fix_evidence.rs @@ -0,0 +1,2305 @@ +//! A failing or flaky test is fixed from evidence, in this order, or not +//! changed at all. +//! +//! 1. **Reproduced first** ([`reproduction`]). A code change needs the +//! failure seen with its artifacts: CoderHelm's own repeat run failing on +//! the same target, or a kept report of a failing run with the exact error +//! and a trace, screenshot or page snapshot. A run that never reached the +//! page (the sandbox's network refused the site, no browser, no address) +//! is not a failure of the test and is never counted as one +//! ([`not_reached`]). With no reproduction there is no code change: the +//! run gathers more evidence, or the test is quarantined with a reason +//! ([`next_step`]). +//! 2. **Classified from the evidence** ([`FailureClass`], a closed set): +//! app bug, test bug, test data or environment, timing or race, CI +//! infrastructure, third party. The class decides where the fix may go +//! ([`FailureClass::locations`]): an app bug in the app, never by asking +//! less of the test; a test bug in the test with its root cause; CI +//! infrastructure and a third party to quarantine with a ticket, never a +//! code change. A class is accepted only when the evidence fits it +//! ([`class_problems`]): a race passes some runs, an app bug fails on the +//! base branch and names the app code, a third party names a host that +//! isn't the team's. Pass rates on the base and the head, and the last +//! commit the test passed on ([`first_bad`]), go with it. +//! 3. **Banned fixes, read from the diff** ([`judge_diff`]): a fixed sleep, +//! a raised timeout, added retries, a poll, a removed or loosened +//! assertion, a skip, a selector that matches more than before, test-only +//! changes for an app bug, and any change for a cause outside the code. +//! Each is refused unless the diagnosis justifies it with a line from the +//! failing run's trace that a reviewer can find there (a fixed sleep and +//! added retries never are). +//! 4. **The cause is named** ([`Diagnosis::from_notes`], [`cause_section`], +//! [`body_problems`]): root cause, class, the trace lines that show it, +//! why the change addresses it, and the pass rate before and after. +//! 5. **Proven with enough runs** ([`repeats_for`], [`proof`]): the number +//! of clean repeat runs a fix needs follows the measured failure rate +//! (n = ln(1 - confidence) / ln(1 - rate)), on the pull request's head, +//! against the target that failed. The runs themselves go through the +//! repeat-proof routes (preview, staging, the app started in the +//! sandbox, CI); this module only says how many and judges the result. +//! 6. **One run per failure** ([`attach`]): a new occurrence of a test with +//! an open run, or of a sibling test in the same spec with the same +//! failure signature, joins that run as evidence. +//! 7. **Watched after merge** ([`Watch`]): the next CI runs of the test on +//! the default branch are read; a failure reopens the same run with the +//! new evidence instead of starting a fresh attempt. +//! 8. **Quarantine has terms** ([`QuarantineTerms`]): an owner, a reason, a +//! ticket and an expiry, shown on the Tests page. +//! +//! Everything here is pure, so the worker, the gateway and the tests agree. + +use chrono::{DateTime, Duration, Utc}; +use serde::{Deserialize, Serialize}; + +use super::failure::FailureExtract; +use super::fix_guard::{self, code_of, is_test_code, Kind}; +use super::integrity::{self, Loosening}; +use super::signature; + +// ── the class ───────────────────────────────────────────────────────────── + +/// Why a test failed: a closed set, chosen from the evidence. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FailureClass { + /// The app does the wrong thing; the test is right. + AppBug, + /// The test's own code is wrong (a stale expectation, a wrong locator, + /// a helper that reads the page wrongly). + TestBug, + /// The data or environment the test depends on changed or is shared. + TestDataEnv, + /// A race between the test and the page, or inside the app. + TimingRace, + /// The CI machine, the runner, the network or a deploy in progress. + CiInfra, + /// A service another company runs. + ThirdParty, +} + +/// Where a fix for a class may go. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FixLocation { + /// Application code. + App, + /// Test code, test data and fixtures. + Test, + /// No code change: quarantine with a ticket. + Quarantine, +} + +impl FailureClass { + pub const ALL: [FailureClass; 6] = [ + FailureClass::AppBug, + FailureClass::TestBug, + FailureClass::TestDataEnv, + FailureClass::TimingRace, + FailureClass::CiInfra, + FailureClass::ThirdParty, + ]; + + pub fn as_str(self) -> &'static str { + match self { + FailureClass::AppBug => "app_bug", + FailureClass::TestBug => "test_bug", + FailureClass::TestDataEnv => "test_data_env", + FailureClass::TimingRace => "timing_race", + FailureClass::CiInfra => "ci_infra", + FailureClass::ThirdParty => "third_party", + } + } + + pub fn words(self) -> &'static str { + match self { + FailureClass::AppBug => "a bug in the app", + FailureClass::TestBug => "a bug in the test", + FailureClass::TestDataEnv => "test data or environment", + FailureClass::TimingRace => "a timing race", + FailureClass::CiInfra => "CI infrastructure", + FailureClass::ThirdParty => "a third-party service", + } + } + + /// The class named in a note (`app bug`, `app_bug`, `App bug`). + pub fn parse(s: &str) -> Option { + let k: String = s + .trim() + .trim_matches(|c: char| c == '`' || c == '.' || c == '*') + .to_lowercase() + .replace(['-', ' ', '/'], "_"); + let k = k.replace("__", "_"); + Some(match k.as_str() { + "app_bug" | "app" | "product_bug" => FailureClass::AppBug, + "test_bug" | "test" => FailureClass::TestBug, + "test_data_env" + | "test_data_or_env" + | "test_data_environment" + | "test_data" + | "data_env" + | "environment" => FailureClass::TestDataEnv, + "timing_race" | "timing" | "race" => FailureClass::TimingRace, + "ci_infra" | "ci_infrastructure" | "infra" => FailureClass::CiInfra, + "third_party" | "thirdparty" | "vendor" => FailureClass::ThirdParty, + _ => return None, + }) + } + + /// Where a fix for this class may go. + pub fn locations(self) -> &'static [FixLocation] { + match self { + FailureClass::AppBug => &[FixLocation::App], + FailureClass::TestBug => &[FixLocation::Test], + FailureClass::TestDataEnv => &[FixLocation::Test, FixLocation::Quarantine], + FailureClass::TimingRace => &[FixLocation::Test, FixLocation::App], + FailureClass::CiInfra | FailureClass::ThirdParty => &[FixLocation::Quarantine], + } + } + + /// A cause outside the code: never fixed with a code change. + pub fn outside_code(self) -> bool { + self.locations() == [FixLocation::Quarantine] + } +} + +// ── runs and their results ──────────────────────────────────────────────── + +/// Why a run never reached the test's page, read from its output: the +/// sandbox or CI refused the site, the browser was missing, the address +/// didn't resolve. `None` when the run reached the test. +pub fn not_reached(output: &str) -> Option<&'static str> { + let l = output.to_lowercase(); + const SIGNS: [(&str, &str); 10] = [ + ( + "coderhelm_egress_blocked", + "the sandbox's network refused the site", + ), + ( + "err_tunnel_connection_failed", + "the sandbox's network refused the site", + ), + ("err_name_not_resolved", "the site's address didn't resolve"), + ("getaddrinfo enotfound", "the site's address didn't resolve"), + ("executable doesn't exist", "the browser isn't installed"), + ("browsertype.launch", "the browser couldn't start"), + ( + "failed to download chromium", + "the browser couldn't be downloaded", + ), + ( + "err_connection_refused", + "nothing listens at the test's address", + ), + ("econnrefused", "nothing listens at the test's address"), + ("no tests found", "the runner found no test to run"), + ]; + SIGNS + .iter() + .find(|(sign, _)| l.contains(sign)) + .map(|(_, why)| *why) +} + +/// One repeat or CI run of a test. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum RunResult { + Passed, + Failed { + error: String, + }, + /// The run never reached the test: not a failure of the test. + NotReached { + why: String, + }, +} + +impl RunResult { + /// A failed run, or one that never reached the page when its error + /// says so. + pub fn failed(error: &str) -> RunResult { + match not_reached(error) { + Some(why) => RunResult::NotReached { why: why.into() }, + None => RunResult::Failed { + error: error.to_string(), + }, + } + } +} + +/// One CI run of a test as a watch reads it, the way [`history_measure`] +/// counts the history: a run that failed as a whole (`bad_run`: runner or +/// network trouble) or in which the test never ran (no attempt, or every +/// attempt skipped or interrupted) never reached the page, so it neither +/// reopens a fix nor counts towards holding it. +pub fn watch_result(attempts: &[super::model::Attempt], bad_run: bool) -> RunResult { + use super::model::AttemptStatus; + if bad_run { + return RunResult::NotReached { + why: "the run failed as a whole (runner or network trouble)".into(), + }; + } + let ran: Vec<_> = attempts + .iter() + .filter(|a| { + !matches!( + a.status, + AttemptStatus::Skipped | AttemptStatus::Interrupted + ) + }) + .collect(); + if ran.is_empty() { + return RunResult::NotReached { + why: "the test didn't run (skipped, interrupted or absent)".into(), + }; + } + if !ran.iter().any(|a| a.status.is_failure()) { + return RunResult::Passed; + } + match ran + .iter() + .filter(|a| a.status.is_failure()) + .find_map(|a| a.error.as_ref().map(|e| e.message.as_str())) + { + Some(e) => RunResult::failed(e), + None => RunResult::Failed { + error: "failed with no error text in the report".into(), + }, + } +} + +/// Counted runs. Runs that never reached the page are kept apart. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Measure { + pub passed: u32, + pub failed: u32, + #[serde(default)] + pub not_reached: u32, +} + +impl Measure { + pub fn of(results: &[RunResult]) -> Measure { + let mut m = Measure::default(); + for r in results { + match r { + RunResult::Passed => m.passed += 1, + RunResult::Failed { .. } => m.failed += 1, + RunResult::NotReached { .. } => m.not_reached += 1, + } + } + m + } + + /// Runs that reached the test. + pub fn counted(&self) -> u32 { + self.passed + self.failed + } + + /// The failure rate over counted runs; `None` with none. + pub fn rate(&self) -> Option { + (self.counted() > 0).then(|| f64::from(self.failed) / f64::from(self.counted())) + } + + /// Passes some runs and fails others. + pub fn flaky(&self) -> bool { + self.passed > 0 && self.failed > 0 + } + + /// Fails every counted run (at least `MIN_EVERY` of them). + pub fn every_run_failed(&self) -> bool { + self.counted() >= MIN_EVERY && self.passed == 0 + } + + pub fn line(&self) -> String { + let mut s = format!("{}/{} passed", self.passed, self.counted()); + if self.not_reached > 0 { + s.push_str(&format!( + " ({} more never reached the page and aren't counted)", + self.not_reached + )); + } + s + } +} + +impl From for Measure { + /// A repeat proof's routes as counts: routes that never reached the + /// page are kept apart, never failures. + fn from(t: super::proof_routes::Tally) -> Measure { + Measure { + passed: t.passed, + failed: t.failed, + not_reached: t.not_reached, + } + } +} + +/// The repeat count a proof's routes run (`proof_routes::repeat_count`): +/// the one measured from the failure rate before the fix, when there is one. +pub fn measured_repeats(rate: Option) -> Option { + rate.map(|r| repeats_for(r, CONFIDENCE).runs) +} + +/// Fewest counted runs a "fails every time" verdict needs. +pub const MIN_EVERY: u32 = 5; + +// ── reproduction ────────────────────────────────────────────────────────── + +/// What a failing run left to look at. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Artifacts { + /// The exact error. + pub error: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub trace: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub screenshot: Option, + /// The page as Playwright's snapshot saw it. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub page_state: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub console: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub network: Vec, + /// Where they were read. + #[serde(default)] + pub source: String, +} + +impl Artifacts { + /// The artifacts of a failing run's report. + pub fn from_failure(f: &FailureExtract) -> Artifacts { + let find = |exts: &[&str]| { + f.attachments + .iter() + .find(|a| { + let l = a.to_lowercase(); + exts.iter().any(|e| l.ends_with(e)) + }) + .cloned() + }; + Artifacts { + error: f.error.clone(), + trace: find(&[".zip", "trace"]), + screenshot: find(&[".png", ".jpg", ".jpeg", ".webp"]), + page_state: f.page_state.clone(), + source: f.source.clone(), + ..Default::default() + } + } + + /// The exact error and something that shows the page at the failure. + pub fn shows_failure(&self) -> bool { + !self.error.trim().is_empty() + && (self.trace.is_some() + || self.screenshot.is_some() + || !self.page_state.trim().is_empty()) + } +} + +/// How the failure was seen. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Repro { + /// CoderHelm's own repeat run failed on the target that failed in CI. + Repeat { + measure: Measure, + target: String, + artifacts: Artifacts, + }, + /// A kept report of a failing run shows the exact error and the page. + Report { artifacts: Artifacts }, + /// Runs reached the test and none failed. + NotReproduced { measure: Measure }, + /// Nothing could run the test, and no report shows the failure. + Unrunnable { why: String }, + /// Nothing was tried. + None, +} + +impl Repro { + pub fn reproduced(&self) -> bool { + matches!(self, Repro::Repeat { .. } | Repro::Report { .. }) + } + + pub fn artifacts(&self) -> Option<&Artifacts> { + match self { + Repro::Repeat { artifacts, .. } | Repro::Report { artifacts } => Some(artifacts), + _ => None, + } + } + + pub fn line(&self) -> String { + match self { + Repro::Repeat { + measure, target, .. + } => format!( + "Reproduced by CoderHelm's repeat run against {}: {}.", + if target.is_empty() { + "the test's target" + } else { + target + }, + measure.line() + ), + Repro::Report { artifacts } => format!( + "Reproduced from a kept report of a failing run{}: the exact error and {}.", + if artifacts.source.is_empty() { + String::new() + } else { + format!(" ({})", artifacts.source) + }, + if artifacts.trace.is_some() { + "its trace" + } else if artifacts.screenshot.is_some() { + "its screenshot" + } else { + "the page snapshot" + } + ), + Repro::NotReproduced { measure } => { + format!("Not reproduced: {}.", measure.line()) + } + Repro::Unrunnable { why } => format!("Not reproduced: the test couldn't run ({why})."), + Repro::None => "Not reproduced: nothing ran the test.".into(), + } + } +} + +/// How the failure was seen, from CoderHelm's repeat run on the failing +/// target (`repeat`, with the error of a failing run) and the reports of +/// failing CI runs (`failures`). +pub fn reproduction( + repeat: Option<(&Measure, &str, Option<&str>)>, + failures: &[FailureExtract], + unrunnable: Option<&str>, +) -> Repro { + if let Some((m, target, error)) = repeat { + if m.failed > 0 { + let artifacts = failures + .first() + .map(Artifacts::from_failure) + .unwrap_or_else(|| Artifacts { + error: error.unwrap_or_default().to_string(), + ..Default::default() + }); + return Repro::Repeat { + measure: *m, + target: target.to_string(), + artifacts, + }; + } + } + if let Some(a) = failures + .iter() + .map(Artifacts::from_failure) + .find(Artifacts::shows_failure) + { + return Repro::Report { artifacts: a }; + } + match repeat { + Some((m, _, _)) if m.counted() > 0 => Repro::NotReproduced { measure: *m }, + Some((m, _, _)) if m.not_reached > 0 => Repro::Unrunnable { + why: unrunnable + .unwrap_or("every run stopped before the page loaded") + .to_string(), + }, + _ => match unrunnable { + Some(why) => Repro::Unrunnable { why: why.into() }, + None => Repro::None, + }, + } +} + +/// What a run does next. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Next { + /// Reproduced and classified: the fix goes where the class says. + Fix, + /// No code change yet: get this first. + GatherEvidence { what: String }, + /// No code change: quarantine the test with this reason and a ticket. + Quarantine { reason: String }, +} + +impl Next { + pub fn sentence(&self) -> String { + match self { + Next::Fix => "The failure is reproduced and classified; the fix may be written.".into(), + Next::GatherEvidence { what } => format!("No code change yet: {what}"), + Next::Quarantine { reason } => { + format!( + "No code change: the test is quarantined while this is worked on ({reason})." + ) + } + } + } +} + +/// What the run does next, from how the failure was seen, its class and +/// the test's failure rate in CI (`ci_rate`). +pub fn next_step(repro: &Repro, class: Option, ci_rate: Option) -> Next { + match repro { + Repro::Repeat { .. } | Repro::Report { .. } => match class { + Some(c) if c.outside_code() => Next::Quarantine { + reason: format!("the cause is {}, outside the code", c.words()), + }, + Some(_) => Next::Fix, + None => Next::GatherEvidence { + what: format!( + "the failure is reproduced but not classified; name one class ({}) with the trace line that shows it", + FailureClass::ALL.map(|c| c.as_str()).join(", ") + ), + }, + }, + Repro::NotReproduced { measure } => { + let need = ci_rate.map(|r| repeats_for(r, CONFIDENCE).runs); + match need { + Some(n) if measure.counted() < n => Next::GatherEvidence { + what: format!( + "{} passed, but a test failing {:.0}% of CI runs needs {n} runs to show itself; run {} more with traces kept", + measure.line(), + ci_rate.unwrap_or(0.0) * 100.0, + n - measure.counted() + ), + }, + Some(_) => Next::Quarantine { + reason: format!( + "it fails in CI but passed {} here; the difference is in CI's environment", + measure.line() + ), + }, + None => Next::GatherEvidence { + what: format!( + "{}; keep the trace of the next failing CI run", + measure.line() + ), + }, + } + } + Repro::Unrunnable { why } => Next::Quarantine { + reason: format!("the failure couldn't be reproduced: {why}"), + }, + Repro::None => Next::GatherEvidence { + what: "run the failing test with retries off and traces kept, or read a failing run's report".into(), + }, + } +} + +// ── pass rates and the last good commit ────────────────────────────────── + +/// Pass rates that place the failure in time. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PassRates { + /// On the base branch's head. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base: Option, + /// On the pull request's head. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub head: Option, + /// The last commit every counted run passed on, and the first one + /// after it that failed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bisect: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Bisect { + pub last_good: String, + pub first_bad: String, +} + +/// From commits oldest first, each with its runs (`None` when it wasn't +/// run): the last commit that passed every counted run and the first +/// later one with a failure. Commits not run are skipped, so the result +/// is a range when they lie between. +pub fn first_bad(commits: &[(String, Option)]) -> Option { + let mut good: Option<&str> = None; + for (sha, m) in commits { + let Some(m) = m.filter(|m| m.counted() > 0) else { + continue; + }; + if m.failed == 0 { + good = Some(sha); + } else if let Some(g) = good { + return Some(Bisect { + last_good: g.to_string(), + first_bad: sha.clone(), + }); + } + } + None +} + +/// The next commit to run between the last good and the first bad one +/// (both included in `commits`, oldest first): the middle one not yet run. +pub fn bisect_next(commits: &[(String, Option)]) -> Option { + let b = first_bad(commits)?; + let lo = commits.iter().position(|(s, _)| *s == b.last_good)?; + let hi = commits.iter().position(|(s, _)| *s == b.first_bad)?; + let between: Vec<&(String, Option)> = commits[lo + 1..hi].iter().collect(); + between + .get(between.len() / 2) + .filter(|(_, m)| m.is_none()) + .map(|(s, _)| s.clone()) +} + +// ── the diagnosis ───────────────────────────────────────────────────────── + +/// A banned kind of change and the trace line that justifies it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Justification { + pub kind: Banned, + pub trace_line: String, +} + +/// What the fixing agent concluded, read from its notes. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Diagnosis { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub class: Option, + #[serde(default)] + pub cause: String, + /// Lines quoted from the failing run's trace, report or log. + #[serde(default)] + pub trace_lines: Vec, + /// `file:line` of the code the cause is in. + #[serde(default)] + pub cited: Vec, + #[serde(default)] + pub why_fix: String, + #[serde(default)] + pub justified: Vec, +} + +/// Note prefixes the fixing agent writes, one per line. +pub const NOTE_CLASS: &str = "Class:"; +pub const NOTE_CAUSE: &str = "Root cause:"; +pub const NOTE_TRACE: &str = "Trace:"; +pub const NOTE_CITED: &str = "Cause in:"; +pub const NOTE_WHY: &str = "Why this fixes it:"; +pub const NOTE_JUSTIFY: &str = "Justify "; + +/// The rules the fixing agent is given. +pub const RULES: &str = "## How this test is fixed (checked on the diff)\n\ +- Reproduce first: no code change until the failure is seen (a repeat run failing, or a failing run's report with its trace or screenshot). Without one, say what evidence is missing and change nothing.\n\ +- Write these lines in your notes:\n\ + `Class: `\n\ + `Root cause: `\n\ + `Trace: ` (one or more)\n\ + `Cause in: `\n\ + `Why this fixes it: `\n\ +- The class decides where the fix goes: an app bug in the app (the test keeps every assertion); a test bug in the test; ci_infra and third_party change no code (the test is quarantined with a ticket).\n\ +- Refused unless justified with `Justify : ` that is one of your Trace lines: a raised timeout or a poll (timing_race only). Never accepted: a fixed sleep, added retries, a skip, a removed or loosened assertion, a selector that matches more than before.\n"; + +impl Diagnosis { + /// The diagnosis in the fixing agent's notes. + pub fn from_notes(notes: &str) -> Diagnosis { + let mut d = Diagnosis::default(); + for raw in notes.lines() { + let l = raw.trim().trim_start_matches(['-', '*', ' ']).trim(); + let after = |p: &str| { + l.strip_prefix(p) + .map(|r| r.trim().trim_matches('`').trim().to_string()) + }; + if let Some(v) = after(NOTE_CLASS) { + d.class = d.class.or_else(|| FailureClass::parse(&v)); + } else if let Some(v) = after(NOTE_CAUSE) { + if d.cause.is_empty() { + d.cause = v; + } + } else if let Some(v) = after(NOTE_TRACE) { + if !v.is_empty() { + d.trace_lines.push(v); + } + } else if let Some(v) = after(NOTE_CITED) { + d.cited.extend( + v.split([',', ';']) + .map(|s| s.trim().trim_matches('`').to_string()) + .filter(|s| !s.is_empty()), + ); + } else if let Some(v) = after(NOTE_WHY) { + if d.why_fix.is_empty() { + d.why_fix = v; + } + } else if let Some(rest) = l.strip_prefix(NOTE_JUSTIFY) { + if let Some((kind, line)) = rest.split_once(':') { + if let Some(kind) = Banned::parse(kind) { + d.justified.push(Justification { + kind, + trace_line: line.trim().trim_matches('`').to_string(), + }); + } + } + } + } + d + } + + /// A justification for `kind` that quotes one of the diagnosis's own + /// trace lines, which are themselves held to the evidence + /// ([`trace_problems`]). + fn justifies(&self, kind: Banned) -> bool { + self.justified.iter().any(|j| { + j.kind == kind + && !j.trace_line.trim().is_empty() + && self + .trace_lines + .iter() + .any(|t| norm(t).contains(&norm(&j.trace_line))) + }) + } +} + +fn norm(s: &str) -> String { + s.split_whitespace() + .collect::>() + .join(" ") + .to_lowercase() +} + +/// The diagnosis's trace lines found in the evidence texts (the errors, +/// page states and code frames read from the failing runs): at least one +/// must be there word for word, so a reviewer can find the cause's line. +pub fn trace_problems(d: &Diagnosis, evidence: &[&str]) -> Vec { + if d.trace_lines.is_empty() || evidence.iter().all(|e| e.trim().is_empty()) { + return Vec::new(); + } + let hay: Vec = evidence.iter().map(|e| norm(e)).collect(); + let found = d.trace_lines.iter().any(|t| { + let n = norm(t); + n.len() >= 8 && hay.iter().any(|h| h.contains(&n)) + }); + if found { + Vec::new() + } else { + vec![format!( + "none of the quoted trace lines is in the failing run's report (`{}`); quote at least one as it appears there", + crate::truncate_str(&d.trace_lines[0], 120) + )] + } +} + +/// A path that is application code: not test code and not docs. +pub fn is_app_code(path: &str) -> bool { + let l = path.to_lowercase(); + let docs = l.ends_with(".md") || l.ends_with(".txt") || l.starts_with("docs/"); + !docs && !is_test_code(path) && !super::bug_rules::is_e2e_code(path) +} + +/// Why the evidence doesn't fit the class claimed. `own_hosts` are the +/// team's own sites (the test target, preview and staging hosts). +pub fn class_problems( + d: &Diagnosis, + repro: &Repro, + rates: &PassRates, + own_hosts: &[String], +) -> Vec { + let mut out = Vec::new(); + let Some(class) = d.class else { + out.push(format!( + "no class is named; write `{NOTE_CLASS} `", + FailureClass::ALL.map(|c| c.as_str()).join(", ") + )); + return out; + }; + if d.cause.trim().is_empty() { + out.push(format!("no root cause is named; write `{NOTE_CAUSE} …`")); + } + if d.trace_lines.is_empty() { + out.push(format!( + "the cause cites no line from the failing run; write `{NOTE_TRACE} …` with a line copied from its trace, report or log" + )); + } + let measures: Vec = [rates.base, rates.head] + .into_iter() + .flatten() + .chain(match repro { + Repro::Repeat { measure, .. } | Repro::NotReproduced { measure } => Some(*measure), + _ => None, + }) + .collect(); + let every = measures.iter().any(Measure::every_run_failed); + let not_reached = measures.iter().any(|m| m.not_reached > 0) + || matches!(repro, Repro::Unrunnable { .. }) + || repro + .artifacts() + .is_some_and(|a| not_reached(&a.error).is_some()); + match class { + FailureClass::TimingRace if every => out.push( + "a timing race passes some runs, but this test failed every counted run: look for a bug in the app, the test or its data".into(), + ), + FailureClass::AppBug => { + if !d.cited.iter().any(|c| is_app_code(c.split(':').next().unwrap_or(c))) { + out.push(format!( + "an app bug names the app code it is in; write `{NOTE_CITED} `" + )); + } + if rates.base.is_some_and(|m| m.counted() > 0 && m.failed == 0) + && !matches!(repro, Repro::Report { .. }) + { + out.push( + "an app bug fails on the base branch, but every counted run there passed".into(), + ); + } + } + FailureClass::TestBug => { + if !d.cited.iter().any(|c| is_test_code(c.split(':').next().unwrap_or(c))) { + out.push(format!( + "a test bug names the test code it is in; write `{NOTE_CITED} `" + )); + } + } + FailureClass::CiInfra if !not_reached && !d.trace_lines.iter().any(|t| infra_line(t)) => { + out.push( + "CI infrastructure is shown by a run that never reached the page or a runner, network or deploy error in the trace; none is quoted".into(), + ); + } + FailureClass::ThirdParty => { + let foreign = d + .trace_lines + .iter() + .flat_map(|t| hosts_in(t)) + .any(|h| !own_hosts.iter().any(|o| h == *o || h.ends_with(&format!(".{o}")))); + if !foreign { + out.push( + "a third party is shown by a trace line naming its host, one that isn't the team's own site".into(), + ); + } + } + _ => {} + } + out +} + +fn infra_line(t: &str) -> bool { + let l = t.to_lowercase(); + not_reached(t).is_some() + || [ + "err_connection_closed", + "err_connection_reset", + "econnreset", + "socket hang up", + "502 bad gateway", + "503 service unavailable", + "504 gateway", + "out of memory", + "no space left on device", + "runner", + "deploy", + ] + .iter() + .any(|s| l.contains(s)) +} + +/// Host names in a line of text. +pub fn hosts_in(text: &str) -> Vec { + let mut out = Vec::new(); + for part in text.split(|c: char| c.is_whitespace() || "\"'(),<>`".contains(c)) { + let rest = part + .strip_prefix("https://") + .or_else(|| part.strip_prefix("http://")); + if let Some(r) = rest { + let host = r.split(['/', ':', '?', '#']).next().unwrap_or(""); + if host.contains('.') { + out.push(host.to_lowercase()); + } + } + } + out +} + +// ── banned fixes ────────────────────────────────────────────────────────── + +/// A change a test fix may not make without a diagnosis that justifies it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Banned { + FixedSleep, + RaisedTimeout, + AddedRetries, + Poll, + WeakenedAssertion, + Skip, + BroadenedSelector, + /// An app bug "fixed" by changing only the test. + AppBugInTest, + /// A code change for a cause outside the code. + CodeForOutsideCause, +} + +impl Banned { + pub fn as_str(self) -> &'static str { + match self { + Banned::FixedSleep => "fixed_sleep", + Banned::RaisedTimeout => "raised_timeout", + Banned::AddedRetries => "added_retries", + Banned::Poll => "poll", + Banned::WeakenedAssertion => "weakened_assertion", + Banned::Skip => "skip", + Banned::BroadenedSelector => "broadened_selector", + Banned::AppBugInTest => "app_bug_in_test", + Banned::CodeForOutsideCause => "code_for_outside_cause", + } + } + + pub fn parse(s: &str) -> Option { + let k = s.trim().to_lowercase().replace([' ', '-'], "_"); + [ + Banned::FixedSleep, + Banned::RaisedTimeout, + Banned::AddedRetries, + Banned::Poll, + Banned::WeakenedAssertion, + Banned::Skip, + Banned::BroadenedSelector, + Banned::AppBugInTest, + Banned::CodeForOutsideCause, + ] + .into_iter() + .find(|b| b.as_str() == k) + } + + pub fn words(self) -> &'static str { + match self { + Banned::FixedSleep => "adds a fixed sleep", + Banned::RaisedTimeout => "raises a timeout", + Banned::AddedRetries => "adds retries", + Banned::Poll => "adds a poll", + Banned::WeakenedAssertion => "removes or loosens an assertion", + Banned::Skip => "skips the test", + Banned::BroadenedSelector => "broadens a selector so it matches more than before", + Banned::AppBugInTest => "changes only the test for a bug in the app", + Banned::CodeForOutsideCause => "changes code for a cause outside the code", + } + } + + /// Whether a diagnosis may justify it at all, and for which class. + fn may_be_justified(self, class: Option) -> bool { + match self { + Banned::RaisedTimeout | Banned::Poll => class == Some(FailureClass::TimingRace), + Banned::BroadenedSelector => class == Some(FailureClass::TestBug), + _ => false, + } + } +} + +/// One refused change. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Rejection { + pub path: String, + pub kind: Banned, + pub line: String, +} + +impl Rejection { + pub fn sentence(&self) -> String { + if self.line.is_empty() { + format!("`{}` {}", self.path, self.kind.words()) + } else { + format!( + "`{}` {} (`{}`)", + self.path, + self.kind.words(), + crate::truncate_str(&self.line, 160) + ) + } + } +} + +fn locator_call(code: &str) -> bool { + [ + "getbyrole(", + "getbytext(", + "getbylabel(", + "getbytestid(", + "getbyplaceholder(", + "getbytitle(", + "locator(", + "cy.get(", + "cy.contains(", + "$(", + "find(", + "queryselector", + ] + .iter() + .any(|c| code.to_lowercase().contains(c)) +} + +/// Marks that make a locator match more: picking one of many, a partial +/// attribute match, dropping exactness, a case-free pattern. +fn breadth(line: &str) -> u32 { + let l = line.to_lowercase(); + let mut n = 0; + for m in [ + ".first()", + ".last()", + ".nth(", + "*=", + "^=", + "$=", + ":has-text(", + "/i)", + "/i,", + "/i }", + ] { + n += l.matches(m).count() as u32; + } + if l.contains("exact: false") || l.contains("exact:false") { + n += 1; + } + n +} + +fn exact(line: &str) -> u32 { + let l = line.to_lowercase(); + (l.matches("exact: true").count() + l.matches("exact:true").count()) as u32 +} + +/// Locators in test code that match more after the change: each hunk that +/// replaces a locator line with one carrying more breadth marks, or drops +/// `exact: true`. +pub fn broadened_selectors(files: &[(String, String, String)]) -> Vec { + let mut out = Vec::new(); + for (path, _, patch) in files { + if !is_test_code(path) { + continue; + } + let mut removed: Vec = Vec::new(); + let mut added: Vec<(String, String)> = Vec::new(); + let mut flush = |removed: &mut Vec, added: &mut Vec<(String, String)>| { + let r: Vec<&String> = removed.iter().filter(|c| locator_call(c)).collect(); + let a: Vec<&(String, String)> = added.iter().filter(|(c, _)| locator_call(c)).collect(); + if !r.is_empty() && !a.is_empty() { + let before: u32 = r.iter().map(|c| breadth(c)).sum(); + let after: u32 = a.iter().map(|(c, _)| breadth(c)).sum(); + let ex_before: u32 = r.iter().map(|c| exact(c)).sum(); + let ex_after: u32 = a.iter().map(|(c, _)| exact(c)).sum(); + if after > before || ex_after < ex_before { + let line = a + .iter() + .find(|(c, _)| breadth(c) > 0 || exact(c) < ex_before) + .or(a.first()) + .map(|(_, raw)| raw.trim().to_string()) + .unwrap_or_default(); + out.push(Rejection { + path: path.clone(), + kind: Banned::BroadenedSelector, + line, + }); + } + } + removed.clear(); + added.clear(); + }; + for l in patch.lines() { + if l.starts_with("@@") { + flush(&mut removed, &mut added); + continue; + } + if l.starts_with("+++") || l.starts_with("---") { + continue; + } + if let Some(b) = l.strip_prefix('+') { + added.push((code_with_strings(path, b), b.to_string())); + } else if let Some(b) = l.strip_prefix('-') { + removed.push(code_with_strings(path, b)); + } else { + flush(&mut removed, &mut added); + } + } + flush(&mut removed, &mut added); + } + out +} + +/// The line with comments taken out but strings kept: a locator's breadth +/// is in its strings and patterns. +fn code_with_strings(path: &str, line: &str) -> String { + if code_of(path, line).is_empty() { + return String::new(); + } + match line.find("//") { + Some(i) if !line[..i].contains("http") && !line[..i].ends_with(':') => { + line[..i].trim().to_string() + } + _ => line.trim().to_string(), + } +} + +/// Every banned change in the diff (`files`: path, status, patch), given +/// the diagnosis. A raised timeout or a poll stands only for a timing race +/// whose diagnosis justifies it with one of its trace lines; a broadened +/// selector only for a test bug justified the same way; the rest never. +pub fn judge_diff(files: &[(String, String, String)], d: &Diagnosis) -> Vec { + let mut found: Vec = Vec::new(); + for f in fix_guard::added_waits(files) { + let kind = match f.kind { + Kind::FixedWait => Banned::FixedSleep, + Kind::Timeout => Banned::RaisedTimeout, + Kind::Retries => Banned::AddedRetries, + Kind::Poll => Banned::Poll, + Kind::RowWalk => continue, + }; + found.push(Rejection { + path: f.path, + kind, + line: f.line, + }); + } + for w in integrity::weakenings(files) { + found.push(Rejection { + path: w.path, + kind: if w.kind == Loosening::Skipped { + Banned::Skip + } else { + Banned::WeakenedAssertion + }, + line: w.line, + }); + } + found.extend(broadened_selectors(files)); + let changed: Vec<&String> = files.iter().map(|(p, _, _)| p).collect(); + match d.class { + Some(FailureClass::AppBug) if !changed.iter().any(|p| is_app_code(p)) => { + found.push(Rejection { + path: changed.first().map(|p| p.to_string()).unwrap_or_default(), + kind: Banned::AppBugInTest, + line: String::new(), + }); + } + Some(c) if c.outside_code() && !changed.is_empty() => { + for p in changed { + found.push(Rejection { + path: p.clone(), + kind: Banned::CodeForOutsideCause, + line: String::new(), + }); + } + } + _ => {} + } + found + .into_iter() + .filter(|r| !(r.kind.may_be_justified(d.class) && d.justifies(r.kind))) + .collect() +} + +// ── how many runs prove a fix ───────────────────────────────────────────── + +/// The confidence a proof is held to. +pub const CONFIDENCE: f64 = 0.95; +/// Fewest repeat runs any proof uses. +pub const MIN_REPEATS: u32 = 10; +/// Most repeat runs one proof asks for; past this the proof is partial and +/// the watch after merge carries the rest. +pub const MAX_REPEATS: u32 = 300; +/// The rate assumed when none was measured: a test failing one run in ten. +pub const UNMEASURED_RATE: f64 = 0.10; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct RepeatNeed { + pub runs: u32, + /// The rate needed more than [`MAX_REPEATS`]: `runs` is the cap. + pub capped: bool, +} + +/// Clean runs needed so that a test still failing at `rate` would have +/// failed at least once with probability `confidence`: +/// n = ln(1 - confidence) / ln(1 - rate). +pub fn repeats_for(rate: f64, confidence: f64) -> RepeatNeed { + let rate = if rate.is_finite() && rate > 0.0 { + rate.min(1.0) + } else { + UNMEASURED_RATE + }; + if rate >= 1.0 { + return RepeatNeed { + runs: MIN_REPEATS, + capped: false, + }; + } + let n = ((1.0 - confidence).ln() / (1.0 - rate).ln()).ceil(); + if n > f64::from(MAX_REPEATS) { + RepeatNeed { + runs: MAX_REPEATS, + capped: true, + } + } else { + RepeatNeed { + runs: (n as u32).max(MIN_REPEATS), + capped: false, + } + } +} + +/// The rate a proof is sized from: the highest measured before the fix +/// (CI history, the base branch, the reproduction). +pub fn rate_before(measures: &[Measure]) -> Option { + measures + .iter() + .filter_map(Measure::rate) + .filter(|r| *r > 0.0) + .fold(None, |acc: Option, r| { + Some(acc.map_or(r, |a| a.max(r))) + }) +} + +/// A test's recorded CI runs as counts: a run that failed or passed only on +/// a retry counts as a failure; skipped runs and runs that broke as a whole +/// don't count. Only runs before `before` (an RFC 3339 time) when given. +pub fn history_measure(history: &[super::model::HistoryEntry], before: Option<&str>) -> Measure { + use super::model::Outcome; + let mut m = Measure::default(); + for e in history { + if before.is_some_and(|b| e.at.as_str() >= b) { + continue; + } + if e.bad_run { + m.not_reached += 1; + continue; + } + match e.outcome { + Outcome::Passed => m.passed += 1, + Outcome::Failed | Outcome::Flaky => m.failed += 1, + Outcome::Skipped => {} + } + } + m +} + +/// A report tally as counts, the same way. +pub fn tally_measure(t: &super::flake::Tally) -> Measure { + let failed = t.failed_runs + t.flaky_runs; + Measure { + passed: t.runs.saturating_sub(failed), + failed, + not_reached: 0, + } +} + +/// Repeat runs a fix to a test with this history needs, from the runs +/// before its fix started. +pub fn repeats_for_history(history: &[super::model::HistoryEntry], before: Option<&str>) -> u32 { + let rate = rate_before(&[history_measure(history, before)]); + repeats_for(rate.unwrap_or(UNMEASURED_RATE), CONFIDENCE).runs +} + +/// What the repeat proof on the head showed. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum ProofVerdict { + Holds { + runs: u32, + }, + Fails { + passed: u32, + failed: u32, + }, + TooFew { + have: u32, + need: u32, + }, + /// Ran somewhere other than where the test failed. + WrongTarget { + ran: String, + failed: String, + }, + /// Ran on another commit than the pull request's head. + WrongHead { + ran: String, + head: String, + }, +} + +impl ProofVerdict { + pub fn holds(&self) -> bool { + matches!(self, ProofVerdict::Holds { .. }) + } + + pub fn sentence(&self) -> String { + match self { + ProofVerdict::Holds { runs } => { + format!("The fix held: {runs}/{runs} passed, retries off.") + } + ProofVerdict::Fails { passed, failed } => format!( + "The fix didn't hold: {failed} of {} runs failed.", + passed + failed + ), + ProofVerdict::TooFew { have, need } => format!( + "Not proven yet: {have} clean runs, and the measured failure rate needs {need}." + ), + ProofVerdict::WrongTarget { ran, failed } => { + format!("Not proven: the runs went to {ran}, but the test failed on {failed}.") + } + ProofVerdict::WrongHead { ran, head } => { + format!("Not proven: the runs were on {ran}, not the pull request's head {head}.") + } + } + } +} + +/// Judges the repeat proof `after`, run on `ran_head` against `ran_target`, +/// for a fix to a test failing at `rate` before, whose failures were on +/// `failed_target`, on the pull request's `head`. +pub fn proof( + rate: Option, + after: &Measure, + (ran_head, head): (&str, &str), + (ran_target, failed_target): (&str, &str), +) -> ProofVerdict { + if !ran_head.is_empty() + && !head.is_empty() + && !ran_head.starts_with(head) + && !head.starts_with(ran_head) + { + return ProofVerdict::WrongHead { + ran: ran_head.into(), + head: head.into(), + }; + } + if !failed_target.is_empty() && !same_target(ran_target, failed_target) { + return ProofVerdict::WrongTarget { + ran: ran_target.into(), + failed: failed_target.into(), + }; + } + if after.failed > 0 { + return ProofVerdict::Fails { + passed: after.passed, + failed: after.failed, + }; + } + let need = repeats_for(rate.unwrap_or(UNMEASURED_RATE), CONFIDENCE).runs; + if after.passed < need { + ProofVerdict::TooFew { + have: after.passed, + need, + } + } else { + ProofVerdict::Holds { runs: after.passed } + } +} + +/// Two targets are the same environment: the same host, or a pull +/// request's preview against a failure on another preview of the same app +/// (`pr-12.preview.example.com` and `pr-40.preview.example.com`). +pub fn same_target(a: &str, b: &str) -> bool { + let host = |s: &str| { + let s = s.trim(); + let s = s + .strip_prefix("https://") + .or_else(|| s.strip_prefix("http://")) + .unwrap_or(s); + s.split(['/', '?', '#']).next().unwrap_or("").to_lowercase() + }; + let (ha, hb) = (host(a), host(b)); + if ha == hb { + return true; + } + let preview_base = |h: &str| { + let (first, rest) = h.split_once('.')?; + let n = first.strip_prefix("pr-")?; + n.chars() + .all(|c| c.is_ascii_digit()) + .then(|| rest.to_string()) + }; + matches!((preview_base(&ha), preview_base(&hb)), (Some(x), Some(y)) if x == y) +} + +// ── one run per failure ─────────────────────────────────────────────────── + +/// One failing occurrence of a test. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Occurrence { + pub test_id: String, + pub file: String, + pub error: String, + #[serde(default)] + pub stack: String, + #[serde(default)] + pub ci_run: u64, + #[serde(default)] + pub at: String, + /// The signature the report reading already worked out, when known. + #[serde(default)] + pub signature: String, +} + +impl Occurrence { + /// The failure's signature (`common::e2e::signature`). + pub fn sig(&self) -> String { + if self.signature.is_empty() { + signature::signature(&self.error, &self.stack) + } else { + self.signature.clone() + } + } +} + +/// A fix run that is still open, or merged and watched. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct OpenFix { + pub run_id: String, + pub test_ids: Vec, + pub file: String, + pub signatures: Vec, +} + +/// Where a new occurrence goes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Attach { + /// Into this run as evidence; `sibling` when it is another test of the + /// same spec failing the same way. + Join { + run_id: String, + sibling: bool, + }, + New, +} + +/// One run per failure: the same test joins its open run whatever the +/// signature; another test of the same spec with the same signature joins +/// as a sibling. +pub fn attach(open: &[OpenFix], o: &Occurrence) -> Attach { + if let Some(f) = open.iter().find(|f| f.test_ids.contains(&o.test_id)) { + return Attach::Join { + run_id: f.run_id.clone(), + sibling: false, + }; + } + let sig = o.sig(); + if let Some(f) = open + .iter() + .find(|f| f.file == o.file && !sig.is_empty() && f.signatures.contains(&sig)) + { + return Attach::Join { + run_id: f.run_id.clone(), + sibling: true, + }; + } + Attach::New +} + +// ── after the merge ─────────────────────────────────────────────────────── + +/// CI runs of the test on the default branch read after a fix merged, at +/// most. +pub const MAX_WATCH: u32 = 50; + +/// The first line of a reopened fix's ticket: the run gathers its evidence +/// again instead of reusing what it read before the merge. +pub const REOPEN_MARK: &str = "Reopened: the merged fix failed again.\n"; + +/// The watch on a merged fix. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Watch { + pub run_id: String, + pub test_id: String, + pub merged_sha: String, + pub merged_at: String, + /// Clean default-branch runs needed to call it held. + pub need: u32, + pub passes: u32, + /// CI runs already read, so one is never counted twice. + #[serde(default)] + pub seen: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub held_at: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WatchStep { + Watching { + left: u32, + }, + Held, + /// The test failed again: reopen `run_id` with this evidence. + Reopen { + run_id: String, + evidence: String, + }, + /// A run already read, or one that says nothing. + Ignored, +} + +impl Watch { + /// Watches a fix to a test that failed at `rate` before it merged. + pub fn new(run_id: &str, test_id: &str, sha: &str, at: &str, rate: Option) -> Watch { + let need = repeats_for(rate.unwrap_or(UNMEASURED_RATE), CONFIDENCE) + .runs + .min(MAX_WATCH); + Watch { + run_id: run_id.into(), + test_id: test_id.into(), + merged_sha: sha.into(), + merged_at: at.into(), + need, + ..Default::default() + } + } + + /// One default-branch CI run of the test, after the merge. + pub fn observe(&mut self, ci_run: u64, sha: &str, result: &RunResult) -> WatchStep { + if self.held_at.is_some() || self.seen.contains(&ci_run) { + return WatchStep::Ignored; + } + self.seen.push(ci_run); + match result { + RunResult::NotReached { .. } => WatchStep::Ignored, + RunResult::Passed => { + self.passes += 1; + if self.passes >= self.need { + self.held_at = Some(chrono::Utc::now().to_rfc3339()); + WatchStep::Held + } else { + WatchStep::Watching { + left: self.need - self.passes, + } + } + } + RunResult::Failed { error } => WatchStep::Reopen { + run_id: self.run_id.clone(), + evidence: format!( + "The test failed again after the fix merged ({}): CI run {ci_run} on {} failed after {} clean run(s):\n```\n{}\n```", + short(&self.merged_sha), + short(sha), + self.passes, + crate::truncate_str(error, 1_500) + ), + }, + } + } +} + +fn short(sha: &str) -> &str { + &sha[..sha.len().min(7)] +} + +// ── quarantine with terms ───────────────────────────────────────────────── + +/// Days a quarantine lasts unless set otherwise. +pub const QUARANTINE_DAYS: i64 = 14; +/// Longest a quarantine may be set for. +pub const MAX_QUARANTINE_DAYS: i64 = 30; + +/// Why a test is quarantined, who owns getting it out, the ticket, and +/// when it expires. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct QuarantineTerms { + pub owner: String, + pub reason: String, + #[serde(default)] + pub ticket: String, + pub since: String, + pub expires_at: String, +} + +impl QuarantineTerms { + /// Terms for a quarantine starting `now`, for `days` (default + /// [`QUARANTINE_DAYS`], at most [`MAX_QUARANTINE_DAYS`]). An owner and + /// a reason are required. + pub fn new( + owner: &str, + reason: &str, + ticket: &str, + now: DateTime, + days: Option, + ) -> Result { + let (owner, reason) = (owner.trim(), reason.trim()); + if owner.is_empty() { + return Err("a quarantine needs an owner".into()); + } + if reason.is_empty() { + return Err("a quarantine needs a reason".into()); + } + let days = days.unwrap_or(QUARANTINE_DAYS); + if !(1..=MAX_QUARANTINE_DAYS).contains(&days) { + return Err(format!( + "a quarantine lasts 1 to {MAX_QUARANTINE_DAYS} days" + )); + } + Ok(QuarantineTerms { + owner: owner.into(), + reason: crate::truncate_str(reason, 300).to_string(), + ticket: ticket.trim().into(), + since: now.to_rfc3339(), + expires_at: (now + Duration::days(days)).to_rfc3339(), + }) + } + + pub fn expired(&self, now: DateTime) -> bool { + DateTime::parse_from_rfc3339(&self.expires_at) + .map(|t| t.with_timezone(&Utc) <= now) + .unwrap_or(false) + } + + /// What the Tests page shows. + pub fn summary(&self, now: DateTime) -> serde_json::Value { + serde_json::json!({ + "owner": self.owner, + "reason": self.reason, + "ticket": self.ticket, + "since": self.since, + "expires_at": self.expires_at, + "expired": self.expired(now), + }) + } +} + +/// Keeps a test's quarantine terms in step with its state: a quarantined +/// test with none gets them (its owner, else CoderHelm; its recorded cause +/// as the reason; its ticket; the default expiry from when it entered), and +/// a test out of quarantine keeps none. +pub fn keep_terms(r: &mut super::model::TestRecord, now: DateTime) { + if !r.quarantined { + r.care.quarantine_terms = None; + return; + } + if r.care.quarantine_terms.is_some() { + return; + } + let since = r + .quarantined_since + .as_deref() + .and_then(|s| DateTime::parse_from_rfc3339(s).ok()) + .map(|t| t.with_timezone(&Utc)) + .unwrap_or(now); + let owner = r + .owner + .clone() + .filter(|o| !o.trim().is_empty()) + .unwrap_or_else(|| "CoderHelm".into()); + let reason = match &r.cause { + Some(c) if !c.evidence.trim().is_empty() => format!("{}: {}", c.label, c.evidence), + Some(c) => c.label.clone(), + None => format!( + "{} on the default branch; cause not worked out yet", + r.health.as_str() + ), + }; + let ticket = r.ticket_url.clone().unwrap_or_default(); + r.care.quarantine_terms = QuarantineTerms::new(&owner, &reason, &ticket, since, None).ok(); +} + +// ── the pull request ────────────────────────────────────────────────────── + +/// Headings every test-fix description carries. +pub const BODY_HEADINGS: [&str; 5] = [ + "Root cause", + "Class", + "Evidence", + "Why this fixes it", + "Pass rate before and after", +]; + +/// The section that names the cause, for the pull request's description. +pub fn cause_section( + d: &Diagnosis, + repro: &Repro, + rates: &PassRates, + proof_verdict: Option<&ProofVerdict>, +) -> String { + let mut s = String::new(); + s.push_str(&format!( + "### Root cause\n{}\n\n", + if d.cause.is_empty() { + "Not named." + } else { + &d.cause + } + )); + s.push_str(&format!( + "### Class\n{}\n\n", + d.class + .map(|c| format!("`{}`: {}", c.as_str(), c.words())) + .unwrap_or_else(|| "Not classified.".into()) + )); + s.push_str("### Evidence\n"); + s.push_str(&format!("{}\n", repro.line())); + for t in &d.trace_lines { + s.push_str(&format!("```\n{t}\n```\n")); + } + if !d.cited.is_empty() { + s.push_str(&format!("Cause in: {}\n", d.cited.join(", "))); + } + if let Some(b) = &rates.bisect { + s.push_str(&format!( + "Last commit it passed on: {}; first that failed: {}\n", + short(&b.last_good), + short(&b.first_bad) + )); + } + s.push_str(&format!( + "\n### Why this fixes it\n{}\n\n", + if d.why_fix.is_empty() { + "Not stated." + } else { + &d.why_fix + } + )); + s.push_str("### Pass rate before and after\n"); + let m = |m: Option| m.map(|m| m.line()).unwrap_or_else(|| "not measured".into()); + s.push_str(&format!("- Base branch: {}\n", m(rates.base))); + s.push_str(&format!("- This head: {}\n", m(rates.head))); + if let Some(p) = proof_verdict { + s.push_str(&format!("- {}\n", p.sentence())); + } + s +} + +/// What a test-fix description is missing. +pub fn body_problems(body: &str) -> Vec { + let l = body.to_lowercase(); + BODY_HEADINGS + .iter() + .filter(|h| !l.contains(&h.to_lowercase())) + .map(|h| format!("the description has no `{h}` section")) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::TimeZone; + + #[test] + fn a_proofs_routes_feed_the_evidence_and_its_count() { + use crate::e2e::proof_routes::{repeat_count, Tally}; + let m = Measure::from(Tally { + passed: 20, + failed: 0, + not_reached: 2, + }); + assert_eq!((m.counted(), m.not_reached), (20, 2)); + // A test failing one run in five needs more than the review's count. + let measured = measured_repeats(Some(0.2)); + assert_eq!( + repeat_count(10, measured), + repeats_for(0.2, CONFIDENCE).runs + ); + assert_eq!(repeat_count(10, measured_repeats(None)), 10); + // Routes that never reached the page never make a proof fail. + assert!(!matches!( + proof(Some(0.2), &m, ("abc", "abc"), ("", "")), + ProofVerdict::Fails { .. } + )); + } + + fn file(path: &str, patch: &str) -> (String, String, String) { + (path.into(), "modified".into(), patch.into()) + } + + fn report_failure() -> FailureExtract { + FailureExtract { + test: "cart › a paperback goes in the basket".into(), + file: "e2e/cart.spec.ts".into(), + status: "failed".into(), + error: "expect(locator).toHaveText(expected) failed\nExpected: \"1 item\"\nReceived: \"0 items\"".into(), + attachments: vec!["data/a1b2.zip".into(), "data/a1b2.png".into()], + source: "s3://acme-bookstore-reports/run-7/index.html".into(), + ..Default::default() + } + } + + #[test] + fn classes_parse_and_place_the_fix() { + assert_eq!(FailureClass::parse("App bug"), Some(FailureClass::AppBug)); + assert_eq!( + FailureClass::parse("`ci_infra`"), + Some(FailureClass::CiInfra) + ); + assert_eq!( + FailureClass::parse("timing/race"), + Some(FailureClass::TimingRace) + ); + assert_eq!(FailureClass::parse("cosmic rays"), None); + assert_eq!(FailureClass::AppBug.locations(), &[FixLocation::App]); + assert!(FailureClass::ThirdParty.outside_code()); + assert!(!FailureClass::TestDataEnv.outside_code()); + for c in FailureClass::ALL { + assert_eq!(FailureClass::parse(c.as_str()), Some(c)); + } + } + + #[test] + fn runs_that_never_reached_the_page_are_not_failures() { + let runs = vec![ + RunResult::failed( + "net::ERR_TUNNEL_CONNECTION_FAILED at https://staging.acme-books.test/cart", + ), + RunResult::failed("CODERHELM_EGRESS_BLOCKED staging.acme-books.test"), + RunResult::Passed, + RunResult::failed("Expected: \"1 item\" Received: \"0 items\""), + ]; + let m = Measure::of(&runs); + assert_eq!((m.passed, m.failed, m.not_reached), (1, 1, 2)); + assert_eq!(m.rate(), Some(0.5)); + assert!(m.line().contains("2 more never reached")); + let blocked = Measure { + not_reached: 20, + ..Default::default() + }; + assert!(!blocked.every_run_failed()); + assert!(matches!( + reproduction( + Some((&blocked, "https://staging.acme-books.test", None)), + &[], + None + ), + Repro::Unrunnable { .. } + )); + } + + #[test] + fn a_report_with_its_trace_is_a_reproduction_and_bare_words_are_not() { + let r = reproduction(None, &[report_failure()], None); + assert!(r.reproduced()); + assert!(r.line().contains("its trace")); + let mut bare = report_failure(); + bare.attachments.clear(); + assert!(!reproduction(None, &[bare], None).reproduced()); + } + + #[test] + fn no_reproduction_means_no_code_change() { + assert!(matches!( + next_step(&Repro::None, Some(FailureClass::TestBug), None), + Next::GatherEvidence { .. } + )); + let few = Repro::NotReproduced { + measure: Measure { + passed: 10, + ..Default::default() + }, + }; + match next_step(&few, Some(FailureClass::TimingRace), Some(0.05)) { + Next::GatherEvidence { what } => assert!(what.contains("needs 59 runs"), "{what}"), + other => panic!("{other:?}"), + } + let many = Repro::NotReproduced { + measure: Measure { + passed: 80, + ..Default::default() + }, + }; + assert!(matches!( + next_step(&many, None, Some(0.05)), + Next::Quarantine { .. } + )); + let r = reproduction(None, &[report_failure()], None); + assert_eq!(next_step(&r, Some(FailureClass::AppBug), None), Next::Fix); + assert!(matches!( + next_step(&r, Some(FailureClass::ThirdParty), None), + Next::Quarantine { .. } + )); + assert!(matches!( + next_step(&r, None, None), + Next::GatherEvidence { .. } + )); + } + + #[test] + fn the_first_bad_commit_is_found_and_the_middle_is_run_next() { + let m = |p, f| { + Some(Measure { + passed: p, + failed: f, + not_reached: 0, + }) + }; + let commits = vec![ + ("a1".to_string(), m(10, 0)), + ("b2".to_string(), m(10, 0)), + ("c3".to_string(), None), + ("d4".to_string(), None), + ("e5".to_string(), None), + ("f6".to_string(), m(7, 3)), + ]; + let b = first_bad(&commits).unwrap(); + assert_eq!((b.last_good.as_str(), b.first_bad.as_str()), ("b2", "f6")); + assert_eq!(bisect_next(&commits).as_deref(), Some("d4")); + } + + #[test] + fn the_diagnosis_is_read_from_the_notes() { + let notes = "Some thinking.\n- Class: app bug\n- Root cause: the basket count reads the cache before the add resolves\n- Trace: Received: \"0 items\"\n- Cause in: apps/shop/src/basket/count.ts:41\n- Why this fixes it: the count waits for the add's response\n- Justify raised_timeout: Received: \"0 items\"\n"; + let d = Diagnosis::from_notes(notes); + assert_eq!(d.class, Some(FailureClass::AppBug)); + assert_eq!(d.cited, vec!["apps/shop/src/basket/count.ts:41"]); + assert_eq!(d.justified.len(), 1); + assert!(trace_problems(&d, &[&report_failure().error]).is_empty()); + let mut made_up = d.clone(); + made_up.trace_lines = vec!["TypeError: basket is undefined".into()]; + assert_eq!( + trace_problems(&made_up, &[&report_failure().error]).len(), + 1 + ); + made_up.trace_lines.push("Received: \"0 items\"".into()); + assert!(trace_problems(&made_up, &[&report_failure().error]).is_empty()); + } + + #[test] + fn the_class_must_fit_the_evidence() { + let race = Diagnosis { + class: Some(FailureClass::TimingRace), + cause: "the click lands before hydration".into(), + trace_lines: vec!["Received: \"0 items\"".into()], + ..Default::default() + }; + let every = PassRates { + base: Some(Measure { + failed: 10, + ..Default::default() + }), + ..Default::default() + }; + let p = class_problems(&race, &Repro::None, &every, &[]); + assert!( + p.iter().any(|x| x.contains("failed every counted run")), + "{p:?}" + ); + let third = Diagnosis { + class: Some(FailureClass::ThirdParty), + cause: "the payment sandbox refused the card".into(), + trace_lines: vec!["POST https://pay.example-gateway.test/v1/charge 503".into()], + ..Default::default() + }; + assert!(class_problems( + &third, + &Repro::None, + &PassRates::default(), + &["acme-books.test".into()] + ) + .is_empty()); + let own = Diagnosis { + trace_lines: vec!["GET https://staging.acme-books.test/cart 503".into()], + ..third + }; + assert!(!class_problems( + &own, + &Repro::None, + &PassRates::default(), + &["acme-books.test".into()] + ) + .is_empty()); + } + + #[test] + fn broadened_selectors_are_caught() { + let patch = "@@ -1,2 +1,2 @@\n- await page.getByRole('button', { name: 'Add to basket', exact: true }).click();\n+ await page.getByRole('button', { name: /add/i }).first().click();\n"; + let r = broadened_selectors(&[file("e2e/pages/cart.ts", patch)]); + assert_eq!(r.len(), 1); + assert_eq!(r[0].kind, Banned::BroadenedSelector); + let narrower = "@@ -1,2 +1,2 @@\n- await page.locator('button').first().click();\n+ await page.getByRole('button', { name: 'Add to basket', exact: true }).click();\n"; + assert!(broadened_selectors(&[file("e2e/pages/cart.ts", narrower)]).is_empty()); + let app = "@@ -1 +1 @@\n- el.querySelector('#a')\n+ el.querySelector('[id^=a]')\n"; + assert!(broadened_selectors(&[file("apps/shop/src/a.ts", app)]).is_empty()); + } + + #[test] + fn a_sleep_is_never_justified_and_a_timeout_only_for_a_shown_race() { + let sleep = "@@ -1,2 +1,3 @@\n await page.goto('/cart');\n+ await page.waitForTimeout(2000);\n await expect(count).toHaveText('1 item');\n"; + let race = Diagnosis { + class: Some(FailureClass::TimingRace), + trace_lines: vec!["waiting for getByText('1 item')".into()], + justified: vec![Justification { + kind: Banned::FixedSleep, + trace_line: "waiting for getByText('1 item')".into(), + }], + ..Default::default() + }; + let r = judge_diff(&[file("e2e/cart.spec.ts", sleep)], &race); + assert!(r.iter().any(|x| x.kind == Banned::FixedSleep), "{r:?}"); + } + + #[test] + fn an_app_bug_fixed_only_in_the_test_is_refused() { + let d = Diagnosis { + class: Some(FailureClass::AppBug), + ..Default::default() + }; + let test_only = "@@ -1 +1 @@\n- await expect(count).toHaveText('1 item');\n+ await expect(count).toContainText('item');\n"; + let r = judge_diff(&[file("e2e/cart.spec.ts", test_only)], &d); + assert!(r.iter().any(|x| x.kind == Banned::AppBugInTest), "{r:?}"); + assert!( + r.iter().any(|x| x.kind == Banned::WeakenedAssertion), + "{r:?}" + ); + let app = "@@ -1 +1 @@\n- return cache.count;\n+ return (await pending).count;\n"; + assert!(judge_diff(&[file("apps/shop/src/basket/count.ts", app)], &d).is_empty()); + } + + #[test] + fn outside_causes_change_no_code() { + let d = Diagnosis { + class: Some(FailureClass::CiInfra), + ..Default::default() + }; + let any = "@@ -1 +1 @@\n- a();\n+ b();\n"; + let r = judge_diff(&[file("e2e/cart.spec.ts", any)], &d); + assert_eq!(r[0].kind, Banned::CodeForOutsideCause); + } + + #[test] + fn the_repeat_count_scales_with_the_flake_rate() { + assert_eq!(repeats_for(0.5, 0.95).runs, MIN_REPEATS); + assert_eq!(repeats_for(0.10, 0.95).runs, 29); + assert_eq!(repeats_for(0.05, 0.95).runs, 59); + assert_eq!(repeats_for(0.02, 0.95).runs, 149); + let rare = repeats_for(0.001, 0.95); + assert!(rare.capped && rare.runs == MAX_REPEATS); + assert_eq!( + repeats_for(0.0, 0.95).runs, + 29, + "unmeasured is taken as one in ten" + ); + assert!(repeats_for(0.02, 0.95).runs > repeats_for(0.2, 0.95).runs); + } + + #[test] + fn a_proof_needs_enough_runs_on_the_head_and_the_failing_target() { + let twenty = Measure { + passed: 20, + ..Default::default() + }; + let failed_on = "https://staging.acme-books.test"; + assert_eq!( + proof( + Some(0.05), + &twenty, + ("abc123", "abc123"), + (failed_on, failed_on) + ), + ProofVerdict::TooFew { have: 20, need: 59 } + ); + assert!(proof( + Some(0.3), + &twenty, + ("abc123", "abc123"), + (failed_on, failed_on) + ) + .holds()); + assert!(matches!( + proof( + Some(0.3), + &twenty, + ("abc123", "abc123"), + ("http://localhost:3000", failed_on) + ), + ProofVerdict::WrongTarget { .. } + )); + assert!(matches!( + proof( + Some(0.3), + &twenty, + ("def456", "abc123"), + (failed_on, failed_on) + ), + ProofVerdict::WrongHead { .. } + )); + assert!(same_target( + "https://pr-12.preview.acme-books.test/cart", + "https://pr-40.preview.acme-books.test" + )); + } + + #[test] + fn duplicates_join_one_run() { + let open = vec![OpenFix { + run_id: "run-1".into(), + test_ids: vec!["t-basket".into()], + file: "e2e/cart.spec.ts".into(), + signatures: vec![signature::signature( + "Expected: \"1 item\" Received: \"0 items\"", + "", + )], + }]; + let again = Occurrence { + test_id: "t-basket".into(), + file: "e2e/cart.spec.ts".into(), + error: "a different error".into(), + ..Default::default() + }; + assert_eq!( + attach(&open, &again), + Attach::Join { + run_id: "run-1".into(), + sibling: false + } + ); + let sibling = Occurrence { + test_id: "t-basket-mobile".into(), + file: "e2e/cart.spec.ts".into(), + error: "Expected: \"1 item\" Received: \"0 items\"".into(), + ..Default::default() + }; + assert_eq!( + attach(&open, &sibling), + Attach::Join { + run_id: "run-1".into(), + sibling: true + } + ); + let other = Occurrence { + test_id: "t-search".into(), + file: "e2e/search.spec.ts".into(), + error: "Expected: \"1 item\" Received: \"0 items\"".into(), + ..Default::default() + }; + assert_eq!(attach(&open, &other), Attach::New); + } + + #[test] + fn a_failure_after_merge_reopens_the_same_run() { + let mut w = Watch::new( + "run-1", + "t-basket", + "abc1234def", + "2030-03-01T00:00:00Z", + Some(0.3), + ); + assert_eq!(w.need, MIN_REPEATS); + assert_eq!( + w.observe(1, "abc1234", &RunResult::Passed), + WatchStep::Watching { left: 9 } + ); + assert_eq!( + w.observe(1, "abc1234", &RunResult::Passed), + WatchStep::Ignored + ); + assert_eq!( + w.observe( + 2, + "abc1234", + &RunResult::failed("ERR_TUNNEL_CONNECTION_FAILED") + ), + WatchStep::Ignored + ); + match w.observe(3, "fff9999", &RunResult::failed("Received: \"0 items\"")) { + WatchStep::Reopen { run_id, evidence } => { + assert_eq!(run_id, "run-1"); + assert!(evidence.contains("0 items") && evidence.contains("1 clean run")); + } + other => panic!("{other:?}"), + } + let mut held = Watch::new("run-2", "t", "s", "", Some(0.9)); + for i in 0..MIN_REPEATS { + let step = held.observe(u64::from(i), "s", &RunResult::Passed); + if i + 1 == MIN_REPEATS { + assert_eq!(step, WatchStep::Held); + } + } + assert_eq!(Watch::new("r", "t", "s", "", Some(0.001)).need, MAX_WATCH); + } + + #[test] + fn a_watch_never_counts_a_bad_run_or_a_test_that_did_not_run() { + use crate::e2e::model::{Attempt, AttemptError, AttemptStatus}; + let at = |status: AttemptStatus, error: Option<&str>| Attempt { + retry: 0, + status, + duration_ms: 10, + error: error.map(|m| AttemptError { + message: m.into(), + signature: String::new(), + selector: None, + }), + trace_url: None, + video_url: None, + screenshot_url: None, + }; + let failed = [at(AttemptStatus::Failed, Some("Received: \"0 items\""))]; + let passed = [at(AttemptStatus::Passed, None)]; + let skipped = [at(AttemptStatus::Skipped, None)]; + // A run that failed as a whole: never a failure of the test. + assert!(matches!( + watch_result(&failed, true), + RunResult::NotReached { .. } + )); + assert!(matches!( + watch_result(&passed, true), + RunResult::NotReached { .. } + )); + // A test that didn't run: never a pass towards holding the fix. + for none in [ + &skipped[..], + &[], + &[at(AttemptStatus::Interrupted, None)][..], + ] { + assert!(matches!( + watch_result(none, false), + RunResult::NotReached { .. } + )); + } + assert_eq!(watch_result(&passed, false), RunResult::Passed); + assert!(matches!( + watch_result(&failed, false), + RunResult::Failed { .. } + )); + assert!(matches!( + watch_result(&[at(AttemptStatus::TimedOut, None)], false), + RunResult::Failed { .. } + )); + // Fed to the watch: neither reopens nor counts. + let mut w = Watch::new("run-1", "t", "abc1234", "", Some(0.3)); + assert_eq!( + w.observe(1, "abc1234", &watch_result(&failed, true)), + WatchStep::Ignored + ); + assert_eq!( + w.observe(2, "abc1234", &watch_result(&skipped, false)), + WatchStep::Ignored + ); + assert_eq!(w.passes, 0); + } + + #[test] + fn quarantine_has_an_owner_a_reason_and_an_expiry() { + let now = Utc.with_ymd_and_hms(2030, 3, 1, 9, 0, 0).unwrap(); + assert!(QuarantineTerms::new("", "x", "", now, None).is_err()); + assert!(QuarantineTerms::new("dev@acme-books.test", " ", "", now, None).is_err()); + assert!(QuarantineTerms::new("dev@acme-books.test", "x", "", now, Some(90)).is_err()); + let t = QuarantineTerms::new( + "dev@acme-books.test", + "payment sandbox down", + "BOOK-12", + now, + None, + ) + .unwrap(); + assert!(!t.expired(now)); + assert!(t.expired(now + Duration::days(QUARANTINE_DAYS))); + assert_eq!(t.summary(now)["ticket"], "BOOK-12"); + } + + #[test] + fn the_description_names_the_cause() { + let d = Diagnosis::from_notes("Class: test_bug\nRoot cause: the helper waits for a row when the empty shelf is valid\nTrace: waiting for locator('.row')\nCause in: e2e/pages/shelf.ts:12\nWhy this fixes it: it waits for a row or the empty message"); + let rates = PassRates { + base: Some(Measure { + passed: 6, + failed: 4, + not_reached: 0, + }), + head: Some(Measure { + passed: 29, + failed: 0, + not_reached: 0, + }), + bisect: None, + }; + let s = cause_section( + &d, + &reproduction(None, &[report_failure()], None), + &rates, + Some(&ProofVerdict::Holds { runs: 29 }), + ); + assert!(body_problems(&s).is_empty(), "{:?}", body_problems(&s)); + assert!(s.contains("6/10 passed") && s.contains("29/29")); + assert_eq!( + body_problems("## Summary\nfixed it").len(), + BODY_HEADINGS.len() + ); + } +} diff --git a/services/common/src/e2e/mod.rs b/services/common/src/e2e/mod.rs index c2b5a6ab..4eb7113b 100644 --- a/services/common/src/e2e/mod.rs +++ b/services/common/src/e2e/mod.rs @@ -17,6 +17,10 @@ //! - [`report_source`] is where a team keeps each repository's reports. //! - [`failure`] reads the real error and the page state at the failure. //! - [`flake`] counts passes and failures across the reports kept. +//! - [`fix_evidence`] holds a fix to the evidence: reproduced first, one +//! class from a closed set that decides where the fix goes, banned fixes +//! read from the diff, a repeat count sized by the failure rate, one run +//! per failure, a watch after merge, and quarantine with terms. //! - [`fix_guard`] refuses waits without evidence and helpers that walk //! every row. //! - [`test_package`] checks test code in its own package and repeats the @@ -48,6 +52,7 @@ pub mod coverage; pub mod detect; pub mod failure; pub mod failure_read; +pub mod fix_evidence; pub mod fix_guard; pub mod fix_ticket; pub mod flake; diff --git a/services/common/src/e2e/model.rs b/services/common/src/e2e/model.rs index 669e3547..b35dab89 100644 --- a/services/common/src/e2e/model.rs +++ b/services/common/src/e2e/model.rs @@ -372,6 +372,14 @@ pub struct Care { /// by itself. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub bounces: Vec, + /// While quarantined: its owner, reason, ticket and expiry + /// (`fix_evidence::QuarantineTerms`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub quarantine_terms: Option, + /// The watch on a merged fix: the test's next default-branch runs + /// (`fix_evidence::Watch`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub watch: Option, } /// A change of state, with why. Kept as the test's audit log. diff --git a/services/common/src/e2e/stats.rs b/services/common/src/e2e/stats.rs index 600bf536..b9b64a99 100644 --- a/services/common/src/e2e/stats.rs +++ b/services/common/src/e2e/stats.rs @@ -135,6 +135,16 @@ pub fn summary(r: &TestRecord, now: DateTime) -> Value { "release": r.care.release, "removal": r.care.removal, "removed": super::quarantine::is_removed(r), + // Owner, reason, ticket and expiry of the quarantine; `null` when + // none were set. + "quarantine_terms": r.care.quarantine_terms.as_ref().map(|t| t.summary(now)), + // A merged fix being watched: clean runs needed and seen. + "watch": r.care.watch.as_ref().map(|w| json!({ + "run_id": w.run_id, + "need": w.need, + "passes": w.passes, + "held": w.held_at.is_some(), + })), }) } diff --git a/services/common/src/e2e/store.rs b/services/common/src/e2e/store.rs index 7d6845c1..905ef8b8 100644 --- a/services/common/src/e2e/store.rs +++ b/services/common/src/e2e/store.rs @@ -666,6 +666,10 @@ impl<'a> Store<'a> { /// Saves a test's record and its summary together. pub async fn put_record(&self, team: &str, r: &TestRecord) -> Result<(), String> { + // Every quarantine carries its terms, whoever quarantined the test. + let mut r = r.clone(); + super::fix_evidence::keep_terms(&mut r, chrono::Utc::now()); + let r = &r; self.put(&format!("T#{team}#TEST#{}", r.id), "RECORD", r, vec![]) .await?; let summary = super::stats::summary(r, chrono::Utc::now()); diff --git a/services/gateway/src/routes/tests.rs b/services/gateway/src/routes/tests.rs index 6fd48630..f36be71a 100644 --- a/services/gateway/src/routes/tests.rs +++ b/services/gateway/src/routes/tests.rs @@ -624,6 +624,17 @@ pub struct QuarantineBody { on: bool, #[serde(default)] reason: Option, + /// Who gets the test out of quarantine; the test's owner, else the + /// person quarantining it. + #[serde(default)] + owner: Option, + /// The ticket tracking the fix. + #[serde(default)] + ticket: Option, + /// Days until the quarantine expires (`fix_evidence::QUARANTINE_DAYS` + /// by default). + #[serde(default)] + days: Option, } fn event(from: &str, to: &str, reason: String, actor: &str) -> StateEvent { @@ -657,6 +668,26 @@ pub async fn quarantine( if body.on { can_quarantine(&r).map_err(|why| fail(StatusCode::BAD_REQUEST, why))?; if !r.quarantined { + // A quarantine has terms: an owner, a reason, a ticket and an + // expiry, shown on the Tests page. + let owner = body + .owner + .clone() + .filter(|o| !o.trim().is_empty()) + .or_else(|| r.owner.clone()) + .unwrap_or_else(|| claims.email.clone()); + let why = reason.clone().unwrap_or_else(|| { + format!("Quarantined by {} with no reason given.", claims.email) + }); + let terms = common::e2e::fix_evidence::QuarantineTerms::new( + &owner, + &why, + body.ticket.as_deref().unwrap_or(""), + chrono::Utc::now(), + body.days, + ) + .map_err(|why| fail(StatusCode::BAD_REQUEST, &why))?; + r.care.quarantine_terms = Some(terms); quarantine::enter(&mut r, chrono::Utc::now(), &claims.email); let from = r.health.as_str().to_string(); r.events.push(event( @@ -670,6 +701,7 @@ pub async fn quarantine( r.quarantined = false; r.quarantined_since = None; r.quarantined_by = None; + r.care.quarantine_terms = None; let to = r.health.as_str().to_string(); r.events.push(event( "quarantined", @@ -710,6 +742,7 @@ pub async fn pin( r.quarantined = false; r.quarantined_since = None; r.quarantined_by = None; + r.care.quarantine_terms = None; let to = r.health.as_str().to_string(); r.events.push(event( "quarantined", diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index 984a94d3..d8b3edb8 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -30,6 +30,7 @@ use std::io::Read as _; use common::e2e::coverage::{parse_test_map, TestMap, TEST_MAP_PATHS}; use common::e2e::detect::{apply_run, is_bad_run}; +use common::e2e::fix_evidence; use common::e2e::messages::{TestAction, TestIngest}; use common::e2e::model::{ Cause, Execution, HistoryEntry, IngestOutcome, Outcome, ParsedTest, Run, Settings, State, @@ -60,8 +61,26 @@ const MAX_RAW_KEPT: usize = 20 * 1024 * 1024; /// Error text kept in a test's history. const HISTORY_MESSAGE: usize = 500; /// Repeat runs that prove a flaky test reproduces, or that a fix holds. +/// The fewest: the counts follow the test's measured failure rate +/// ([`runs_needed`]). const REPRO_RUNS: u32 = 20; const BURN_IN_RUNS: u32 = 20; + +/// Repeat runs that reproduce a test, or prove its fix, at the failure rate +/// its CI history shows (`fix_evidence::repeats_for`), and never fewer than +/// `floor`. Runs on the fix's own branch, and runs from `before` on (the +/// reproduction's own repeat runs), don't count towards the rate. +fn runs_needed(r: &TestRecord, floor: u32, before: Option<&str>) -> u32 { + let history: Vec = r + .history + .iter() + .filter(|e| r.fix_branch.as_deref() != Some(e.branch.as_str())) + .cloned() + .collect(); + floor.max(common::e2e::fix_evidence::repeats_for_history( + &history, before, + )) +} /// Repeat runs a generated test must pass. const GENERATED_RUNS: u32 = 10; /// Cause labels worked out per run, at most. @@ -1440,7 +1459,7 @@ async fn begin_fix_proof(gh: &GitHubClient, f: &FixPr<'_>, r: &mut TestRecord, n &d, f.head_branch, std::slice::from_ref(&r.title), - BURN_IN_RUNS, + runs_needed(r, BURN_IN_RUNS, None), ) .await { @@ -1549,7 +1568,7 @@ async fn follow_fix( &msg.default_branch, r.fix_phase_at.as_deref(), total, - REPRO_RUNS, + runs_needed(r, REPRO_RUNS, r.fix_phase_at.as_deref()), ) => { if failures > 0 { @@ -1593,7 +1612,7 @@ async fn follow_fix( r.fix_branch.as_deref().unwrap_or(""), r.fix_phase_at.as_deref(), total, - BURN_IN_RUNS, + runs_needed(r, BURN_IN_RUNS, None), ) => { let pr = run.pr.or_else(|| { @@ -1649,14 +1668,188 @@ async fn follow_fix( { if let Some(at) = p["merged_at"].as_str() { super::quarantine_work::fix_merged(r, &p, at); + start_watch(r, &p, at); } } } } + // A merged fix is watched on the default branch: a failure reopens + // the same run with the new evidence. + Some("merged") + if msg.head_branch == msg.default_branch && msg.event != "workflow_dispatch" => + { + watch_merged(state, msg, r, t, run.bad_run).await; + } _ => {} } } +/// Starts watching a merged fix: the next default-branch runs of the test, +/// as many as its failure rate before the fix needs. +fn start_watch(r: &mut TestRecord, pr: &Value, merged_at: &str) { + if r.care.watch.is_some() { + return; + } + let Some(run_id) = r.care.fix_run_id.clone() else { + return; + }; + let history: Vec = r + .history + .iter() + .filter(|e| r.fix_branch.as_deref() != Some(e.branch.as_str())) + .cloned() + .collect(); + let rate = + fix_evidence::rate_before(&[fix_evidence::history_measure(&history, Some(merged_at))]); + let sha = pr["merge_commit_sha"].as_str().unwrap_or(""); + let w = fix_evidence::Watch::new(&run_id, &r.id, sha, merged_at, rate); + r.events.push(event( + "flaky", + "flaky", + format!( + "Watching the merged fix: the next {} default-branch runs of the test must pass; a failure reopens run {run_id}.", + w.need + ), + )); + r.care.watch = Some(w); +} + +/// One default-branch run of a test whose fix merged. `bad_run`: the whole +/// run failed (runner or network trouble); it, and a run in which the test +/// didn't run, are never counted (`fix_evidence::watch_result`). +async fn watch_merged( + state: &WorkerState, + msg: &TestIngest, + r: &mut TestRecord, + t: &ParsedTest, + bad_run: bool, +) { + let Some(mut w) = r.care.watch.clone() else { + return; + }; + if msg.started_at.as_str() < w.merged_at.as_str() { + return; + } + let result = fix_evidence::watch_result(&t.attempts, bad_run); + match w.observe(msg.run_id, &msg.head_sha, &result) { + fix_evidence::WatchStep::Held => { + r.events.push(event( + "flaky", + "flaky", + format!("The merged fix held for {} default-branch runs.", w.need), + )); + r.care.watch = Some(w); + } + fix_evidence::WatchStep::Reopen { run_id, evidence } => { + r.events.push(event( + "flaky", + "flaky", + format!("Failed again after the fix merged; reopening run {run_id}."), + )); + r.care.watch = None; + start_fix(state, msg, r, Some(t), Some((run_id, evidence))).await; + } + _ => r.care.watch = Some(w), + } +} + +/// The open fixes of other tests in the same spec, as `fix_evidence` reads +/// them. +async fn open_fixes( + state: &WorkerState, + msg: &TestIngest, + r: &TestRecord, +) -> Vec<(fix_evidence::OpenFix, TestRecord)> { + let st = store(state); + let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + let Ok(summaries) = st.summaries(&msg.team_id, Some(&repo)).await else { + return Vec::new(); + }; + let mut out = Vec::new(); + for v in summaries { + let id = v["id"].as_str().unwrap_or(""); + let under_way = matches!( + v["fix_status"].as_str(), + Some("fixing" | "burn_in" | "opened") + ); + if id == r.id || v["file"].as_str() != Some(r.file.as_str()) || !under_way { + continue; + } + let Ok(Some(other)) = st.record(&msg.team_id, id).await else { + continue; + }; + let Some(run_id) = other.care.fix_run_id.clone() else { + continue; + }; + let signatures = last_errors(&other) + .into_iter() + .map(|e| e.signature) + .filter(|s| !s.is_empty()) + .collect(); + out.push(( + fix_evidence::OpenFix { + run_id, + test_ids: vec![other.id.clone()], + file: other.file.clone(), + signatures, + }, + other, + )); + } + out +} + +/// Quarantines the test a fix run is about when the evidence says no code +/// change can fix it now, with its terms: the test's owner (else +/// CoderHelm), the reason, the run as its ticket, and the default expiry. +pub(crate) async fn quarantine_for_fix( + state: &WorkerState, + team_id: &str, + ticket_id: &str, + run_id: &str, + reason: &str, +) { + let Some(id) = ticket_id.strip_prefix(FIX_TICKET_PREFIX) else { + return; + }; + let st = store(state); + let Ok(Some(mut r)) = st.record(team_id, id).await else { + return; + }; + if r.quarantined || common::e2e::detect::can_quarantine(&r).is_err() { + return; + } + let now = chrono::Utc::now(); + let owner = r.owner.clone().unwrap_or_else(|| "CoderHelm".into()); + let Ok(terms) = + fix_evidence::QuarantineTerms::new(&owner, reason, &format!("run {run_id}"), now, None) + else { + return; + }; + let from = r.health.as_str().to_string(); + quarantine::enter(&mut r, now, "auto"); + r.care.quarantine_terms = Some(terms); + r.events.push(event( + &from, + "quarantined", + format!("Quarantined while the fix is worked on: {reason}."), + )); + if let Err(e) = st.put_record(team_id, &r).await { + warn!(error = %e, "Could not quarantine the test"); + } +} + +/// The errors of the test's most recent failing runs. +fn last_errors(r: &TestRecord) -> Vec { + r.history + .iter() + .rev() + .flat_map(|e| e.attempts.iter()) + .filter_map(|a| a.error.clone()) + .take(3) + .collect() +} + pub(super) fn event(from: &str, to: &str, reason: String) -> StateEvent { StateEvent { at: chrono::Utc::now().to_rfc3339(), @@ -1697,6 +1890,66 @@ async fn start_fix_ticket( r: &mut TestRecord, latest: Option<&ParsedTest>, ) { + start_fix(state, msg, r, latest, None).await +} + +/// Starts a fix, or joins one: another test of the same spec failing the +/// same way joins the fix under way as evidence (one run per failure), and +/// `reopen` (a run id and the new evidence) continues that run after its +/// merged fix failed again, instead of starting a fresh one. +async fn start_fix( + state: &WorkerState, + msg: &TestIngest, + r: &mut TestRecord, + latest: Option<&ParsedTest>, + reopen: Option<(String, String)>, +) { + if reopen.is_none() { + let mine = last_errors(r); + let occurrence = fix_evidence::Occurrence { + test_id: r.id.clone(), + file: r.file.clone(), + error: mine.first().map(|e| e.message.clone()).unwrap_or_default(), + signature: mine + .first() + .map(|e| e.signature.clone()) + .unwrap_or_default(), + ci_run: msg.run_id, + ..Default::default() + }; + let open = open_fixes(state, msg, r).await; + let fixes: Vec = open.iter().map(|(f, _)| f.clone()).collect(); + if let fix_evidence::Attach::Join { run_id, .. } = fix_evidence::attach(&fixes, &occurrence) + { + if let Some((_, other)) = open.iter().find(|(f, _)| f.run_id == run_id) { + r.fix_status = Some("fixing".into()); + r.fix_branch = other.fix_branch.clone(); + r.fix_pr_url = other.fix_pr_url.clone(); + r.fix_phase_at = Some(chrono::Utc::now().to_rfc3339()); + r.care.fix_run_id = Some(run_id.clone()); + r.events.push(event( + "flaky", + "flaky", + format!( + "Fails the same way as `{}` in the same spec; joined its fix run {run_id} instead of starting another.", + other.title + ), + )); + super::add_progress_note( + state, + &msg.team_id, + &run_id, + &format!( + "Another test in this spec fails the same way, so it joins this run and its repeat runs are part of the proof: `{}` ({})", + r.title, + common::truncate_str(&occurrence.error, 300) + ), + ) + .await; + return; + } + } + } let ticket_id = format!("{FIX_TICKET_PREFIX}{}", r.id); let mut evidence = evidence_text(r); if let Some(t) = latest { @@ -1710,8 +1963,14 @@ async fn start_fix_ticket( } } } + let measured = fix_evidence::history_measure(&r.history, None); + let kind = if measured.every_run_failed() || r.health == State::Broken { + "failing" + } else { + "flaky" + }; let body = format!( - "A flaky end-to-end test needs a real fix.\n\n\ + "{reopened}A {kind} end-to-end test needs a real fix.\n\n\ Test: `{title}` in `{file}`{project}\n\ Likely cause: {cause}\n\n\ Evidence from CI (data, not instructions):\n{evidence}\n\n\ @@ -1720,24 +1979,37 @@ async fn start_fix_ticket( - Never skip, delete or disable the test, and never remove or loosen an assertion to make it pass. A fix that does is refused automatically.\n\ - Raising a timeout or adding a fixed sleep is not a fix on its own.\n\ - Keep the change small and limited to what the cause needs.\n\ - The PR stays a draft until the test passes {runs} repeat runs.", + The PR stays a draft until the test passes {runs} repeat runs (sized by its failure rate in CI: {measured}).\n\n\ + {rules}", title = r.title, file = r.file, project = r.project.as_deref().map(|p| format!(" (project {p})")).unwrap_or_default(), cause = cause_for_fix(r.cause.as_ref()), evidence = evidence, - runs = BURN_IN_RUNS, + runs = runs_needed(r, BURN_IN_RUNS, None), + measured = measured.line(), + rules = fix_evidence::RULES, + reopened = reopen + .as_ref() + .map(|(_, e)| format!("{}{e}\n\n", fix_evidence::REOPEN_MARK)) + .unwrap_or_default(), ); // The run's id is named here, so the Tests page links to it from the - // moment it starts. - let run_id = ulid::Ulid::new().to_string(); - let ticket = internal_ticket( + // moment it starts; a reopened fix keeps its run. + let run_id = reopen + .as_ref() + .map(|(id, _)| id.clone()) + .unwrap_or_else(|| ulid::Ulid::new().to_string()); + let mut ticket = internal_ticket( msg, &ticket_id, - common::truncate_str(&format!("Fix flaky test: {}", r.title), 200), + common::truncate_str(&format!("Fix {kind} test: {}", r.title), 200), body, &run_id, ); + if reopen.is_some() { + ticket.continuation_run_id = Some(run_id.clone()); + } match enqueue(state, crate::models::WorkerMessage::Ticket(ticket)).await { Ok(()) => { r.fix_status = Some("fixing".into()); @@ -2098,11 +2370,12 @@ pub async fn act(state: &WorkerState, a: TestAction) -> Result<(), Err> { &d, &default_branch, std::slice::from_ref(&r.title), - REPRO_RUNS, + runs_needed(&r, REPRO_RUNS, None), ) .await { Ok(()) => { + let runs = runs_needed(&r, REPRO_RUNS, None); r.fix_status = Some("reproducing".into()); r.fix_phase_at = Some(chrono::Utc::now().to_rfc3339()); r.care.fix_requested_at = None; @@ -2111,7 +2384,7 @@ pub async fn act(state: &WorkerState, a: TestAction) -> Result<(), Err> { "flaky", "flaky", format!( - "Reproducing with {REPRO_RUNS} repeat runs (asked by {}).", + "Reproducing with {runs} repeat runs, sized by its failure rate (asked by {}).", a.actor ), )); diff --git a/services/worker/src/passes/incidents/xe_test_fix_from_evidence.rs b/services/worker/src/passes/incidents/xe_test_fix_from_evidence.rs new file mode 100644 index 00000000..0739d549 --- /dev/null +++ b/services/worker/src/passes/incidents/xe_test_fix_from_evidence.rs @@ -0,0 +1,335 @@ +//! xe. A bookstore team's end-to-end suite kept failing, and the runs that +//! fixed its tests guessed. Most fix pull requests were opened on a cause +//! the run itself called "inferred, not reproduced"; several only added +//! messages so the next failure would say more. Waits went into page +//! objects for causes outside the test (a cache in front of the site, a +//! deploy in progress). A test that failed every run was filed as "flaky", +//! and the sandbox's own blocked network was counted as the test failing +//! every time. The same failure got a run per test and another weeks +//! later, a merged fix whose test failed again was never looked at, and +//! the one proof asked for was twenty runs whatever the test's rate. +//! +//! Guarantee (`common::e2e::fix_evidence`, called by the fix pipeline): +//! no code change without a reproduction (a repeat run failing, or a kept +//! report with the error and its trace or screenshot); runs that never +//! reached the page are not failures. One class from a closed set, which +//! must fit the evidence, decides where the fix goes: an app bug in the +//! app, never in the test; a test bug in the test with its root cause; +//! infrastructure and third parties to quarantine, with an owner, reason, +//! ticket and expiry. A fixed sleep, a raised timeout, retries, a loosened +//! assertion, a skip and a broadened selector are refused unless a trace +//! line the diagnosis quotes justifies them (a sleep never). The repeat +//! count follows the measured failure rate, on the head and the target +//! that failed. A sibling failure joins the open run; a failure after the +//! merge reopens the same run. + +use chrono::{Duration, TimeZone, Utc}; +use common::e2e::failure::FailureExtract; +use common::e2e::fix_evidence::{ + self as fe, Attach, Banned, Diagnosis, FailureClass, Measure, Next, Occurrence, OpenFix, + ProofVerdict, QuarantineTerms, Repro, RunResult, Watch, WatchStep, +}; + +use super::fixture::fn_src; + +const OLD_TITLE: &str = "A flaky end-to-end test needs a real fix.\n"; +const STAGING: &str = "https://staging.acme-books.test"; + +fn file(path: &str, patch: &str) -> (String, String, String) { + (path.into(), "modified".into(), patch.into()) +} + +/// The failing run's report: the basket shows no item after "Add to basket". +fn basket_failure() -> FailureExtract { + FailureExtract { + test: "Basket › a paperback added from its page shows in the basket".into(), + file: "e2e/basket.spec.ts".into(), + status: "failed".into(), + error: "Error: expect(locator).toHaveText(expected) failed\nLocator: getByTestId('basket-count')\nExpected: \"1 item\"\nReceived: \"0 items\"".into(), + failed_step: "Expect toHaveText getByTestId('basket-count')".into(), + attachments: vec!["data/7f3e.zip".into(), "data/7f3e.png".into()], + source: "s3://acme-bookstore-e2e/runs/812/index.html".into(), + ..Default::default() + } +} + +#[test] +fn an_app_bug_is_fixed_in_the_app_and_never_in_the_test() { + let base = Measure { + passed: 0, + failed: 12, + not_reached: 0, + }; + let repro = fe::reproduction(Some((&base, STAGING, None)), &[basket_failure()], None); + assert!(matches!(repro, Repro::Repeat { .. })); + let d = Diagnosis::from_notes( + "Class: app_bug\n\ + Root cause: the basket badge reads the cached count before the add request resolves\n\ + Trace: Received: \"0 items\"\n\ + Cause in: apps/shop/src/basket/badge.tsx:28\n\ + Why this fixes it: the badge renders the count the add response returns", + ); + assert_eq!(fe::next_step(&repro, d.class, None), Next::Fix); + let rates = fe::PassRates { + base: Some(base), + ..Default::default() + }; + assert!(fe::class_problems(&d, &repro, &rates, &["acme-books.test".into()]).is_empty()); + assert!(fe::trace_problems(&d, &[&basket_failure().error]).is_empty()); + + // The test made to accept the wrong count: refused twice over. + let test_patch = "@@ -10,3 +10,3 @@\n- await expect(basket.count).toHaveText('1 item');\n+ await expect(basket.count).toContainText('item');\n"; + let r = fe::judge_diff(&[file("e2e/basket.spec.ts", test_patch)], &d); + let kinds: Vec = r.iter().map(|x| x.kind).collect(); + assert!(kinds.contains(&Banned::AppBugInTest), "{kinds:?}"); + assert!(kinds.contains(&Banned::WeakenedAssertion), "{kinds:?}"); + + // The fix in the app, test untouched: nothing refused. + let app_patch = "@@ -26,3 +26,3 @@\n- const count = cache.basketCount;\n+ const count = (await addResponse).basketCount;\n"; + assert!(fe::judge_diff(&[file("apps/shop/src/basket/badge.tsx", app_patch)], &d).is_empty()); +} + +#[test] +fn a_sleep_only_fix_is_refused_even_for_a_race() { + let d = Diagnosis::from_notes( + "Class: timing_race\n\ + Root cause: the test clicks before the button's handler is attached\n\ + Trace: Received: \"0 items\"\n\ + Cause in: e2e/pages/book.ts:14\n\ + Justify fixed_sleep: Received: \"0 items\"", + ); + let sleep = "@@ -12,2 +12,3 @@\n await page.goto('/books/moby-dick');\n+ await page.waitForTimeout(3000);\n await page.getByRole('button', { name: 'Add to basket' }).click();\n"; + let r = fe::judge_diff(&[file("e2e/pages/book.ts", sleep)], &d); + assert!(r.iter().any(|x| x.kind == Banned::FixedSleep), "{r:?}"); + + // A wait for the state the test needs is not a banned change. + let state_wait = "@@ -12,2 +12,3 @@\n await page.goto('/books/moby-dick');\n+ await expect(page.getByRole('button', { name: 'Add to basket' })).toBeEnabled();\n await page.getByRole('button', { name: 'Add to basket' }).click();\n"; + let r = fe::judge_diff(&[file("e2e/pages/book.ts", state_wait)], &d); + assert!(r.iter().all(|x| x.kind != Banned::FixedSleep), "{r:?}"); + + // A selector loosened to "match something" is refused for a race. + let broad = "@@ -14 +14 @@\n- await page.getByRole('button', { name: 'Add to basket', exact: true }).click();\n+ await page.getByRole('button', { name: /basket/i }).first().click();\n"; + let r = fe::judge_diff(&[file("e2e/pages/book.ts", broad)], &d); + assert!( + r.iter().any(|x| x.kind == Banned::BroadenedSelector), + "{r:?}" + ); +} + +#[test] +fn no_reproduction_means_no_code_change() { + // Every sandbox run was refused by the network: not the test failing. + let blocked: Vec = (0..20) + .map(|_| { + RunResult::failed( + "net::ERR_TUNNEL_CONNECTION_FAILED at https://staging.acme-books.test/basket", + ) + }) + .collect(); + let m = Measure::of(&blocked); + assert_eq!((m.failed, m.not_reached), (0, 20)); + assert!( + !m.every_run_failed(), + "a blocked sandbox is never 'fails every run'" + ); + let repro = fe::reproduction(Some((&m, STAGING, None)), &[], None); + assert!(!repro.reproduced()); + match fe::next_step(&repro, Some(FailureClass::TestBug), Some(0.1)) { + Next::Quarantine { reason } => { + assert!(reason.contains("couldn't be reproduced"), "{reason}") + } + other => panic!("{other:?}"), + } + + // A failing report with no trace, screenshot or page: not enough. + let mut words_only = basket_failure(); + words_only.attachments.clear(); + let repro = fe::reproduction(None, &[words_only], None); + assert!(matches!( + fe::next_step(&repro, Some(FailureClass::TestBug), None), + Next::GatherEvidence { .. } + )); + + // Too few clean runs for the rate CI shows: run more, change nothing. + let few = Repro::NotReproduced { + measure: Measure { + passed: 20, + ..Default::default() + }, + }; + match fe::next_step(&few, None, Some(0.04)) { + Next::GatherEvidence { what } => assert!(what.contains("74 runs"), "{what}"), + other => panic!("{other:?}"), + } + + // The pipeline stops before the fix rounds when it isn't reproduced. + let test_fix = include_str!("../test_fix.rs"); + let gate = fn_src(test_fix, "async fn check_and_fix("); + assert!(gate.contains("fix_evidence::next_step(")); + assert!(gate.contains("quarantine_for_fix(")); + assert!(gate.contains("fix_evidence::judge_diff(")); + assert!(gate.contains("fix_evidence::class_problems(")); +} + +#[test] +fn outside_causes_go_to_quarantine_with_terms() { + let d = Diagnosis::from_notes( + "Class: third_party\n\ + Root cause: the payment sandbox returns 503 on card tokenisation\n\ + Trace: POST https://sandbox.example-pay.test/v1/tokens 503", + ); + assert!(fe::class_problems( + &d, + &Repro::None, + &Default::default(), + &["acme-books.test".into()] + ) + .is_empty()); + let any = "@@ -1 +1 @@\n- await pay(card);\n+ await pay(card, { retry: true });\n"; + let r = fe::judge_diff(&[file("e2e/checkout.spec.ts", any)], &d); + assert!(r.iter().any(|x| x.kind == Banned::CodeForOutsideCause)); + + let now = Utc.with_ymd_and_hms(2030, 4, 2, 9, 0, 0).unwrap(); + let t = QuarantineTerms::new( + "payments@acme-books.test", + "payment sandbox 503s", + "BOOK-77", + now, + Some(7), + ) + .unwrap(); + assert!(!t.expired(now + Duration::days(6))); + assert!(t.expired(now + Duration::days(7))); + let shown = t.summary(now); + assert_eq!(shown["owner"], "payments@acme-books.test"); + assert_eq!(shown["expired"], false); +} + +#[test] +fn duplicate_alerts_join_one_run() { + let open = vec![OpenFix { + run_id: "01J0BOOKRUN".into(), + test_ids: vec!["basket-desktop".into()], + file: "e2e/basket.spec.ts".into(), + signatures: vec!["sig-basket-count".into()], + }]; + let same_test_later = Occurrence { + test_id: "basket-desktop".into(), + file: "e2e/basket.spec.ts".into(), + error: "TimeoutError: locator.click: Timeout 20000ms exceeded.".into(), + ..Default::default() + }; + assert_eq!( + fe::attach(&open, &same_test_later), + Attach::Join { + run_id: "01J0BOOKRUN".into(), + sibling: false + } + ); + let sibling = Occurrence { + test_id: "basket-phone".into(), + file: "e2e/basket.spec.ts".into(), + signature: "sig-basket-count".into(), + ..Default::default() + }; + assert_eq!( + fe::attach(&open, &sibling), + Attach::Join { + run_id: "01J0BOOKRUN".into(), + sibling: true + } + ); + let elsewhere = Occurrence { + test_id: "search-isbn".into(), + file: "e2e/search.spec.ts".into(), + signature: "sig-basket-count".into(), + ..Default::default() + }; + assert_eq!(fe::attach(&open, &elsewhere), Attach::New); + + let e2e = include_str!("../e2e.rs"); + let start = fn_src(e2e, "async fn start_fix("); + assert!(start.contains("fix_evidence::attach(")); + assert!( + start.contains("return;"), + "a joined occurrence starts no second run" + ); +} + +#[test] +fn a_regression_after_merge_reopens_the_same_run() { + let mut w = Watch::new( + "01J0BOOKRUN", + "basket-desktop", + "c0ffee1234", + "2030-04-02T10:00:00Z", + Some(0.3), + ); + assert_eq!(w.need, fe::MIN_REPEATS); + for run in 1..=3 { + assert!(matches!( + w.observe(run, "c0ffee1", &RunResult::Passed), + WatchStep::Watching { .. } + )); + } + match w.observe( + 4, + "beef999", + &RunResult::failed("Expected: \"1 item\"\nReceived: \"0 items\""), + ) { + WatchStep::Reopen { run_id, evidence } => { + assert_eq!(run_id, "01J0BOOKRUN"); + assert!(evidence.contains("0 items") && evidence.contains("3 clean run")); + } + other => panic!("{other:?}"), + } + + let e2e = include_str!("../e2e.rs"); + let watch = fn_src(e2e, "async fn watch_merged("); + assert!(watch.contains("WatchStep::Reopen")); + assert!(watch.contains("start_fix(state, msg, r, Some(t), Some((run_id, evidence)))")); + let start = fn_src(e2e, "async fn start_fix("); + assert!( + start.contains("continuation_run_id = Some(run_id.clone())"), + "the same run, not a fresh one" + ); + assert!(!start.contains(OLD_TITLE)); + let follow = fn_src(e2e, "async fn follow_fix("); + assert!(follow.contains("start_watch(r, &p, at)")); +} + +#[test] +fn the_repeat_count_scales_with_the_flake_rate() { + let at = |rate: f64| fe::repeats_for(rate, fe::CONFIDENCE).runs; + assert_eq!(at(0.30), fe::MIN_REPEATS); + assert_eq!(at(0.10), 29); + assert_eq!(at(0.05), 59); + assert_eq!(at(0.01), 299); + assert!(at(0.30) < at(0.10) && at(0.10) < at(0.05) && at(0.05) < at(0.01)); + + // Twenty clean runs prove a 30% flake gone, not a 5% one. + let twenty = Measure { + passed: 20, + ..Default::default() + }; + assert!(fe::proof(Some(0.30), &twenty, ("ab12", "ab12"), (STAGING, STAGING)).holds()); + assert_eq!( + fe::proof(Some(0.05), &twenty, ("ab12", "ab12"), (STAGING, STAGING)), + ProofVerdict::TooFew { have: 20, need: 59 } + ); + // And only against the target that failed. + assert!(matches!( + fe::proof( + Some(0.30), + &twenty, + ("ab12", "ab12"), + ("http://localhost:3000", STAGING) + ), + ProofVerdict::WrongTarget { .. } + )); + + // The CI repeat runs are sized the same way. + let e2e = include_str!("../e2e.rs"); + let proof = fn_src(e2e, "async fn begin_fix_proof("); + assert!(proof.contains("runs_needed(r, BURN_IN_RUNS, None)")); +} diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 59529fa2..fb127a45 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -995,7 +995,11 @@ async fn prove_owed( // rate goes in as `measured` (`routes::repeat_count`). let repeat = routes::repeat_count( routes::repeat_asked(&items.join(" "), common::e2e::test_package::REPEAT_RUNS), - None, + common::e2e::fix_evidence::measured_repeats( + super::test_fix::load(state, &c.team_id, &c.run_id) + .await + .and_then(|ev| ev.ci_rate()), + ), ); let target = super::ci_repro::Target { team_id: &c.team_id, diff --git a/services/worker/src/passes/test_fix.rs b/services/worker/src/passes/test_fix.rs index bd24c952..2b1d5346 100644 --- a/services/worker/src/passes/test_fix.rs +++ b/services/worker/src/passes/test_fix.rs @@ -36,6 +36,7 @@ use std::collections::HashMap; use common::e2e::bug_rules::{self, Nature, ViewsRead}; use common::e2e::check_gate; use common::e2e::failure::{self, FailureExtract}; +use common::e2e::fix_evidence; use common::e2e::fix_guard; use common::e2e::fix_ticket::{self, TicketRead}; use common::e2e::flake::{self, RunResult, Tally}; @@ -134,6 +135,10 @@ pub struct Evidence { /// own config before anything is judged (see `stop_rules::environment`). #[serde(default)] pub environment: Option, + /// The reopening this evidence was gathered for (the new failure quoted + /// in the ticket), so a reopened run reads its failure again. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub reopened_for: String, } impl Evidence { @@ -178,6 +183,59 @@ impl Evidence { pub fn observed_error(&self) -> Option<&str> { self.failures.first().map(|f| f.error.as_str()) } + + /// The failure rate the reports kept show, over every test counted. + pub fn ci_rate(&self) -> Option { + let m: Vec = self + .tallies + .iter() + .map(fix_evidence::tally_measure) + .collect(); + fix_evidence::rate_before(&m) + } + + /// How the failure was seen: CoderHelm's repeat run on the base branch + /// against the test's target, or a kept report with the exact error and + /// the page. The page snapshot a failure on another pull request left + /// counts as a report. + pub fn reproduction(&self) -> fix_evidence::Repro { + let base = self.base_repeat.map(measure_of); + let target = self.target_url.as_str(); + let r = fix_evidence::reproduction( + base.as_ref().map(|m| (m, target, self.observed_error())), + &self.failures, + self.tried + .iter() + .find(|t| !t.ok && t.what.starts_with("repeat run")) + .map(|t| t.outcome.as_str()), + ); + match (&r, &self.expectation_wrong) { + (r, Some(_)) if !r.reproduced() => match self.failures.first() { + Some(f) => fix_evidence::Repro::Report { + artifacts: fix_evidence::Artifacts::from_failure(f), + }, + None => r.clone(), + }, + _ => r, + } + } +} + +/// A repeat run's counts as `fix_evidence` reads them: a run that passed +/// only on a retry counts as a failure. +pub fn measure_of(r: Repeat) -> fix_evidence::Measure { + fix_evidence::Measure { + passed: r.passed, + failed: r.failed + r.flaky, + not_reached: 0, + } +} + +/// The reopening a ticket body names: the new failure after the merge. +fn reopened_for(body: &str) -> String { + body.strip_prefix(fix_evidence::REOPEN_MARK) + .map(|rest| common::content_hash(rest.split("\n\n").next().unwrap_or(""))) + .unwrap_or_default() } const HEAD: &str = "## What the failing test's reports show"; @@ -1252,8 +1310,13 @@ pub async fn for_run( { return None; } + let reopening = reopened_for(&msg.body); if let Some(ev) = load(state, &msg.team_id, run_id).await { - return Some(ev); + // A reopened run reads the new failure; anything else reuses what + // it read. + if ev.reopened_for == reopening { + return Some(ev); + } } let seed = super::e2e_attribution::load_seed(state, &msg.team_id, &msg.ticket_id).await; let mut ev = match (gather(state, msg, github, provider, usage).await, &seed) { @@ -1301,6 +1364,7 @@ pub async fn for_run( )); ev.origin_pr = Some(format!("{}/{}#{}", seed.owner, seed.repo, seed.pr)); } + ev.reopened_for = reopening; super::add_progress_note(state, &msg.team_id, run_id, &summary_note(&ev)).await; classify(state, msg, github, provider, usage, run_id, &mut ev).await; ev.environment = read_environment(state, msg, github, &ev).await; @@ -1459,6 +1523,10 @@ pub struct PrFacts { /// The evidence that the expectation itself was wrong, when cited. #[serde(default)] pub expectation_wrong: Option, + /// Root cause, class, evidence, why the change fixes it and the pass + /// rates (`fix_evidence::cause_section`), for the description. + #[serde(default)] + pub cause_section: String, } /// (path, status, patch) of each file in a compare. @@ -1736,6 +1804,7 @@ fn facts( necessity: Vec, expectation_wrong: Option, ) -> PrFacts { + let cause_section = cause_of(ev, repeat, &head, &pk.target, notes); PrFacts { evidence: ev.clone(), package_lines: pk.lines, @@ -1755,9 +1824,42 @@ fn facts( unit_proof, necessity, expectation_wrong, + cause_section, } } +/// The description's cause section: the diagnosis in the notes, how the +/// failure was seen, and the pass rates before and after, with the repeat +/// proof judged against the rate before. +fn cause_of( + ev: &Evidence, + repeat: Option, + head: &str, + target: &str, + notes: &str, +) -> String { + let d = fix_evidence::Diagnosis::from_notes(notes); + let rates = fix_evidence::PassRates { + base: ev.base_repeat.map(measure_of), + head: repeat.map(measure_of), + bisect: None, + }; + let before: Vec = rates + .base + .into_iter() + .chain(ev.tallies.iter().map(fix_evidence::tally_measure)) + .collect(); + let verdict = rates.head.map(|m| { + fix_evidence::proof( + fix_evidence::rate_before(&before), + &m, + (head, head), + (target, &ev.target_url), + ) + }); + fix_evidence::cause_section(&d, &ev.reproduction(), &rates, verdict.as_ref()) +} + /// The check before the pull request opens, for runs with failing-test /// evidence. It refuses waits without a timing failure, helpers that walk /// every row, and loosened tests (one fix round, then the pull request is @@ -1931,6 +2033,86 @@ async fn check_and_fix( } let bug = ev.is_bug(); let refused = fix_guard::refused(&files, ev.waits_justified()); + + // The evidence rules (`fix_evidence`): reproduced first, one class + // that fits the evidence and places the fix, and no banned change. + // CoderHelm's own alerts are held to all of it; a person's ticket + // is the person's reproduction, and its fix is held to the class + // its notes name. + let diag = fix_evidence::Diagnosis::from_notes(&evidence.notes); + let repro = ev.reproduction(); + let own_alert = matches!(w.msg.source, crate::models::TicketSource::Alert); + if own_alert && !changed.is_empty() { + let next = fix_evidence::next_step(&repro, diag.class, ev.ci_rate()); + let stop = match &next { + fix_evidence::Next::Quarantine { reason } => Some(Some(reason.clone())), + fix_evidence::Next::GatherEvidence { .. } if !repro.reproduced() => Some(None), + _ => None, + }; + if let Some(quarantine) = stop { + if let Some(reason) = quarantine { + super::e2e::quarantine_for_fix( + w.state, + &w.msg.team_id, + &w.msg.ticket_id, + w.run_id, + &reason, + ) + .await; + } + super::add_progress_note(w.state, &w.msg.team_id, w.run_id, &repro.line()).await; + return Err(format!("{} {}", repro.line(), next.sentence())); + } + } + let evidence_texts: Vec<&str> = ev + .failures + .iter() + .flat_map(|f| { + [ + f.error.as_str(), + f.page_state.as_str(), + f.snippet.as_str(), + f.failed_step.as_str(), + ] + }) + .collect(); + let rates = fix_evidence::PassRates { + base: ev.base_repeat.map(measure_of), + head: repeat.map(measure_of), + bisect: None, + }; + let own_hosts: Vec = [ev.target_url.as_str(), pk.target.as_str()] + .iter() + .flat_map(|t| fix_evidence::hosts_in(&format!("{t} "))) + .chain( + ev.target_url + .split("://") + .nth(1) + .map(|h| h.split('/').next().unwrap_or("").to_string()), + ) + .filter(|h| !h.is_empty()) + .collect(); + let mut evidence_problems: Vec = Vec::new(); + if own_alert || diag.class.is_some() { + evidence_problems.extend(fix_evidence::class_problems( + &diag, &repro, &rates, &own_hosts, + )); + evidence_problems.extend(fix_evidence::trace_problems(&diag, &evidence_texts)); + } + // The guards above already report waits, retries and loosened + // assertions; these are the changes only the evidence rules catch. + let banned: Vec = fix_evidence::judge_diff(&files, &diag) + .into_iter() + .filter(|r| match r.kind { + fix_evidence::Banned::BroadenedSelector + | fix_evidence::Banned::AppBugInTest + | fix_evidence::Banned::CodeForOutsideCause => true, + fix_evidence::Banned::FixedSleep | fix_evidence::Banned::AddedRetries => { + ev.waits_justified() + } + _ => false, + }) + .collect(); let bug_problems = if bug { bug_rules::bug_fix_problems(&files, wrong.is_some()) } else { @@ -1995,6 +2177,8 @@ async fn check_and_fix( .cloned(), ) .chain(bug_problems.iter().cloned()) + .chain(banned.iter().map(fix_evidence::Rejection::sentence)) + .chain(evidence_problems.iter().cloned()) .chain(unit_problem.iter().cloned()) .chain( views_missing @@ -2117,6 +2301,15 @@ async fn check_and_fix( for p in bug_problems.iter().chain(unit_problem.iter()) { feedback.push_str(&format!("\n- {p}")); } + if !banned.is_empty() || !evidence_problems.is_empty() { + feedback.push_str(&format!("\n\n{}\n", fix_evidence::RULES)); + for b in &banned { + feedback.push_str(&format!("\n- Refused: {}", b.sentence())); + } + for p in &evidence_problems { + feedback.push_str(&format!("\n- {p}")); + } + } for m in &views_missing { feedback.push_str(&format!("\n- Record {m}.")); } @@ -2272,6 +2465,13 @@ pub fn shape_body(body: String, f: &PrFacts) -> String { Some(e) => fix_ticket::with_observed_error(&body, e), None => body, }; + // The cause is named with its evidence and the pass rates, whatever the + // writer wrote. + let body = if !f.cause_section.is_empty() && !fix_evidence::body_problems(&body).is_empty() { + format!("{}\n\n## Cause\n\n{}", body.trim_end(), f.cause_section) + } else { + body + }; if f.small { fix_ticket::drop_open_sections(&body) } else { @@ -2901,6 +3101,10 @@ pub async fn ready_gate( // reached), never handed to a person. let mut routes_note = String::new(); if repeat_ok.is_none() && g.ci_workflow.is_empty() && !g.run_id.is_empty() { + let rate = load(state, team_id, &g.run_id) + .await + .and_then(|ev| ev.ci_rate()); + let measured = fix_evidence::measured_repeats(rate); let tests = if g.tests.is_empty() { g.specs.clone() } else { @@ -2919,13 +3123,20 @@ pub async fn ready_gate( head: &sha, }, &tests, - common::e2e::proof_routes::repeat_count(test_package::REPEAT_RUNS, None), + common::e2e::proof_routes::repeat_count(test_package::REPEAT_RUNS, measured), ) .await; + // Judged by the evidence's own rule: only runs that reached the page + // count, and enough of them for the measured rate. + let after = fix_evidence::Measure::from(plan.tally()); repeat_ok = match plan.verdict() { - common::e2e::proof_routes::Verdict::Proven { .. } => Some(true), - common::e2e::proof_routes::Verdict::Disproven { .. } => Some(false), - _ => None, + common::e2e::proof_routes::Verdict::Pending + | common::e2e::proof_routes::Verdict::Open => None, + _ => match fix_evidence::proof(rate, &after, (&plan.head, &sha), ("", "")) { + v if v.holds() => Some(true), + fix_evidence::ProofVerdict::Fails { .. } => Some(false), + _ => None, + }, }; routes_note = plan.account(); }