diff --git a/docs/api/openapi.json b/docs/api/openapi.json index b78ed2bd4..c6cfac554 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -3838,6 +3838,17 @@ "null" ] }, + "merge_standing": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunMergeStanding", + "description": "Where the run's pull request stands on its way to merge, in the one\nreason that is true now (`common::merge_standing`): what holds it,\nwhat happens next, whether a person has to act and, when a setting\ndecides it, where that setting is. Null until the worker has looked\nat the pull request." + } + ] + }, "outside_change_report": { "description": "The report written when (part of) the fix is a change outside the code.", "examples": [ @@ -4641,6 +4652,56 @@ ], "type": "object" }, + "RunMergeStanding": { + "description": "Where a run's pull request stands on its way to merge.", + "properties": { + "code": { + "description": "Stable code: `merged`, `closed`, `reviewing`, `fixing_review`,\n`review_changes_requested`, `checks_running`, `checks_failing`,\n`conflict`, `draft`, `auto_merge_off`, `needs_person_approval`,\n`repo_requires_person_review` or `merging`.", + "examples": [ + "auto_merge_off" + ], + "type": "string" + }, + "link": { + "description": "Where the rule is set, when a setting decides it: a dashboard path\nor a GitHub URL. Null otherwise.", + "examples": [ + "/reviewer/config" + ], + "type": [ + "string", + "null" + ] + }, + "needs_person": { + "description": "A person has to act for the merge to happen.", + "examples": [ + true + ], + "type": "boolean" + }, + "next": { + "description": "What happens next, one sentence.", + "examples": [ + "Merge it, or turn auto-merge on and CoderHelm merges approved pull requests itself." + ], + "type": "string" + }, + "text": { + "description": "What is true now, one sentence.", + "examples": [ + "Auto-merge is off for this repo, so CoderHelm leaves the merge to your team." + ], + "type": "string" + } + }, + "required": [ + "code", + "text", + "next", + "needs_person" + ], + "type": "object" + }, "RunNote": { "description": "A note the run wrote while it worked.", "properties": { diff --git a/docs/incidents.md b/docs/incidents.md index fd64dcd99..22fd22104 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -62,6 +62,9 @@ pipeline still calls it there. | ae. `ae_budget_rounds` | Two loops of fix rounds still stopped on their own budget after the supervisor took every other ending. At eight automatic pushes the CI-only rounds on a finished run's pull request marked it ready, completed the run with its checks red and said a comment naming a change would start the next round, even while each round turned another red check green; at two rounds the self-review on CoderHelm's own pull request said the same and left its findings holding the draft, even while each round closed one. | Both loops follow `supervisor::next_round`: rounds go on while they make progress (checks that were red turn green, findings close), past the cap up to twice it and below the spend ceiling; a round without progress changes approach (one item, a fresh context with small edits, a re-split, the strongest model). When the rounds end, the findings left move to "Deferred" with the reason and stop holding the draft, and the run finishes; red checks are reverted to the last green head and deferred, or, when nothing can come out, the run fails with what fails and why. No message asks for a comment to go on: the phrases are on the `ownership` hand-off list. | | af. `af_lockfiles_out_of_sync` | A security update's pull request changed three `package.json` files (a pnpm workspace root and two npm packages with their own lockfiles) and none of the lockfiles, so every CI job failed at its frozen install. A retry planned its bumps by rule, then handed the red pull request to a model instead of building the plan. The model changed nothing; landing "nothing" removed the round's work branch, so the next attempt wrote to a branch that was gone (every write a 404, a hand edit of a lockfile among them). The round was called unfinished and the run ended failed after one attempt of three, with the same vague sentence twice. | A lockfile out of sync with its manifest is repaired by code before any model round, for any ticket and every package manager CoderHelm writes lockfiles for: each manager writes its own lockfile in the sandbox (with another mode and the LTS Node as fallbacks), one commit, and one that can't be written never hides the others. Any run that changes a manifest gets its lockfile written before the pull request opens. A retry of a dependency fix rebuilds its change from its plan on the same branch. A model's write to a lockfile is refused and pointed to the regenerate tool. Every attempt of a CI fix round opens its work branch first; a fault inside the round (no work branch, a compare or push GitHub refuses, a sandbox failure, anything else) is classified and has a way around it, and the catch-all runs the round again from a clean state, then once in a fresh step, before the supervisor's ending is asked. An attempt that changed nothing is followed by the repairs by code, then fresh evidence, then the strongest model. A run about to complete with red checks goes back to its CI fix round first, and an ending for red checks names the recorded cause, once. | | ag. `ag_red_ci_ships_what_passes` | Three ways were left for a run to end badly over red checks or a refused landing. A dependency fix whose CI stayed red was taken apart by planned task (one task per lockfile, so a lockfile went back without its manifest), and after three reverts the run ended failed with bumps left in that passed on their own. A run stopped after its work opened its pull request with manifests changed and lockfiles unwritten, and waited for CI to fail first. A review fix or feedback round whose finished work GitHub refused to land was recorded as unfinished at once. | Red checks after every fix take out only what breaks them. A dependency fix takes out its newest commit of verified bumps, defers those bumps with what CI printed, holds their findings out of later bundles and keeps the commits before it, again while CI stays red, never emptying the pull request. Any other run is taken apart task by task (up to eight reverts) down to the part that passes; what ships is green with the rest under "Deferred". A stopped run's lockfiles are written by their package managers before its pull request opens, and one that can't be written is named without stopping it. Every kind of fix round takes one classified decision about a fault (`round::plan_for_fault`): while it may continue it runs again in a fresh step, keeping its work when only the landing failed and starting from the pull request's head otherwise. | +| ba. `ba_verdict_on_old_commit` | A run finished as Done with its pull request ready while its own reviewer stood at "Changes requested" on a commit older than the head, and the run page said a person was needed and that merging was the team's call. The last fix was pushed, and the wake-up that found CI green with no event to read completed the run through an ending that skips the review step, so the new head was never reviewed. | Every completion and the sweep look at the finished run's pull request (`pr_watch`): no reviewer verdict on the head asks for the review of that commit, once per head; changes requested on the head get their fix round, and when the run's rounds are over the findings are deferred on the pull request with the reason. The run page names the one true reason the pull request is where it is (`common::merge_standing`) and names a person only for the team's own rule, with where it is set. | +| bb. `bb_flaky_not_broken` | An end-to-end workflow failed on a timeout in a spec the change never touched, as it had on unrelated pull requests that week. The run spent fix rounds editing the spec's timeout and a retry helper. Where the GitHub App may not write Actions, the re-run tried first was refused and the same fix round followed. | Before a CI fix round the failure is judged (`common::flaky_checks`): a failure naming a changed file is the change's; a check with a record of failing and then passing on one commit of other pull requests, naming no changed file, is re-run once and no code changes for it, and the pull request says which check, the evidence and what was done. A refused re-run is said with the permission by name and still changes no code. The record is per repository and learns only from a commit that failed and then passed unchanged. | +| bc. `bc_stays_through_merge_and_deploy` | Pull requests were left as they were after their runs finished: one conflicted after its base moved, one went red a day later on a commit status no event carries, and one merged by a person had its production deploy fail with nothing watching. | A finished run's pull request is looked at on completion and by the sweep: a conflict starts the conflict round once per base commit, red checks not red on the base go to the fix loop once per head, and a merge by anyone gets its merge commit's deploy watched once. A deploy of CoderHelm's own change that fails on checks passing before the merge gets a revert pull request with the failing jobs as evidence, ready for the team's approval and never merged by CoderHelm; files changed again since are never overwritten. | ## Adding a case diff --git a/services/common/src/flaky_checks.rs b/services/common/src/flaky_checks.rs new file mode 100644 index 000000000..a3886b693 --- /dev/null +++ b/services/common/src/flaky_checks.rs @@ -0,0 +1,642 @@ +//! Flaky or broken: whose failure a red check is. +//! +//! A red check on CoderHelm's pull request is not always the pull request's +//! doing. Before a fix round changes code for it, three things are read: +//! +//! - whether the check also fails on the base branch's head (red before the +//! change, see `resume::split_base_failures`); +//! - whether the repository has a record of the check failing and then +//! passing on the same commit of OTHER pull requests ([`Record`]); +//! - whether the failure names a file the pull request changed ([`touch`]). +//! +//! A failure that names a changed file is the change's, whatever the record +//! says. A failure of a check with a record of intermittent failures on +//! unrelated pull requests, which names no changed file, is re-run, not +//! "fixed": changing code that is not wrong makes the pull request worse and +//! the next reader's trust in it lower. The pull request says which check +//! was judged flaky and on what evidence ([`section`]). +//! +//! The record is one item per repository. It learns from what really +//! happened: a commit whose check failed and then passed on a re-run with +//! no change in between is the only observation that counts as flaky. + +use std::collections::BTreeMap; + +use chrono::{DateTime, Duration, Utc}; +use serde::{Deserialize, Serialize}; + +/// Sort key prefix of a repository's record (`FLAKY#owner/repo`), under the +/// team's partition of the settings table. +pub const PREFIX: &str = "FLAKY#"; + +/// Observations older than this say nothing about the check today. +pub const WINDOW_DAYS: i64 = 30; +/// Other pull requests that must have seen the check fail and then pass on +/// one commit before it counts as flaky for this one. +pub const MIN_OTHER_PRS: usize = 2; +/// Observations kept per check, newest last. +pub const MAX_OBSERVATIONS: usize = 20; +/// Checks kept per repository; the ones seen longest ago go first. +pub const MAX_CHECKS: usize = 200; + +/// The record's sort key for `owner/repo`. +pub fn sk(repo: &str) -> String { + format!("{PREFIX}{repo}") +} + +/// What was seen of one check on one commit. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + /// It failed, was re-run with no change, and passed. + PassedOnRerun, + /// It failed for the runner's or a service's reason (a DNS miss, a + /// runner that went away), read from its log. + Infra, +} + +/// One observation, with what a person needs to check it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Observation { + pub kind: Kind, + /// RFC 3339. + pub at: String, + pub pr: u64, + pub sha: String, + /// The line that says so (an infrastructure line), empty when none. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub line: String, +} + +/// A repository's flaky checks: observations by check name. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Record { + #[serde(default)] + pub checks: BTreeMap>, +} + +impl Record { + pub fn from_json(s: &str) -> Record { + serde_json::from_str(s).unwrap_or_default() + } + + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string()) + } + + /// Adds an observation. The same commit of the same pull request is one + /// observation however often it is reported (a webhook and a sweep). True + /// when the record changed. + pub fn observe(&mut self, check: &str, o: Observation) -> bool { + let check = check.trim(); + if check.is_empty() { + return false; + } + let list = self.checks.entry(check.to_string()).or_default(); + if list + .iter() + .any(|x| x.kind == o.kind && x.pr == o.pr && x.sha == o.sha) + { + return false; + } + list.push(o); + if list.len() > MAX_OBSERVATIONS { + let drop = list.len() - MAX_OBSERVATIONS; + list.drain(..drop); + } + while self.checks.len() > MAX_CHECKS { + let oldest = self + .checks + .iter() + .min_by_key(|(_, v)| v.last().map(|o| o.at.clone()).unwrap_or_default()) + .map(|(k, _)| k.clone()); + match oldest { + Some(k) => { + self.checks.remove(&k); + } + None => break, + } + } + true + } + + /// The check's observations inside the window on pull requests other + /// than `pr`, newest last. + pub fn elsewhere(&self, check: &str, pr: u64, now: DateTime) -> Vec<&Observation> { + let cut = now - Duration::days(WINDOW_DAYS); + self.checks + .get(check.trim()) + .map(|l| { + l.iter() + .filter(|o| o.pr != pr && o.kind == Kind::PassedOnRerun) + .filter(|o| { + DateTime::parse_from_rfc3339(&o.at) + .map(|t| t.with_timezone(&Utc) >= cut) + .unwrap_or(false) + }) + .collect() + }) + .unwrap_or_default() + } + + /// Whether the check has a record of intermittent failure on unrelated + /// pull requests: it failed and then passed on one commit of at least + /// [`MIN_OTHER_PRS`] other pull requests inside the window. + pub fn known_flaky(&self, check: &str, pr: u64, now: DateTime) -> bool { + let mut prs: Vec = self + .elsewhere(check, pr, now) + .iter() + .map(|o| o.pr) + .collect(); + prs.sort_unstable(); + prs.dedup(); + prs.len() >= MIN_OTHER_PRS + } +} + +/// What a failure's output says about the files the pull request changed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Touch { + /// It names these changed files: the change's own failure. + Changed(Vec), + /// It names files, none of them changed by the pull request. + Elsewhere(Vec), + /// It names no file. + Unknown, +} + +/// File extensions a failure's output names source files with. +const SOURCE_EXTS: &[&str] = &[ + "rs", "ts", "tsx", "js", "jsx", "mjs", "cjs", "py", "go", "rb", "java", "kt", "swift", "cs", + "php", "c", "cc", "cpp", "h", "hpp", "vue", "svelte", "scala", "ex", "exs", "tf", "sql", + "yaml", "yml", "json", "toml", "css", "scss", "html", "sh", +]; + +/// A token of a log line as a repository path, when it reads as one: +/// `src/a/b.test.ts:12:3`, `./src/a.py`, `/home/runner/work/app/app/src/a.go`. +fn path_in(token: &str) -> Option { + let t = token.trim_matches(|c: char| { + !(c.is_alphanumeric() || matches!(c, '/' | '.' | '_' | '-' | '@' | '[' | ']')) + }); + // `file.rs:12:3` and `file.py(12)`: the position goes. + let t = t.split([':', '(']).next().unwrap_or(t); + let t = t.trim_end_matches(['.', ',', ')', ']']); + let (stem, ext) = t.rsplit_once('.')?; + if stem.is_empty() || !SOURCE_EXTS.contains(&ext.to_ascii_lowercase().as_str()) { + return None; + } + if t.contains("://") || t.len() > 300 { + return None; + } + // A bare file name names nothing in particular; a path does. + if !t.contains('/') { + return None; + } + let t = t.trim_start_matches("./"); + // A runner's checkout prefix (`/home/runner/work/{repo}/{repo}/`). + let t = match t.split_once("/work/") { + Some((_, rest)) if t.starts_with('/') => { + let mut parts = rest.splitn(3, '/'); + match (parts.next(), parts.next(), parts.next()) { + (Some(a), Some(b), Some(path)) if a == b => path, + _ => rest, + } + } + _ => t, + }; + let t = t.trim_start_matches('/'); + (!t.is_empty() && !t.contains("node_modules/")).then(|| t.to_string()) +} + +/// The repository paths a failure's output names, in order, each once. +pub fn named_paths(logs: &str) -> Vec { + let mut out: Vec = Vec::new(); + for token in logs.split(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | '`' | '=')) { + if let Some(p) = path_in(token) { + if !out.contains(&p) { + out.push(p); + } + } + if out.len() >= 200 { + break; + } + } + out +} + +/// Whether a path a log names is the changed file `changed`: equal, or one +/// ends with the other at a directory boundary (a log printed relative to a +/// package directory, or with a build prefix). +fn same_file(named: &str, changed: &str) -> bool { + let ends = |long: &str, short: &str| { + long.ends_with(short) + && long[..long.len() - short.len()] + .chars() + .last() + .is_none_or(|c| c == '/') + }; + named == changed || ends(named, changed) || ends(changed, named) +} + +/// What the failure's output says about the pull request's changed files. +pub fn touch(logs: &str, changed: &[String]) -> Touch { + let named = named_paths(logs); + if named.is_empty() { + return Touch::Unknown; + } + let hit: Vec = changed + .iter() + .filter(|c| named.iter().any(|n| same_file(n, c))) + .cloned() + .collect(); + if hit.is_empty() { + Touch::Elsewhere(named.into_iter().take(5).collect()) + } else { + Touch::Changed(hit) + } +} + +/// Why a failing check is not the pull request's. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum NotOurs { + /// It fails on the base branch's head too. + RedOnBase, + /// The runner or a service failed, with the line that says so. + Infra(String), + /// It failed and then passed on one commit of these other pull requests + /// (`#pr at sha`), newest last. + Flaky(Vec), +} + +/// Whose failure each failing check is. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Judgement { + /// Checks the pull request has to fix. + pub ours: Vec, + /// Checks it did not cause, with why. + pub not_ours: Vec<(String, NotOurs)>, +} + +impl Judgement { + /// Nothing here is the pull request's to fix: re-run, don't change code. + pub fn none_ours(&self) -> bool { + self.ours.is_empty() && !self.not_ours.is_empty() + } +} + +/// Judges the failing checks of a pull request's head. `failing` is every +/// failing check, `on_base` those failing on the base branch's head too, +/// `touch` what the failure output says about the changed files, `infra` +/// the infrastructure line the output shows. +/// +/// A check failing on the base is the base's. For the rest: output that +/// names a changed file makes every one of them the pull request's. An +/// infrastructure line makes them the runner's. Otherwise a check is flaky +/// only with a record on unrelated pull requests; with none it is the pull +/// request's, since a failure that names no changed file can still be +/// caused by one. +pub fn judge( + failing: &[String], + on_base: &[String], + touch: &Touch, + infra: Option<&str>, + record: &Record, + pr: u64, + now: DateTime, +) -> Judgement { + let mut j = Judgement::default(); + for check in failing { + if on_base.contains(check) { + j.not_ours.push((check.clone(), NotOurs::RedOnBase)); + continue; + } + if matches!(touch, Touch::Changed(_)) { + j.ours.push(check.clone()); + continue; + } + if let Some(line) = infra { + j.not_ours + .push((check.clone(), NotOurs::Infra(line.to_string()))); + continue; + } + if record.known_flaky(check, pr, now) { + let seen = record + .elsewhere(check, pr, now) + .iter() + .map(|o| format!("#{} at `{}`", o.pr, short(&o.sha))) + .collect(); + j.not_ours.push((check.clone(), NotOurs::Flaky(seen))); + continue; + } + j.ours.push(check.clone()); + } + j +} + +fn short(sha: &str) -> &str { + sha.get(..7).unwrap_or(sha) +} + +/// What happened to the re-run of the checks judged not the pull request's. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Rerun { + /// The failed jobs were started again. + Started, + /// GitHub refused: the installation may not write Actions. + NoPermission, + /// Nothing to start again (a check outside GitHub Actions). + NotActions, +} + +/// Whether GitHub's refusal of a re-run is a missing permission (the App +/// has no Actions write on the repository), not a failure worth a retry. +pub fn rerun_refused_for_permission(error: &str) -> bool { + let e = error.to_ascii_lowercase(); + e.contains("resource not accessible by integration") + || (e.contains("403") && (e.contains("actions") || e.contains("must have admin rights"))) +} + +pub const START: &str = ""; +pub const END: &str = ""; + +/// The pull request's section saying which red checks CoderHelm judged not +/// caused by the change, the evidence for each, and what it did about it. +/// Empty when every failing check is the pull request's. +pub fn section(j: &Judgement, base: &str, rerun: &Rerun, touch: &Touch) -> String { + if j.not_ours.is_empty() { + return String::new(); + } + let mut lines: Vec = Vec::new(); + for (check, why) in &j.not_ours { + lines.push(match why { + NotOurs::RedOnBase => { + format!("* `{check}` also fails on the head of `{base}`: red before this change.") + } + NotOurs::Infra(line) => format!( + "* `{check}` failed on the runner or a service, not on the code: `{}`.", + line.replace('`', "'") + ), + NotOurs::Flaky(seen) => format!( + "* `{check}` has failed and then passed on the same commit of other pull \ + requests ({}).", + seen.join(", ") + ), + }); + } + if let Touch::Elsewhere(files) = touch { + lines.push(format!( + "* The failure names {}, which this pull request does not change.", + files + .iter() + .map(|f| format!("`{f}`")) + .collect::>() + .join(", ") + )); + } + let did = match rerun { + Rerun::Started if j.ours.is_empty() => { + "CoderHelm re-ran the failed jobs and changed no code for them." + } + Rerun::Started => { + "CoderHelm re-ran the failed jobs for these and fixes the others in code." + } + Rerun::NoPermission => { + "CoderHelm changed no code for them. It could not re-run them: its GitHub App has no \ + Actions write permission on this repository (Settings, GitHub App, Repository \ + permissions, Actions: Read and write)." + } + Rerun::NotActions => { + "CoderHelm changed no code for them. They run outside GitHub Actions, so it has no \ + way to start them again." + } + }; + format!( + "{START}\n**Red checks not caused by this change**\n{}\n\n{did}\n{END}", + lines.join("\n") + ) +} + +/// What the fix round is told when a check with a flaky record failed again +/// after its re-run: the record is evidence, the second failure is too. +pub fn fixer_note(j: &Judgement) -> String { + let flaky: Vec<&str> = j + .not_ours + .iter() + .filter(|(_, w)| matches!(w, NotOurs::Flaky(_))) + .map(|(c, _)| c.as_str()) + .collect(); + if flaky.is_empty() { + return String::new(); + } + format!( + "Note on {}: the repository's record shows it failing and then passing on one commit of \ + unrelated pull requests, and it failed here again after a re-run. Find what in THIS \ + change it depends on before changing anything; change only code the failure output \ + ties to this change, and never weaken, skip or delete the test.", + flaky.join(", ") + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn now() -> DateTime { + DateTime::parse_from_rfc3339("2026-03-10T12:00:00Z") + .unwrap() + .with_timezone(&Utc) + } + + fn seen(pr: u64, sha: &str, days_ago: i64) -> Observation { + Observation { + kind: Kind::PassedOnRerun, + at: (now() - Duration::days(days_ago)).to_rfc3339(), + pr, + sha: sha.to_string(), + line: String::new(), + } + } + + fn strings(v: &[&str]) -> Vec { + v.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn one_commit_is_one_observation() { + let mut r = Record::default(); + assert!(r.observe("e2e", seen(11, "aaaaaaa1", 1))); + assert!(!r.observe("e2e", seen(11, "aaaaaaa1", 0))); + assert_eq!(r.checks["e2e"].len(), 1); + assert!(!r.observe(" ", seen(11, "aaaaaaa1", 0))); + } + + #[test] + fn flaky_needs_other_pull_requests_inside_the_window() { + let mut r = Record::default(); + // This pull request's own history is not evidence about itself. + r.observe("e2e", seen(40, "s1", 1)); + r.observe("e2e", seen(40, "s2", 1)); + assert!(!r.known_flaky("e2e", 40, now())); + // One other pull request is not a record. + r.observe("e2e", seen(31, "s3", 2)); + assert!(!r.known_flaky("e2e", 40, now())); + // Old observations say nothing about today. + r.observe("e2e", seen(12, "s4", WINDOW_DAYS + 3)); + assert!(!r.known_flaky("e2e", 40, now())); + r.observe("e2e", seen(33, "s5", 5)); + assert!(r.known_flaky("e2e", 40, now())); + // An infrastructure failure is not a flaky test. + let mut infra = Record::default(); + for pr in [1, 2, 3] { + infra.observe( + "build", + Observation { + kind: Kind::Infra, + ..seen(pr, "s", 1) + }, + ); + } + assert!(!infra.known_flaky("build", 40, now())); + } + + #[test] + fn the_record_stays_bounded_and_round_trips() { + let mut r = Record::default(); + for i in 0..(MAX_OBSERVATIONS as u64 + 5) { + r.observe("e2e", seen(i, "s", 1)); + } + assert_eq!(r.checks["e2e"].len(), MAX_OBSERVATIONS); + assert_eq!(r.checks["e2e"][0].pr, 5); + assert_eq!(Record::from_json(&r.to_json()), r); + assert_eq!(Record::from_json("not json"), Record::default()); + } + + #[test] + fn paths_are_read_from_failure_output() { + let logs = "FAIL apps/web/src/cart/total.test.ts:41:7\n\ + at /home/runner/work/shop/shop/apps/web/src/cart/total.ts:12:3\n\ + error[E0308]: mismatched types --> services/api/src/price.rs:88:9\n\ + see https://example.com/docs/a.html and node_modules/x/y.js and total.ts"; + assert_eq!( + named_paths(logs), + strings(&[ + "apps/web/src/cart/total.test.ts", + "apps/web/src/cart/total.ts", + "services/api/src/price.rs" + ]) + ); + } + + #[test] + fn touch_matches_changed_files_at_directory_boundaries() { + let changed = strings(&["apps/web/src/cart/total.ts"]); + // A log printed relative to the package directory. + assert_eq!( + touch("FAIL src/cart/total.ts:3:1", &changed), + Touch::Changed(changed.clone()) + ); + // A file whose name merely ends alike is another file. + assert_eq!( + touch("FAIL src/cart/subtotal.ts:3:1", &changed), + Touch::Elsewhere(strings(&["src/cart/subtotal.ts"])) + ); + assert_eq!( + touch("Timeout of 30000ms exceeded", &changed), + Touch::Unknown + ); + } + + fn flaky_record() -> Record { + let mut r = Record::default(); + r.observe("e2e", seen(31, "abcdef1234", 2)); + r.observe("e2e", seen(33, "1234abcdef", 5)); + r + } + + #[test] + fn a_failure_naming_a_changed_file_is_the_changes_whatever_the_record_says() { + let j = judge( + &strings(&["e2e"]), + &[], + &Touch::Changed(strings(&["src/a.ts"])), + Some("ECONNRESET"), + &flaky_record(), + 40, + now(), + ); + assert_eq!(j.ours, strings(&["e2e"])); + assert!(!j.none_ours()); + } + + #[test] + fn a_known_flaky_check_that_names_no_changed_file_is_not_fixed_in_code() { + let j = judge( + &strings(&["e2e", "unit"]), + &strings(&["lint"]), + &Touch::Elsewhere(strings(&["tests/checkout.spec.ts"])), + None, + &flaky_record(), + 40, + now(), + ); + // `unit` has no record: a failure that names no changed file can + // still be caused by one. + assert_eq!(j.ours, strings(&["unit"])); + assert_eq!( + j.not_ours, + vec![( + "e2e".to_string(), + NotOurs::Flaky(strings(&["#31 at `abcdef1`", "#33 at `1234abc`"])) + )] + ); + let only = judge( + &strings(&["e2e", "lint"]), + &strings(&["lint"]), + &Touch::Unknown, + None, + &flaky_record(), + 40, + now(), + ); + assert!(only.none_ours()); + assert_eq!(only.not_ours[1], ("lint".to_string(), NotOurs::RedOnBase)); + } + + #[test] + fn the_section_names_each_check_its_evidence_and_what_was_done() { + let j = judge( + &strings(&["e2e", "lint"]), + &strings(&["lint"]), + &Touch::Elsewhere(strings(&["tests/checkout.spec.ts"])), + None, + &flaky_record(), + 40, + now(), + ); + let touch = Touch::Elsewhere(strings(&["tests/checkout.spec.ts"])); + let s = section(&j, "main", &Rerun::Started, &touch); + assert!(s.starts_with(START) && s.ends_with(END)); + assert!(s.contains("`e2e` has failed and then passed on the same commit of other pull requests (#31 at `abcdef1`, #33 at `1234abc`)")); + assert!(s.contains("`lint` also fails on the head of `main`")); + assert!(s.contains("`tests/checkout.spec.ts`, which this pull request does not change")); + assert!(s.contains("re-ran the failed jobs and changed no code")); + let refused = section(&j, "main", &Rerun::NoPermission, &touch); + assert!(refused.contains("no Actions write permission")); + assert!(refused.contains("changed no code")); + assert_eq!( + section(&Judgement::default(), "main", &Rerun::Started, &touch), + "" + ); + } + + #[test] + fn a_refused_rerun_is_told_from_a_failed_one() { + assert!(rerun_refused_for_permission( + "GitHub API 403: {\"message\":\"Resource not accessible by integration\"}" + )); + assert!(!rerun_refused_for_permission("GitHub API 502: bad gateway")); + assert!(!rerun_refused_for_permission( + "GitHub API 409: workflow run is already running" + )); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 4b3e47c00..f6265e0bb 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -118,6 +118,9 @@ pub mod memory_meta; /// The auto-merge gate's per-PR record: keys and states (the worker runs the /// gate, the gateway re-arms it on GitHub events). pub mod merge_gate; +/// Where a finished run's pull request stands on its way to merge, in the +/// one reason that is true. +pub mod merge_standing; /// Every message on the worker queues: one enum the gateway and worker share. pub mod messages; /// Retrying model API calls on transient failures, classified by status. @@ -152,6 +155,9 @@ pub mod run_prs; // review_stats: time-ordered review records for analytics pub mod decision_log; pub mod deploy_stats; +/// Flaky or broken: whose failure a red check is, and the repository's +/// record of checks that failed and then passed on one commit. +pub mod flaky_checks; /// Run statuses; which ones a person set; closing and reopening a run. pub mod handback; /// Work CoderHelm started on its own pull request and hasn't landed, and diff --git a/services/common/src/merge_standing.rs b/services/common/src/merge_standing.rs new file mode 100644 index 000000000..e72a2efa8 --- /dev/null +++ b/services/common/src/merge_standing.rs @@ -0,0 +1,395 @@ +//! Where a finished run's pull request stands on its way to merge, in the +//! one reason that is true. +//! +//! A run page once said "Needs a person" and "merging is your team's call" +//! for every finished run with an open pull request, whatever held the +//! merge: auto-merge being off, the repository asking for a person's +//! approval, CoderHelm's own review still asking for changes, or nothing at +//! all. A person is needed only for what only a person can give, and then +//! the page says exactly which thing that is and where it is set. +//! +//! [`decide`] reads the facts in the order they hold the merge and returns +//! one [`Standing`]: its code (stable, for the dashboard and analytics), the +//! sentence shown, whether a person has to act, and the setting it comes +//! from when it comes from a setting. The worker writes it on the run +//! record ([`FIELD`]) whenever it looks at the pull request. + +use serde::{Deserialize, Serialize}; + +/// The run record's field holding the standing, as JSON. +pub const FIELD: &str = "merge_standing"; + +/// What the worker knows about the pull request and the repository's rules. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Facts { + pub merged: bool, + pub closed: bool, + pub draft: bool, + /// The pull request's head commit. + pub head: String, + /// CoderHelm's reviewer is on for the repository. + pub reviewer_on: bool, + /// CoderHelm's latest review verdict and the commit it is on. + pub own_verdict: Option<(String, String)>, + /// A fix round or a review of the head is queued or running. + pub working: bool, + /// Checks failing on the head (names), and whether any still runs. + pub failing: Vec, + pub checks_running: bool, + /// The pull request conflicts with its base. + pub conflict: bool, + /// The repository's auto-merge setting, and whether it asks for a + /// person's approval before CoderHelm merges. + pub auto_merge: bool, + pub require_human_approval: bool, + /// A person approved the head. + pub human_approved: bool, + /// GitHub reports the merge blocked by the branch's rules although the + /// checks are green (`mergeable_state` = `blocked`). + pub blocked_by_rules: bool, +} + +/// One standing, as shown. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Standing { + /// Stable code: `merged`, `closed`, `reviewing`, `fixing_review`, + /// `review_changes_requested`, `checks_running`, `checks_failing`, + /// `conflict`, `draft`, `auto_merge_off`, `needs_person_approval`, + /// `repo_requires_person_review`, `merging`. + pub code: String, + /// What is true now, one sentence. + pub text: String, + /// What happens next, one sentence. + pub next: String, + /// A person has to act for the merge to happen. + pub needs_person: bool, + /// Where the rule is set, when it is a setting (a dashboard path, or a + /// GitHub URL); empty otherwise. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub link: String, +} + +impl Standing { + fn new(code: &str, text: String, next: &str, needs_person: bool, link: String) -> Standing { + Standing { + code: code.to_string(), + text, + next: next.to_string(), + needs_person, + link, + } + } + + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_default() + } + + pub fn from_json(s: &str) -> Option { + serde_json::from_str(s).ok() + } +} + +fn short(sha: &str) -> &str { + sha.get(..7).unwrap_or(sha) +} + +/// The dashboard page where a repository's reviewer and auto-merge are set. +pub fn settings_path(_repo: &str) -> String { + "/reviewer/config".to_string() +} + +/// GitHub's page for a repository's branch rules. +pub fn branch_rules_url(repo: &str) -> String { + format!("https://github.com/{repo}/settings/branches") +} + +/// The standing of `repo`'s pull request, from the facts, first holder +/// first. CoderHelm's own work (a review of the head, a fix round, checks) +/// never asks for a person; only the team's own rules do. +pub fn decide(repo: &str, f: &Facts) -> Standing { + let none = String::new; + if f.merged { + return Standing::new( + "merged", + "The pull request is merged.".into(), + "CoderHelm watches the deploy of the merge commit.", + false, + none(), + ); + } + if f.closed { + return Standing::new( + "closed", + "The pull request was closed without merging.".into(), + "Nothing further runs on it.", + false, + none(), + ); + } + if f.conflict { + return Standing::new( + "conflict", + "The pull request conflicts with its base branch.".into(), + "CoderHelm merges the base branch in and resolves the conflict.", + false, + none(), + ); + } + if !f.failing.is_empty() && !f.checks_running { + return Standing::new( + "checks_failing", + format!( + "Checks fail on `{}`: {}.", + short(&f.head), + f.failing + .iter() + .take(4) + .cloned() + .collect::>() + .join(", ") + ), + "CoderHelm fixes them, or says on the pull request why they are not this change's.", + false, + none(), + ); + } + if f.reviewer_on { + match &f.own_verdict { + Some((verdict, sha)) if sha == &f.head && verdict == "APPROVE" => {} + Some((verdict, sha)) if sha == &f.head && verdict == "REQUEST_CHANGES" => { + return if f.working { + Standing::new( + "fixing_review", + format!( + "CoderHelm's review asked for changes on `{}` and a fix round is \ + taking them.", + short(sha) + ), + "The fix is pushed and the new head is reviewed.", + false, + none(), + ) + } else { + Standing::new( + "review_changes_requested", + format!( + "CoderHelm's review asks for changes on `{}`; what it could not fix \ + is listed as deferred on the pull request.", + short(sha) + ), + "CoderHelm does not merge over its own review; the deferred findings \ + say what each needs.", + false, + none(), + ) + }; + } + // No verdict, or one on an older commit: never shown as the + // verdict on this head. + other => { + let was = other + .as_ref() + .map(|(_, sha)| format!(" (its last review was of `{}`)", short(sha))) + .unwrap_or_default(); + return Standing::new( + "reviewing", + format!("CoderHelm is reviewing the head `{}`{was}.", short(&f.head)), + "Its verdict on this commit decides what follows: a fix round, or the merge.", + false, + none(), + ); + } + } + } + if f.checks_running { + return Standing::new( + "checks_running", + format!("Checks are still running on `{}`.", short(&f.head)), + "CoderHelm reads their result when they finish.", + false, + none(), + ); + } + if f.draft { + return Standing::new( + "draft", + "The pull request is still a draft; its description says why at the top.".into(), + "CoderHelm marks it ready once what holds it is settled.", + false, + none(), + ); + } + if !f.auto_merge { + return Standing::new( + "auto_merge_off", + "Auto-merge is off for this repo, so CoderHelm leaves the merge to your team.".into(), + "Merge it, or turn auto-merge on and CoderHelm merges approved pull requests itself.", + true, + settings_path(repo), + ); + } + if f.require_human_approval && !f.human_approved { + return Standing::new( + "needs_person_approval", + "This repo's auto-merge setting requires an approving review from a person before \ + CoderHelm merges." + .into(), + "Once a person approves this commit, CoderHelm merges it and follows the deploy.", + true, + settings_path(repo), + ); + } + if f.blocked_by_rules { + return Standing::new( + "repo_requires_person_review", + "Your repo's branch rules block the merge: they require an approving review from a \ + person (or another rule GitHub enforces on this branch)." + .into(), + "Once the branch's rules are met, CoderHelm merges it and follows the deploy.", + true, + branch_rules_url(repo), + ); + } + Standing::new( + "merging", + "Approved, checks green, and the repo's rules allow it: CoderHelm merges it.".into(), + "After the merge CoderHelm watches the deploy of the merge commit.", + false, + none(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + const HEAD: &str = "9f8e7d6c5b4a39281706f5e4d3c2b1a098765432"; + const OLD: &str = "1111111aaaaaaa2222222bbbbbbb3333333ccccc"; + + /// Everything in place for CoderHelm to merge on its own. + fn clear() -> Facts { + Facts { + head: HEAD.into(), + reviewer_on: true, + own_verdict: Some(("APPROVE".into(), HEAD.into())), + auto_merge: true, + require_human_approval: false, + ..Default::default() + } + } + + #[test] + fn approved_green_and_allowed_merges_with_nobody_asked() { + let s = decide("acme/shop", &clear()); + assert_eq!(s.code, "merging"); + assert!(!s.needs_person); + assert!(s.next.contains("watches the deploy")); + } + + #[test] + fn a_verdict_on_an_older_commit_is_never_the_standing_verdict() { + let mut f = clear(); + f.own_verdict = Some(("REQUEST_CHANGES".into(), OLD.into())); + let s = decide("acme/shop", &f); + assert_eq!(s.code, "reviewing"); + assert!(!s.needs_person, "a review of the head is CoderHelm's work"); + assert!( + s.text.contains("`9f8e7d6`") && s.text.contains("its last review was of `1111111`") + ); + assert!(!s.text.to_lowercase().contains("changes requested")); + f.own_verdict = None; + assert_eq!(decide("acme/shop", &f).code, "reviewing"); + } + + #[test] + fn changes_requested_on_the_head_is_coderhelms_to_fix() { + let mut f = clear(); + f.own_verdict = Some(("REQUEST_CHANGES".into(), HEAD.into())); + f.working = true; + let s = decide("acme/shop", &f); + assert_eq!(s.code, "fixing_review"); + assert!(!s.needs_person); + f.working = false; + let s = decide("acme/shop", &f); + assert_eq!(s.code, "review_changes_requested"); + assert!(!s.needs_person); + assert!(s.text.contains("deferred")); + } + + #[test] + fn a_person_is_asked_only_for_the_teams_own_rule_and_the_rule_is_named() { + let mut off = clear(); + off.auto_merge = false; + let s = decide("acme/shop", &off); + assert_eq!(s.code, "auto_merge_off"); + assert!(s.needs_person); + assert!(s.text.starts_with("Auto-merge is off for this repo")); + assert_eq!(s.link, "/reviewer/config"); + + let mut key = clear(); + key.require_human_approval = true; + let s = decide("acme/shop", &key); + assert_eq!(s.code, "needs_person_approval"); + assert!(s.needs_person); + assert!(s + .text + .contains("requires an approving review from a person")); + key.human_approved = true; + assert_eq!(decide("acme/shop", &key).code, "merging"); + + let mut rules = clear(); + rules.blocked_by_rules = true; + let s = decide("acme/shop", &rules); + assert_eq!(s.code, "repo_requires_person_review"); + assert!(s + .text + .starts_with("Your repo's branch rules block the merge")); + assert_eq!(s.link, "https://github.com/acme/shop/settings/branches"); + } + + #[test] + fn coderhelms_own_work_comes_before_any_ask_of_a_person() { + // Auto-merge off AND red checks: the checks are said, not the setting. + let mut f = clear(); + f.auto_merge = false; + f.failing = vec!["unit".into()]; + let s = decide("acme/shop", &f); + assert_eq!(s.code, "checks_failing"); + assert!(!s.needs_person); + f.failing.clear(); + f.conflict = true; + assert_eq!(decide("acme/shop", &f).code, "conflict"); + f.conflict = false; + f.checks_running = true; + assert_eq!(decide("acme/shop", &f).code, "checks_running"); + } + + #[test] + fn no_standing_says_a_person_is_needed_without_naming_why() { + let mut all = vec![clear()]; + for i in 0..7 { + let mut f = clear(); + match i { + 0 => f.auto_merge = false, + 1 => f.require_human_approval = true, + 2 => f.blocked_by_rules = true, + 3 => f.draft = true, + 4 => f.merged = true, + 5 => f.closed = true, + _ => f.reviewer_on = false, + } + all.push(f); + } + for f in all { + let s = decide("acme/shop", &f); + assert!(!s.text.is_empty() && !s.next.is_empty(), "{s:?}"); + if s.needs_person { + assert!( + !s.link.is_empty(), + "a person's turn names its setting: {s:?}" + ); + } + assert_eq!(Standing::from_json(&s.to_json()), Some(s)); + } + } +} diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index e02e896b4..ad8dd9ce2 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -848,6 +848,12 @@ pub struct HealthCheckMessage { /// merge), so an approval wait never runs into it. #[serde(default)] pub approval_seen_at: Option, + /// The watch of a merge nobody asked a report for (CoderHelm's own pull + /// request merged by anyone, see `worker::passes::pr_watch`): it speaks + /// only when the deploy fails. A team's own health check setting is + /// never quiet. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub quiet: bool, } /// A deploy run of the merge commit that was superseded, and the later run on diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 1a06ba186..88fcf0543 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -991,6 +991,48 @@ fn draft_hold_of(item: &run_search::Item) -> Option { }) } +/// Where a run's pull request stands on its way to merge. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct RunMergeStanding { + /// Stable code: `merged`, `closed`, `reviewing`, `fixing_review`, + /// `review_changes_requested`, `checks_running`, `checks_failing`, + /// `conflict`, `draft`, `auto_merge_off`, `needs_person_approval`, + /// `repo_requires_person_review` or `merging`. + #[schema(example = "auto_merge_off")] + pub code: String, + /// What is true now, one sentence. + #[schema( + example = "Auto-merge is off for this repo, so CoderHelm leaves the merge to your team." + )] + pub text: String, + /// What happens next, one sentence. + #[schema( + example = "Merge it, or turn auto-merge on and CoderHelm merges approved pull requests itself." + )] + pub next: String, + /// A person has to act for the merge to happen. + #[schema(example = true)] + pub needs_person: bool, + /// Where the rule is set, when a setting decides it: a dashboard path + /// or a GitHub URL. Null otherwise. + #[schema(example = "/reviewer/config")] + pub link: Option, +} + +fn merge_standing_of(item: &run_search::Item) -> Option { + let s = item + .get(common::merge_standing::FIELD) + .and_then(|v| v.as_s().ok()) + .and_then(|s| common::merge_standing::Standing::from_json(s))?; + Some(RunMergeStanding { + code: s.code, + text: s.text, + next: s.next, + needs_person: s.needs_person, + link: Some(s.link).filter(|l| !l.is_empty()), + }) +} + fn waiting_on_of(item: &run_search::Item) -> Option { let w = common::run_wait::WaitingOn::of_item(item)?; Some(RunWaitingOn { @@ -1249,6 +1291,13 @@ pub struct Run { /// is ready or closed. #[schema(example = json!(null))] pub draft_hold: Option, + /// Where the run's pull request stands on its way to merge, in the one + /// reason that is true now (`common::merge_standing`): what holds it, + /// what happens next, whether a person has to act and, when a setting + /// decides it, where that setting is. Null until the worker has looked + /// at the pull request. + #[schema(example = json!(null))] + pub merge_standing: Option, /// The CI checks on the head of the run's open pull request, read from /// GitHub (reused for up to a minute). Null when the run has no open /// pull request or GitHub can't be read. @@ -1848,6 +1897,7 @@ fn run_of( None }, draft_hold: draft_hold_of(item), + merge_standing: merge_standing_of(item), checks: None, pr_review: None, pr_review_comments: None, diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 73cfcbf1b..77a3ba9fb 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -539,6 +539,17 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) prs = ?drafts.settled, "Draft sweep done" ); + // Finished runs' pull requests: a conflict with a moved base, + // checks that went red later, a reviewer verdict missing on the + // head, a merge whose deploy nobody watches. Each is picked + // back up by the mechanism it already has. + let watch = passes::pr_watch::sweep(&state).await; + info!( + candidates = watch.candidates, + looked_at = watch.looked_at, + acted = ?watch.acted, + "Pull request watch sweep done" + ); // Deploy counts that stopped between passes carry on without // waiting for someone to open Analytics. let resumed = passes::deploy_stats::sweep(&state).await; diff --git a/services/worker/src/passes/completeness.rs b/services/worker/src/passes/completeness.rs index 2b0130f0c..abb49ce1e 100644 --- a/services/worker/src/passes/completeness.rs +++ b/services/worker/src/passes/completeness.rs @@ -136,10 +136,17 @@ pub enum Section { /// the very top (see `ready::status_section`): a finished run never /// leaves its pull request a draft without saying why here. DraftStatus, + /// What a reviewer reads first: where to look, how to roll back, and + /// each verification claim with the recorded check result it rests on + /// (see `reviewer_guide`). Written from records, never by the writer. + ReviewerGuide, + /// Red checks judged not caused by the change, with the evidence and + /// what was done about them (see `common::flaky_checks`). + CiNotes, } impl Section { - const ALL: [Section; 10] = [ + const ALL: [Section; 12] = [ Section::Links, Section::Mirrors, Section::MergeOrder, @@ -150,6 +157,8 @@ impl Section { Section::OpenFindings, Section::Objections, Section::DraftStatus, + Section::ReviewerGuide, + Section::CiNotes, ]; /// Its start and end markers. @@ -174,6 +183,8 @@ impl Section { Section::OpenFindings => (super::own_review::START, super::own_review::END), Section::Objections => (OBJECTIONS_START, OBJECTIONS_END), Section::DraftStatus => (super::ready::STATUS_START, super::ready::STATUS_END), + Section::ReviewerGuide => (super::reviewer_guide::START, super::reviewer_guide::END), + Section::CiNotes => (common::flaky_checks::START, common::flaky_checks::END), } } } @@ -211,6 +222,8 @@ pub struct Owned { pub open_findings: String, pub objections: String, pub draft_status: String, + pub reviewer_guide: String, + pub ci_notes: String, } impl Owned { @@ -226,6 +239,8 @@ impl Owned { Section::OpenFindings => &mut self.open_findings, Section::Objections => &mut self.objections, Section::DraftStatus => &mut self.draft_status, + Section::ReviewerGuide => &mut self.reviewer_guide, + Section::CiNotes => &mut self.ci_notes, } } @@ -342,11 +357,13 @@ pub fn assemble(rest: &str, owned: &Owned) -> String { let (main, footer) = split_footer(rest); let main = main.trim(); let middle: Vec<&str> = [ + &owned.reviewer_guide, &owned.links, &owned.mirrors, &owned.merge_order, &owned.not_in_pr, &owned.review_fixes, + &owned.ci_notes, ] .into_iter() .map(|s| s.trim()) @@ -1202,6 +1219,8 @@ mod tests { objections: String::new(), draft_status: String::new(), links: String::new(), + reviewer_guide: String::new(), + ci_notes: String::new(), mirrors: mirrors_section(&[Mirror { path: "envs/prod/users.tf".into(), name: "billing_reader".into(), diff --git a/services/worker/src/passes/deploy_revert.rs b/services/worker/src/passes/deploy_revert.rs new file mode 100644 index 000000000..d64bb9303 --- /dev/null +++ b/services/worker/src/passes/deploy_revert.rs @@ -0,0 +1,489 @@ +//! Staying through deploy: a revert pull request when a merged change of +//! CoderHelm's breaks its deploy. +//! +//! After a merge the post-merge check (`health_check`) watches the merge +//! commit's own deploy. When that deploy fails on checks that were not +//! failing before the merge, CoderHelm opens a pull request that reverts +//! the change, with the evidence, ready for the team's approval. It never merges it: a revert of +//! a shared branch is the team's decision, made the way the team approves +//! any pull request. +//! +//! The revert is built from trees, with no sandbox: every path the merge +//! changed goes back to what it was before the merge, on top of the base +//! branch as it stands now. A path a later commit changed again is not +//! touched: then there is no clean revert, and CoderHelm says which files +//! moved instead of opening a pull request that would undo someone else's +//! work. One revert pull request per merge, however many times the deploy +//! is looked at. + +use std::collections::{BTreeSet, HashMap}; + +use tracing::{info, warn}; + +use crate::clients::github::{GitEntry, GitHubClient}; + +/// The branch a merge's revert lives on: one per merged pull request and +/// merge commit, so a second look finds the first one's pull request. +pub fn branch(pr_number: u64, merge_sha: &str) -> String { + format!("coderhelm/revert-{pr_number}-{}", short(merge_sha)) +} + +fn short(sha: &str) -> &str { + sha.get(..7).unwrap_or(sha) +} + +/// What reverting a merge on top of the current base comes to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Plan { + /// Lay these over the base's tree (`None` removes the path). + Clean(Vec<(String, Option)>), + /// Later commits changed these files the merge changed: no clean revert. + Moved(Vec), + /// The base already has every path as it was before the merge. + AlreadyReverted, +} + +/// The paths a merge changed: every path whose entry differs between the +/// tree before it and the tree it made (a rename is both its paths). +pub fn changed_paths( + before: &HashMap, + merged: &HashMap, +) -> Vec { + let mut paths: BTreeSet<&String> = BTreeSet::new(); + for (p, e) in merged { + if before.get(p) != Some(e) { + paths.insert(p); + } + } + for p in before.keys() { + if !merged.contains_key(p) { + paths.insert(p); + } + } + paths.into_iter().cloned().collect() +} + +/// Plans the revert of a merge on the base as it stands: `before` is the +/// tree the merge started from, `merged` the tree it made, `head` the base +/// branch's tree now. A path still as the merge left it goes back to what +/// it was; a path already back is left; a path a later commit changed is +/// reported and nothing is planned. +pub fn plan( + before: &HashMap, + merged: &HashMap, + head: &HashMap, +) -> Plan { + let mut changes: Vec<(String, Option)> = Vec::new(); + let mut moved: Vec = Vec::new(); + for path in changed_paths(before, merged) { + let (was, made, now) = (before.get(&path), merged.get(&path), head.get(&path)); + if now == was { + continue; + } + if now == made { + changes.push((path, was.cloned())); + } else { + moved.push(path); + } + } + if !moved.is_empty() { + Plan::Moved(moved) + } else if changes.is_empty() { + Plan::AlreadyReverted + } else { + Plan::Clean(changes) + } +} + +/// Why CoderHelm proposes the revert. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Cause { + /// The merge commit's deploy failed on checks that passed before it. + DeployFailed, +} + +/// The revert pull request's title, in GitHub's own shape so tools that +/// read reverts recognise it. +pub fn title(original_title: &str) -> String { + format!( + "Revert \"{}\"", + common::truncate_str(original_title.trim(), 200) + ) +} + +/// The revert's commit message. +pub fn commit_message(original_title: &str, pr_number: u64, merge_sha: &str) -> String { + format!( + "{}\n\nThis reverts commit {merge_sha} (#{pr_number}).", + title(original_title) + ) +} + +/// The revert pull request's description: what it reverts, the evidence +/// (one line each, as recorded), what the revert does and does not undo, +/// and that it waits for the team's approval. `rollback` is the reverted +/// change's own account of what a revert leaves in place +/// (`reviewer_guide::rollback` of its files). +pub fn body( + pr_number: u64, + merge_sha: &str, + cause: &Cause, + evidence: &[String], + files: &[String], + not_undone: &str, +) -> String { + let why = match cause { + Cause::DeployFailed => format!( + "The deploy of `{}` (the merge of #{pr_number}) failed on checks that were not \ + failing before the merge.", + short(merge_sha) + ), + }; + let evidence: String = evidence + .iter() + .map(|e| format!("* {}\n", e.trim().trim_start_matches(['-', '*']).trim())) + .collect(); + let shown: Vec = files.iter().take(20).map(|f| format!("`{f}`")).collect(); + let more = files.len().saturating_sub(shown.len()); + let mut out = format!( + "Reverts #{pr_number}\n\n**Summary** {why} This pull request puts every file that merge \ + changed back to what it was before it.\n\n**Evidence**\n{evidence}\n**Changes**\n* \ + {}{}\n\n", + shown.join(", "), + if more > 0 { + format!(" and {more} more") + } else { + String::new() + }, + ); + if !not_undone.trim().is_empty() { + out.push_str(&format!("**Not undone by this revert** {not_undone}\n\n")); + } + out.push_str( + "**Approval** CoderHelm opened this and does not merge it: it merges the way the team \ + approves any pull request. Closing it keeps the original change.", + ); + out +} + +/// What became of the proposal. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + Opened { + number: u64, + url: String, + }, + /// A revert pull request for this merge is open already. + Exists { + number: u64, + url: String, + }, + /// Later commits changed files the merge changed. + Moved(Vec), + AlreadyReverted, + /// Something couldn't be read or written, in plain words. + Failed(String), +} + +/// One line for the report on the merged pull request and the run: what +/// CoderHelm did about the failed deploy, never a request to do its work. +pub fn report_line(o: &Outcome) -> String { + match o { + Outcome::Opened { number, .. } => format!( + "CoderHelm opened #{number} to revert this change, with the evidence. It is not \ + merged without the team's approval." + ), + Outcome::Exists { number, .. } => { + format!("The revert of this change is #{number}, waiting for the team's approval.") + } + Outcome::Moved(files) => format!( + "CoderHelm did not open a revert: later commits changed {} since this merge, and a \ + revert would undo their work too.", + files + .iter() + .take(5) + .map(|f| format!("`{f}`")) + .collect::>() + .join(", ") + ), + Outcome::AlreadyReverted => { + "The base branch already has every file as it was before this merge: nothing to \ + revert." + .to_string() + } + Outcome::Failed(why) => format!( + "CoderHelm could not build the revert ({}); the failing checks are listed above.", + common::truncate_str(why, 200) + ), + } +} + +/// What to revert and why. +pub struct Request<'a> { + pub owner: &'a str, + pub repo: &'a str, + pub pr_number: u64, + pub merge_sha: &'a str, + pub base_branch: &'a str, + pub cause: Cause, + pub evidence: &'a [String], +} + +type BoxErr = Box; + +async fn tree_of( + github: &GitHubClient, + owner: &str, + repo: &str, + commit: &str, +) -> Result<(String, Vec, HashMap), BoxErr> { + let (tree, parents) = github.commit_tree_parents(owner, repo, commit).await?; + let entries = github + .tree_all(owner, repo, &tree) + .await? + .ok_or("the repository's tree is too large to read in one request")?; + Ok((tree, parents, entries)) +} + +/// The commit the merged pull request started from. A merge commit and a +/// squash start from the merge commit's first parent. A rebase merge laid +/// the pull request's commits one by one: it started that many first +/// parents back, which shows as the merge commit alone changing fewer files +/// than the pull request did. +async fn before_merge( + github: &GitHubClient, + r: &Request<'_>, + pr: &serde_json::Value, + merged: &HashMap, + parents: &[String], +) -> Result, BoxErr> { + let first = parents.first().ok_or("the merge commit has no parent")?; + let (_, mut up, mut before) = tree_of(github, r.owner, r.repo, first).await?; + let commits = pr["commits"].as_u64().unwrap_or(1); + let files = pr["changed_files"].as_u64().unwrap_or(0) as usize; + if parents.len() == 1 && commits > 1 && changed_paths(&before, merged).len() < files { + for _ in 1..commits.min(100) { + let Some(next) = up.first().cloned() else { + break; + }; + let (_, p, t) = tree_of(github, r.owner, r.repo, &next).await?; + up = p; + before = t; + } + } + Ok(before) +} + +async fn build(github: &GitHubClient, r: &Request<'_>) -> Result { + let name = branch(r.pr_number, r.merge_sha); + if let Some(open) = github + .find_open_pr_for_branch(r.owner, r.repo, &name) + .await? + { + return Ok(Outcome::Exists { + number: open["number"].as_u64().unwrap_or(0), + url: open["html_url"].as_str().unwrap_or("").to_string(), + }); + } + let pr = github + .get_pull_request(r.owner, r.repo, r.pr_number) + .await?; + let (_, parents, merged) = tree_of(github, r.owner, r.repo, r.merge_sha).await?; + let before = before_merge(github, r, &pr, &merged, &parents).await?; + let head_sha = github.get_ref(r.owner, r.repo, r.base_branch).await?; + let (head_tree, _, head) = tree_of(github, r.owner, r.repo, &head_sha).await?; + let changes = match plan(&before, &merged, &head) { + Plan::Clean(c) => c, + Plan::Moved(files) => return Ok(Outcome::Moved(files)), + Plan::AlreadyReverted => return Ok(Outcome::AlreadyReverted), + }; + let original = pr["title"].as_str().unwrap_or(""); + let tree = github + .put_tree(r.owner, r.repo, &head_tree, &changes) + .await?; + let commit = github + .put_commit( + r.owner, + r.repo, + &commit_message(original, r.pr_number, r.merge_sha), + &tree, + &[head_sha], + ) + .await?; + github + .create_branch(r.owner, r.repo, &name, &commit) + .await?; + let files: Vec = changes.iter().map(|(p, _)| p.clone()).collect(); + let as_files: Vec<(String, String, String)> = files + .iter() + .map(|p| (p.clone(), "modified".to_string(), String::new())) + .collect(); + let rollback = super::reviewer_guide::rollback(&as_files); + let not_undone = rollback + .split_once("The revert does not undo everything: ") + .map(|(_, rest)| rest.to_string()) + .unwrap_or_default(); + let opened = github + .create_pull_request( + r.owner, + r.repo, + &title(original), + &body( + r.pr_number, + r.merge_sha, + &r.cause, + r.evidence, + &files, + ¬_undone, + ), + &name, + r.base_branch, + // Ready for approval, never a draft: it is complete as it is. + false, + ) + .await?; + Ok(Outcome::Opened { + number: opened["number"].as_u64().unwrap_or(0), + url: opened["html_url"].as_str().unwrap_or("").to_string(), + }) +} + +/// Opens the revert pull request for a merge (or finds the one already +/// open). Never merges anything. +pub async fn propose(github: &GitHubClient, r: &Request<'_>) -> Outcome { + match build(github, r).await { + Ok(o) => { + info!(pr = r.pr_number, sha = %r.merge_sha, outcome = ?o, "Deploy watch: revert proposal"); + o + } + Err(e) => { + warn!(pr = r.pr_number, sha = %r.merge_sha, error = %e, "Deploy watch: could not build the revert"); + Outcome::Failed(common::run_fail::error_text(&*e)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn e(sha: &str) -> GitEntry { + GitEntry { + mode: "100644".to_string(), + kind: "blob".to_string(), + sha: sha.to_string(), + } + } + + fn tree(files: &[(&str, &str)]) -> HashMap { + files.iter().map(|(p, s)| (p.to_string(), e(s))).collect() + } + + #[test] + fn a_revert_right_after_the_merge_restores_every_path() { + let before = tree(&[ + ("src/a.ts", "a1"), + ("src/old.ts", "o1"), + ("README.md", "r1"), + ]); + // Changed a file, added one, renamed one. + let merged = tree(&[ + ("src/a.ts", "a2"), + ("src/new.ts", "n1"), + ("src/renamed.ts", "o1"), + ("README.md", "r1"), + ]); + assert_eq!( + changed_paths(&before, &merged), + vec!["src/a.ts", "src/new.ts", "src/old.ts", "src/renamed.ts"] + ); + let Plan::Clean(changes) = plan(&before, &merged, &merged) else { + panic!("clean revert expected"); + }; + assert_eq!( + changes, + vec![ + ("src/a.ts".to_string(), Some(e("a1"))), + ("src/new.ts".to_string(), None), + ("src/old.ts".to_string(), Some(e("o1"))), + ("src/renamed.ts".to_string(), None), + ] + ); + } + + #[test] + fn later_commits_to_other_files_stay_and_the_revert_is_still_clean() { + let before = tree(&[("src/a.ts", "a1"), ("src/b.ts", "b1")]); + let merged = tree(&[("src/a.ts", "a2"), ("src/b.ts", "b1")]); + let head = tree(&[("src/a.ts", "a2"), ("src/b.ts", "b9"), ("src/c.ts", "c1")]); + assert_eq!( + plan(&before, &merged, &head), + Plan::Clean(vec![("src/a.ts".to_string(), Some(e("a1")))]) + ); + } + + #[test] + fn a_file_someone_changed_since_is_never_overwritten() { + let before = tree(&[("src/a.ts", "a1"), ("src/b.ts", "b1")]); + let merged = tree(&[("src/a.ts", "a2"), ("src/b.ts", "b2")]); + let head = tree(&[("src/a.ts", "a3"), ("src/b.ts", "b2")]); + assert_eq!( + plan(&before, &merged, &head), + Plan::Moved(vec!["src/a.ts".to_string()]) + ); + } + + #[test] + fn a_change_already_reverted_plans_nothing() { + let before = tree(&[("src/a.ts", "a1")]); + let merged = tree(&[("src/a.ts", "a2"), ("src/n.ts", "n1")]); + assert_eq!(plan(&before, &merged, &before), Plan::AlreadyReverted); + // Half reverted by hand: the rest is still a clean revert. + let half = tree(&[("src/a.ts", "a1"), ("src/n.ts", "n1")]); + assert_eq!( + plan(&before, &merged, &half), + Plan::Clean(vec![("src/n.ts".to_string(), None)]) + ); + } + + #[test] + fn the_pull_request_carries_the_evidence_and_waits_for_approval() { + let sha = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"; + assert_eq!(branch(41, sha), "coderhelm/revert-41-a1b2c3d"); + assert_eq!(title("Add order totals"), "Revert \"Add order totals\""); + let b = body( + 41, + sha, + &Cause::DeployFailed, + &["- [**deploy-production**](https://github.com/acme/shop/actions/runs/9/job/1) (failure)".to_string()], + &["src/a.ts".to_string(), "db/migrate/0042.sql".to_string()], + "a migration that already ran stays applied (`db/migrate/0042.sql`).", + ); + // GitHub and the reward records recognise a revert by this line. + assert!(b.starts_with("Reverts #41\n")); + assert!(b.contains("The deploy of `a1b2c3d` (the merge of #41) failed")); + assert!(b.contains("* [**deploy-production**](https://github.com/acme/shop/actions/runs/9/job/1) (failure)")); + assert!(b.contains("`src/a.ts`, `db/migrate/0042.sql`")); + assert!(b.contains("**Not undone by this revert** a migration that already ran")); + assert!(b.contains("does not merge it")); + let low = b.to_lowercase(); + for phrase in crate::passes::ownership::HAND_OFF_PHRASES { + assert!(!low.contains(phrase), "{phrase}"); + } + } + + #[test] + fn every_outcome_is_reported_in_words() { + let opened = report_line(&Outcome::Opened { + number: 57, + url: String::new(), + }); + assert!( + opened.contains("#57") && opened.contains("not merged without the team's approval") + ); + let moved = report_line(&Outcome::Moved(vec!["src/a.ts".to_string()])); + assert!(moved.contains("did not open a revert") && moved.contains("`src/a.ts`")); + assert!(report_line(&Outcome::AlreadyReverted).contains("nothing to revert")); + assert!(report_line(&Outcome::Failed("GitHub API 502".into())).contains("GitHub API 502")); + } +} diff --git a/services/worker/src/passes/flaky.rs b/services/worker/src/passes/flaky.rs new file mode 100644 index 000000000..4f922a386 --- /dev/null +++ b/services/worker/src/passes/flaky.rs @@ -0,0 +1,274 @@ +//! The repository's record of flaky checks, and what a red check on a pull +//! request is judged against before a fix round (`common::flaky_checks`). +//! +//! The record is one item per repository in the settings table. It is +//! written when a commit's check failed, was re-run with nothing changed and +//! passed, and read when a later pull request's check fails: a check with +//! such a record on unrelated pull requests, whose failure names no file the +//! pull request changed, is re-run and not "fixed" in code. What was judged, +//! on what evidence, and what was done goes on the pull request. + +use aws_sdk_dynamodb::types::AttributeValue; +use chrono::Utc; +use common::flaky_checks::{self as fc, Judgement, Kind, Observation, Record, Rerun, Touch}; +use tracing::{info, warn}; + +use super::{attr_n, attr_s}; +use crate::clients::github::GitHubClient; +use crate::WorkerState; + +/// The run record's field naming the workflows whose failed jobs were +/// re-run on a head, so a later green on that head is written to the +/// repository's record under their names. +pub(crate) const RERUN_WORKFLOWS_FIELD: &str = "ci_rerun_workflows"; + +/// The repository's record and its version (0 when there is none yet). +pub(crate) async fn load(state: &WorkerState, team_id: &str, repo: &str) -> (Record, u64) { + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(&fc::sk(repo))) + .send() + .await + .ok() + .and_then(|r| r.item); + let Some(item) = item else { + return (Record::default(), 0); + }; + let record = item + .get("checks") + .and_then(|v| v.as_s().ok()) + .map(|s| Record::from_json(s)) + .unwrap_or_default(); + let version = item + .get("version") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0); + (record, version) +} + +/// Adds observations to the repository's record. Two writers at once (a +/// webhook and a sweep, two pull requests) never lose each other's: the +/// write is conditional on the version read, and read again when it moved. +pub(crate) async fn observe( + state: &WorkerState, + team_id: &str, + repo: &str, + checks: &[String], + o: &Observation, +) { + if checks.is_empty() || state.config.settings_table_name.is_empty() { + return; + } + for _ in 0..4 { + let (mut record, version) = load(state, team_id, repo).await; + let mut changed = false; + for c in checks { + changed |= record.observe(c, o.clone()); + } + if !changed { + return; + } + let mut req = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", attr_s(team_id)) + .item("sk", attr_s(&fc::sk(repo))) + .item("record_type", attr_s("flaky_checks")) + .item("repo", attr_s(repo)) + .item("checks", attr_s(&record.to_json())) + .item("version", attr_n(version + 1)) + .item("updated_at", attr_s(&Utc::now().to_rfc3339())); + req = if version == 0 { + req.condition_expression("attribute_not_exists(sk)") + } else { + req.condition_expression("version = :v") + .expression_attribute_values(":v", attr_n(version)) + }; + match req.send().await { + Ok(_) => { + info!(repo, checks = ?checks, kind = ?o.kind, pr = o.pr, "Flaky checks: recorded"); + return; + } + Err(e) if common::run_fail::is_condition_failed(&e) => continue, + Err(e) => { + warn!(repo, error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Flaky checks: could not record"); + return; + } + } + } + warn!( + repo, + "Flaky checks: the record kept moving; observation not written" + ); +} + +/// Remembers on the run which workflows were re-run on this head. +pub(crate) async fn remember_rerun( + state: &WorkerState, + team_id: &str, + run_id: &str, + workflows: &[String], +) { + let names: Vec = workflows + .iter() + .filter(|w| !w.trim().is_empty()) + .cloned() + .collect(); + if names.is_empty() { + return; + } + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("ADD #f :w") + .expression_attribute_names("#f", RERUN_WORKFLOWS_FIELD) + .expression_attribute_values(":w", AttributeValue::Ss(names)) + .send() + .await + { + warn!(run_id, error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Flaky checks: could not remember the re-run"); + } +} + +/// The workflows re-run on this run's heads. +pub(crate) fn rerun_workflows( + run_record: &std::collections::HashMap, +) -> Vec { + run_record + .get(RERUN_WORKFLOWS_FIELD) + .and_then(|v| v.as_ss().ok()) + .cloned() + .unwrap_or_default() +} + +/// A head that failed, was re-run with nothing changed and is green now: +/// the workflows re-run on it are written to the repository's record. +pub(crate) async fn passed_after_rerun( + state: &WorkerState, + team_id: &str, + repo: &str, + pr: u64, + head: &str, + run_record: &std::collections::HashMap, +) { + let workflows = rerun_workflows(run_record); + if workflows.is_empty() || head.is_empty() { + return; + } + observe( + state, + team_id, + repo, + &workflows, + &Observation { + kind: Kind::PassedOnRerun, + at: Utc::now().to_rfc3339(), + pr, + sha: head.to_string(), + line: String::new(), + }, + ) + .await; +} + +/// The failure of a pull request's head, as the fix round is about to see it. +pub(crate) struct Failure<'a> { + pub team_id: &'a str, + pub owner: &'a str, + pub repo: &'a str, + pub pr: u64, + /// The failing workflows (the record's check names). + pub failing: &'a [String], + /// Checks failing on the base branch's head too. + pub on_base: &'a [String], + /// Everything the failure printed. + pub logs: &'a str, + /// The infrastructure line the output shows, when it shows one. + pub infra: Option<&'a str>, +} + +/// Judges the failure: the pull request's changed files against what the +/// output names, and the failing checks against the repository's record. +/// With the changed files unreadable the failure is the pull request's. +pub(crate) async fn judge( + state: &WorkerState, + github: &GitHubClient, + f: &Failure<'_>, +) -> (Judgement, Touch) { + let changed: Vec = match github.list_pull_files(f.owner, f.repo, f.pr).await { + Ok(files) => files.into_iter().map(|(path, _)| path).collect(), + Err(e) => { + warn!(pr = f.pr, error = %e, "Flaky checks: could not read the pull request's files"); + return ( + Judgement { + ours: f.failing.to_vec(), + not_ours: Vec::new(), + }, + Touch::Unknown, + ); + } + }; + let touch = fc::touch(f.logs, &changed); + let (record, _) = load(state, f.team_id, &format!("{}/{}", f.owner, f.repo)).await; + let j = fc::judge( + f.failing, + f.on_base, + &touch, + f.infra, + &record, + f.pr, + Utc::now(), + ); + (j, touch) +} + +/// Writes the judgement on the pull request (its own section of the +/// description, replaced on a later judgement). +pub(crate) async fn note_on_pr( + github: &GitHubClient, + owner: &str, + repo: &str, + pr: u64, + section: String, +) { + let body = match github.get_pull_request(owner, repo, pr).await { + Ok(p) => p["body"].as_str().unwrap_or("").to_string(), + Err(e) => { + warn!(pr, error = %e, "Flaky checks: could not read the pull request to note the judgement"); + return; + } + }; + let out = + super::completeness::with_section(&body, super::completeness::Section::CiNotes, section); + if out != body { + if let Err(e) = github.update_pr_body(owner, repo, pr, &out).await { + warn!(pr, error = %e, "Flaky checks: could not note the judgement on the pull request"); + } + } +} + +/// The progress note for a judgement that changed no code. +pub(crate) fn progress_note(j: &Judgement, rerun: &Rerun) -> String { + let checks: Vec<&str> = j.not_ours.iter().map(|(c, _)| c.as_str()).collect(); + let did = match rerun { + Rerun::Started => "re-ran the failed jobs and changed no code", + Rerun::NoPermission => { + "changed no code; the re-run needs the GitHub App's Actions write permission, which \ + this installation doesn't grant" + } + Rerun::NotActions => "changed no code; the checks run outside GitHub Actions", + }; + format!( + "CI is red on {} for a reason outside this change (the evidence is on the pull request): \ + CoderHelm {did}.", + checks.join(", ") + ) +} diff --git a/services/worker/src/passes/health_check.rs b/services/worker/src/passes/health_check.rs index 991489d05..139cf5b91 100644 --- a/services/worker/src/passes/health_check.rs +++ b/services/worker/src/passes/health_check.rs @@ -837,8 +837,10 @@ pub async fn run(state: &WorkerState, msg: HealthCheckMessage) -> Result<(), Box delay, } => { msg.green_since = None; - let body = render_interim(&msg.merge_sha, finished, &failed, &waiting, &follows); - upsert_comment(&github, &msg, &body).await; + if speaks(msg.quiet, None) { + let body = render_interim(&msg.merge_sha, finished, &failed, &waiting, &follows); + upsert_comment(&github, &msg, &body).await; + } info!( pr = msg.pr_number, sha = %msg.merge_sha, @@ -876,7 +878,19 @@ pub async fn run(state: &WorkerState, msg: HealthCheckMessage) -> Result<(), Box "Health check: SAFETY CEILING reached with the deploy still running" ); } - let body = render(&msg.merge_sha, &verdict, &follows); + if !speaks(msg.quiet, Some(&verdict)) { + info!(pr = msg.pr_number, sha = %msg.merge_sha, ?verdict, "Health check: quiet watch, nothing failed, nothing to report"); + return Ok(()); + } + let mut body = render(&msg.merge_sha, &verdict, &follows); + // A failed deploy of CoderHelm's own change: the revert is + // opened, ready for the team's approval, with these failures as + // its evidence. Never merged here. + if let Verdict::Failed(jobs) = &verdict { + if let Some(line) = propose_revert(state, &github, &msg, jobs).await { + body = with_revert_line(&body, &line); + } + } upsert_comment(&github, &msg, &body).await; info!(pr = msg.pr_number, sha = %msg.merge_sha, ?verdict, "Health check reported"); } @@ -884,6 +898,78 @@ pub async fn run(state: &WorkerState, msg: HealthCheckMessage) -> Result<(), Box Ok(()) } +/// Whether a look's result is said on the pull request. A quiet watch (a +/// merge nobody asked a report for) speaks only for a failed deploy. +pub fn speaks(quiet: bool, verdict: Option<&Verdict>) -> bool { + !quiet || matches!(verdict, Some(Verdict::Failed(_))) +} + +/// The failed verdict's comment with what CoderHelm did about it: the +/// question it used to end on is answered by the revert's own line. +pub fn with_revert_line(body: &str, line: &str) -> String { + const ASK: &str = " Rolling a deploy back needs the approval"; + const ASK_END: &str = "be rolled back?"; + if let (Some(a), Some(b)) = (body.find(ASK), body.find(ASK_END)) { + if b > a { + return format!("{} {line}{}", &body[..a], &body[b + ASK_END.len()..]); + } + } + match body.rfind("\n\n"; +pub const END: &str = ""; + +/// Passed checks named one by one; the rest are counted. +const MAX_PASSED_LINES: usize = 8; + +fn is_test(path: &str) -> bool { + let l = path.to_ascii_lowercase(); + l.contains(".test.") + || l.contains(".spec.") + || l.contains("_test.") + || l.contains("__tests__") + || l.contains("/test/") + || l.contains("/tests/") + || l.starts_with("test/") + || l.starts_with("tests/") +} + +/// Files nobody reviews line by line: lockfiles, snapshots, generated code. +fn is_generated(path: &str) -> bool { + let l = path.to_ascii_lowercase(); + let name = l.rsplit('/').next().unwrap_or(&l); + name.ends_with(".lock") + || name.ends_with("-lock.json") + || name.ends_with("-lock.yaml") + || name == "go.sum" + || name.ends_with(".snap") + || name.ends_with(".min.js") + || l.contains("/generated/") + || l.contains("/__snapshots__/") +} + +fn added_lines(patch: &str) -> usize { + patch + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + .count() +} + +/// The first path a risk reason names in backticks, when the diff has it. +fn path_in_reason(reason: &str, files: &[(String, String, String)]) -> Option { + reason + .split('`') + .skip(1) + .step_by(2) + .find(|p| files.iter().any(|(f, _, _)| f == p)) + .map(str::to_string) +} + +/// Where the reviewer looks first, and why: the file the diff's risk floor +/// names, else the code file with the most added lines. None for a diff +/// with nothing to read (only removed, generated or test files). +pub fn look_first(files: &[(String, String, String)], floor: &Floor) -> Option<(String, String)> { + for reason in &floor.reasons { + if let Some(path) = path_in_reason(reason, files) { + return Some((path, reason.clone())); + } + } + files + .iter() + .filter(|(p, status, _)| status != "removed" && !is_test(p) && !is_generated(p)) + .map(|(p, _, patch)| (p, added_lines(patch))) + .filter(|(_, n)| *n > 0) + // The first of equals, so the answer never depends on file order + // beyond the diff's own. + .fold(None::<(&String, usize)>, |best, cur| match best { + Some(b) if b.1 >= cur.1 => Some(b), + _ => Some(cur), + }) + .map(|(p, n)| { + ( + p.clone(), + format!( + "the largest change to code ({n} added line{})", + if n == 1 { "" } else { "s" } + ), + ) + }) +} + +/// What reverting the code leaves in place, by the kind of file changed. +const NOT_UNDONE: &[(&str, &[&str])] = &[ + ( + "a migration that already ran stays applied", + &["/migrations/", "/migration/", "/migrate/", "db/migrate"], + ), + ( + "infrastructure already applied stays as it is until the stack is applied again", + &[ + ".tf", + ".tfvars", + "cloudformation", + "/cdk/", + "/infra/", + "/helm/", + "/k8s/", + ], + ), +]; + +/// How to roll the change back: a revert of the pull request, and what that +/// revert does not undo, each with the changed file that says so. +pub fn rollback(files: &[(String, String, String)]) -> String { + let mut caveats: Vec = Vec::new(); + for (what, marks) in NOT_UNDONE { + let hit = files.iter().find(|(p, status, _)| { + let l = format!("/{}", p.to_ascii_lowercase()); + status != "removed" + && marks.iter().any(|m| match m.strip_prefix('.') { + // An extension ends the path; a directory is anywhere in it. + Some(_) => l.ends_with(m), + None => l.contains(m), + }) + }); + if let Some((p, _, _)) = hit { + caveats.push(format!("{what} (`{p}`)")); + } + } + if caveats.is_empty() { + "revert this pull request; nothing outside the code changes with it.".to_string() + } else { + format!( + "revert this pull request. The revert does not undo everything: {}.", + caveats.join("; ") + ) + } +} + +/// One check's standing on the head commit. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Check { + pub name: String, + pub url: String, + pub state: State, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum State { + Passed, + Failed, + Running, + /// Skipped, neutral or cancelled: it reported, and proved nothing. + DidNotRun, +} + +/// The newest run of each check in a `check-runs` listing (commit statuses +/// included, see `common::commit_ci`), by name. +pub fn checks_of(listing: &Value) -> Vec { + let mut latest: HashMap<&str, &Value> = HashMap::new(); + let mut order: Vec<&str> = Vec::new(); + for c in listing["check_runs"].as_array().into_iter().flatten() { + let Some(name) = c["name"].as_str().filter(|n| !n.is_empty()) else { + continue; + }; + let ts = c["started_at"].as_str().unwrap_or(""); + match latest.get(name) { + Some(prev) if prev["started_at"].as_str().unwrap_or("") > ts => {} + Some(_) => { + latest.insert(name, c); + } + None => { + order.push(name); + latest.insert(name, c); + } + } + } + order + .into_iter() + .map(|name| { + let c = latest[name]; + let state = if c["status"].as_str() != Some("completed") { + State::Running + } else { + match c["conclusion"].as_str().unwrap_or("") { + "success" => State::Passed, + "skipped" | "neutral" | "cancelled" | "stale" => State::DidNotRun, + _ => State::Failed, + } + }; + Check { + name: name.to_string(), + url: c["html_url"] + .as_str() + .or_else(|| c["details_url"].as_str()) + .unwrap_or("") + .to_string(), + state, + } + }) + .collect() +} + +fn short(sha: &str) -> &str { + sha.get(..7).unwrap_or(sha) +} + +fn linked(c: &Check) -> String { + if c.url.starts_with("https://") { + format!("[`{}`]({})", c.name.replace('`', "'"), c.url) + } else { + format!("`{}`", c.name.replace('`', "'")) + } +} + +/// The verification lines: what passed on `head` (each with its recorded +/// result), then what did not verify the change and why. Empty when no +/// check reported: no claim is made without a result behind it. +pub fn verified_lines(checks: &[Check], head: &str) -> Vec { + let mut out = Vec::new(); + let passed: Vec<&Check> = checks.iter().filter(|c| c.state == State::Passed).collect(); + if !passed.is_empty() { + let shown: Vec = passed + .iter() + .take(MAX_PASSED_LINES) + .map(|c| linked(c)) + .collect(); + let more = passed.len().saturating_sub(MAX_PASSED_LINES); + out.push(format!( + "**Verified by:** {}{} passed on `{}`.", + shown.join(", "), + if more > 0 { + format!(" and {more} more") + } else { + String::new() + }, + short(head) + )); + } + let mut not: Vec = Vec::new(); + for (state, word) in [ + (State::Failed, "failed"), + (State::Running, "still running"), + (State::DidNotRun, "did not run"), + ] { + let names: Vec = checks + .iter() + .filter(|c| c.state == state) + .map(linked) + .collect(); + if !names.is_empty() { + not.push(format!("{} ({word})", names.join(", "))); + } + } + if !not.is_empty() { + out.push(format!( + "**Not verified on `{}`:** {}.", + short(head), + not.join("; ") + )); + } + out +} + +/// The section, from the diff's files (path, status, patch), its risk +/// floor, the head commit and that commit's checks. Empty when there is +/// nothing to say. +pub fn section( + files: &[(String, String, String)], + floor: &Floor, + head: &str, + checks: &[Check], +) -> String { + let mut lines: Vec = Vec::new(); + if let Some((path, why)) = look_first(files, floor) { + // A reason that already names the file reads on its own. + lines.push(if why.contains(&format!("`{path}`")) { + format!("**Look first:** {why}.") + } else { + format!("**Look first:** `{path}`, {why}.") + }); + } + if !files.is_empty() { + lines.push(format!("**Roll back:** {}", rollback(files))); + } + lines.extend(verified_lines(checks, head)); + if lines.is_empty() { + return String::new(); + } + format!( + "{START}\n**For the reviewer**\n{}\n{END}", + lines + .iter() + .map(|l| format!("* {l}")) + .collect::>() + .join("\n") + ) +} + +/// `body` with the section rebuilt for the current diff and head. +pub fn put(body: &str, section: String) -> String { + super::completeness::with_section(body, super::completeness::Section::ReviewerGuide, section) +} + +/// The section for a pull request as it stands: its current diff's files +/// and floor, and the checks on `head`. An unreadable check listing leaves +/// the verification lines out rather than guessing them. +pub async fn build( + github: &GitHubClient, + owner: &str, + repo: &str, + files: &[(String, String, String)], + floor: &Floor, + head: &str, +) -> String { + let checks = if head.is_empty() { + Vec::new() + } else { + match github.list_ci_for_ref(owner, repo, head).await { + Ok(listing) => checks_of(&listing), + Err(e) => { + warn!(owner, repo, head, error = %e, "Reviewer guide: could not read the head's checks"); + Vec::new() + } + } + }; + section(files, floor, head, &checks) +} + +/// Rebuilds the section on an open pull request from what GitHub shows now. +/// Costs no model call. Leaves the description alone when nothing changed +/// or anything can't be read. +pub async fn refresh(github: &GitHubClient, owner: &str, repo: &str, pr_number: u64) { + let Ok(pr) = github.get_pull_request(owner, repo, pr_number).await else { + return; + }; + let (Some(base), Some(head_ref)) = (pr["base"]["ref"].as_str(), pr["head"]["ref"].as_str()) + else { + return; + }; + let head = pr["head"]["sha"].as_str().unwrap_or(""); + let body = pr["body"].as_str().unwrap_or(""); + let Ok(diff) = github.get_diff(owner, repo, base, head_ref).await else { + return; + }; + let files = super::pr_risk::diff_files(&diff); + let floor = super::pr_risk::floor(&files, &HashMap::new()); + let out = put(body, build(github, owner, repo, &files, &floor, head).await); + if out != body { + if let Err(e) = github.update_pr_body(owner, repo, pr_number, &out).await { + warn!(pr_number, error = %e, "Reviewer guide: could not save the description"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::passes::pr_risk::Level; + use serde_json::json; + + const HEAD: &str = "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567"; + + fn file(path: &str, status: &str, added: usize) -> (String, String, String) { + ( + path.to_string(), + status.to_string(), + format!("@@ -1 +1,{added} @@\n{}", "+line\n".repeat(added)), + ) + } + + fn low() -> Floor { + Floor { + level: Level::Low, + reasons: Vec::new(), + } + } + + fn run(name: &str, status: &str, conclusion: Option<&str>, started: &str) -> Value { + json!({ + "name": name, "status": status, "conclusion": conclusion, + "started_at": started, + "html_url": format!("https://github.com/acme/shop/actions/runs/7/job/{}", name.len()), + }) + } + + #[test] + fn the_risk_floors_file_is_looked_at_first() { + let files = vec![ + file("apps/web/src/pages/cart.tsx", "modified", 90), + file("apps/web/src/middleware.ts", "modified", 4), + ]; + let floor = Floor { + level: Level::Medium, + reasons: vec!["`apps/web/src/middleware.ts` runs on every request".to_string()], + }; + let (path, why) = look_first(&files, &floor).unwrap(); + assert_eq!(path, "apps/web/src/middleware.ts"); + assert!(why.contains("every request")); + // A reason naming a file the diff no longer has is not followed. + let stale = Floor { + level: Level::Medium, + reasons: vec!["`apps/web/src/gone.ts` is shared".to_string()], + }; + assert_eq!( + look_first(&files, &stale).unwrap().0, + "apps/web/src/pages/cart.tsx" + ); + } + + #[test] + fn without_a_floor_the_largest_code_change_is_first_never_a_test_or_lockfile() { + let files = vec![ + file("pnpm-lock.yaml", "modified", 900), + file("apps/web/src/cart/total.test.ts", "added", 120), + file("apps/web/src/cart/total.ts", "modified", 31), + file("apps/web/src/cart/format.ts", "modified", 31), + file("apps/web/src/cart/old.ts", "removed", 0), + ]; + let (path, why) = look_first(&files, &low()).unwrap(); + assert_eq!(path, "apps/web/src/cart/total.ts"); + assert_eq!(why, "the largest change to code (31 added lines)"); + assert_eq!( + look_first(&[file("pnpm-lock.yaml", "modified", 9)], &low()), + None + ); + } + + #[test] + fn rollback_says_what_a_revert_does_not_undo() { + assert_eq!( + rollback(&[file("apps/web/src/a.ts", "modified", 3)]), + "revert this pull request; nothing outside the code changes with it." + ); + let r = rollback(&[ + file("services/api/migrations/0042_orders.sql", "added", 12), + file("infra/queues.tf", "modified", 5), + ]); + assert!(r.starts_with("revert this pull request. The revert does not undo everything:")); + assert!(r.contains( + "a migration that already ran stays applied (`services/api/migrations/0042_orders.sql`)" + )); + assert!(r.contains("(`infra/queues.tf`)")); + // A removed migration file is no new migration. + assert!( + !rollback(&[file("services/api/migrations/0001.sql", "removed", 0)]) + .contains("does not undo") + ); + } + + #[test] + fn every_verification_claim_points_at_a_recorded_result() { + let listing = json!({"check_runs": [ + run("unit", "completed", Some("failure"), "2026-02-01T10:00:00Z"), + // The re-run of the same check is the one that counts. + run("unit", "completed", Some("success"), "2026-02-01T10:20:00Z"), + run("lint", "completed", Some("success"), "2026-02-01T10:00:00Z"), + run("e2e", "in_progress", None, "2026-02-01T10:00:00Z"), + run("deploy-preview", "completed", Some("skipped"), "2026-02-01T10:00:00Z"), + run("types", "completed", Some("timed_out"), "2026-02-01T10:00:00Z"), + ]}); + let checks = checks_of(&listing); + let lines = verified_lines(&checks, HEAD); + assert_eq!(lines.len(), 2); + assert_eq!( + lines[0], + "**Verified by:** [`unit`](https://github.com/acme/shop/actions/runs/7/job/4), \ + [`lint`](https://github.com/acme/shop/actions/runs/7/job/4) passed on `0a1b2c3`." + ); + assert!(lines[1].starts_with("**Not verified on `0a1b2c3`:**")); + assert!(lines[1].contains("job/5) (failed)"), "{}", lines[1]); + assert!(lines[1].contains("job/3) (still running)"), "{}", lines[1]); + assert!(lines[1].contains("job/14) (did not run)"), "{}", lines[1]); + // A check that did not pass is never among the verified. + assert!(!lines[0].contains("e2e") && !lines[0].contains("types")); + } + + #[test] + fn no_check_result_means_no_verification_claim() { + assert!(verified_lines(&[], HEAD).is_empty()); + let s = section(&[file("src/a.ts", "modified", 2)], &low(), HEAD, &[]); + assert!(s.contains("**Look first:** `src/a.ts`")); + assert!(s.contains("**Roll back:**")); + assert!(!s.contains("Verified")); + } + + #[test] + fn many_passed_checks_are_counted_not_listed() { + let checks: Vec = (0..MAX_PASSED_LINES + 3) + .map(|i| Check { + name: format!("job-{i}"), + url: String::new(), + state: State::Passed, + }) + .collect(); + let lines = verified_lines(&checks, HEAD); + assert!( + lines[0].contains("`job-7` and 3 more passed"), + "{}", + lines[0] + ); + } + + #[test] + fn nothing_to_say_is_no_section_and_the_section_is_replaced_in_place() { + assert_eq!(section(&[], &low(), HEAD, &[]), ""); + let body = + "Closes #4\n\n**Summary** x\n\n**Risk** **Low**: small.\n\n**Verification**\n1. CI."; + let first = put( + body, + section(&[file("src/a.ts", "modified", 2)], &low(), HEAD, &[]), + ); + assert!(first.find(START).unwrap() < first.find("**Risk**").unwrap()); + assert!(first.find("**Summary**").unwrap() < first.find(START).unwrap()); + let second = put( + &first, + section(&[file("src/b.ts", "modified", 9)], &low(), HEAD, &[]), + ); + assert_eq!(second.matches(START).count(), 1); + assert!(second.contains("`src/b.ts`") && !second.contains("`src/a.ts`")); + assert_eq!(put(&second, String::new()), body); + } +}