diff --git a/docs/incidents/xu_every_repo_gets_its_ci_rounds.md b/docs/incidents/xu_every_repo_gets_its_ci_rounds.md new file mode 100644 index 00000000..47cdd9a8 --- /dev/null +++ b/docs/incidents/xu_every_repo_gets_its_ci_rounds.md @@ -0,0 +1,15 @@ +# xu. `xu_every_repo_gets_its_ci_rounds` + +**What happened:** A ticket asked the bookstore's orders service to return a book's price in cents and the storefront to show it. The plan changed both repositories and the run opened a pull request in each. CI failed on the storefront's pull request: a price test still expected the old shape. The run's CI loop read both heads, saw a red one, and finished with the pull requests open, saying CoderHelm fixes CI only inside a single repository. Nothing fixed the storefront, and its red check was left for a person. + +**Why:** The loop for a run with several pull requests only read CI. The fix rounds, the mode diagnosis and the rule that rounds go on while they make progress all lived in the single repository loop, which reads one repository and one branch from the run record. + +**The guarantee (invariants, enforced in code):** + +- **Each pull request has its own CI ledger.** Every pull request of the run is an entry of `common::repo_ci::RepoCi` on the run record: its rounds, how many in a row met the same failure, and whether its rounds stopped or wait on a person. +- **A red pull request gets the same round a single repository gets.** The mode diagnosis first (`mode_cause`, `mode_repair::on_red`): a mode CoderHelm's own commits dropped is put back and CI decides again. Then the CI fix round every fix takes (`run_fix_round`, a `run_round` round with its own budget, parked for a fresh step when it needs one), on that pull request's branch, with its failing checks, their logs and the run's other pull requests named. A parked round runs again for the pull request it belongs to. The run waits for CI on what the round pushed. +- **Repositories go independently; providers first.** A pull request whose change builds on another repository's (the plan's order, which is also the merge order) waits while that one is red or its CI runs. Every other red pull request takes its round; the one with the fewest rounds goes first. A provider whose rounds stopped never holds the rest. +- **Rounds go on while they make progress.** The bound is the single repository loop's own rule (`run_round::ci_cycle_goes_on`): a round followed by the same failure it was asked to fix made no progress. Two such rounds in a row stop that pull request's rounds. The stop is CoderHelm's own problem: an internal alert and the run page's line (`own_problems::record`), the pull request says what fails and what was tried, and the run ends with its typed stop with the checks named (`stop_red`). Never a person's to-do. +- **The run ends only when every pull request is settled.** All green or merged: each goes through the ready decision in the plan's order and the run completes. A person is named only for a typed person-only reason (`common::person_only::admit`): a round that changed no code and found the fix needs a GitHub permission only an admin grants holds that pull request, and the run's note says exactly that, beside every other pull request having gone green. + +**Where it's enforced:** `common::repo_ci::{RepoCi::of, next, begin, after_round, hold_for_person, brief}`, the worker's `resume::{resume_multi_repo, run_repo_round, repo_red, stop_repo_rounds, ready_in_merge_order, restore_primary, claim_for_round, CI_FIX_RULES}`, and `run_fix_round`, which keeps a CI round's account for the reading after it. diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 2e4f5708..458b6493 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -217,6 +217,9 @@ pub mod embed; /// Knowledge bases: files a team uploads, read into cited passages that the /// brain chat and the team's agents search. pub mod knowledge; +// CI fix rounds for every pull request of a run that spans several +// repositories. +pub mod repo_ci; // Reading the team's repositories for Chat (overview, files, search). pub mod repo_reach; pub mod repo_read; diff --git a/services/common/src/repo_ci.rs b/services/common/src/repo_ci.rs new file mode 100644 index 00000000..6a1f5d46 --- /dev/null +++ b/services/common/src/repo_ci.rs @@ -0,0 +1,414 @@ +//! CI on every pull request of a run that spans several repositories. +//! +//! A run whose plan changes several repositories opens one pull request in +//! each. Its CI loop read every head and, when any of them was red, finished +//! with the pull requests open and the red ones left as they were. The +//! ledger here gives each pull request its own CI fix rounds instead: +//! +//! - **Each red pull request gets its own rounds.** The round is the one a +//! single repository's run takes (the worker's `run_fix_round`, after the +//! mode diagnosis), on that pull request's branch, counted on its own entry +//! ([`PrCi`]); nothing is shared between repositories but the run. +//! - **Rounds go on while they make progress.** The bound is the single +//! repository loop's own rule ([`crate::run_round::ci_cycle_goes_on`]): a +//! round followed by the same failure it was asked to fix made no +//! progress, and rounds in a row without progress stop that pull +//! request's rounds ([`RepoCi::begin`]). A stop is CoderHelm's own problem +//! ([`PrCi::stopped`]), never a person's to-do. +//! - **Repositories go independently, providers first.** A pull request +//! whose change builds on another repository's ([`PrCi::after`]: the +//! plan's order, which is the merge order) waits while that one is red or +//! its CI runs; every other red pull request takes its round. Among +//! several, the one with the fewest rounds goes first, then the plan's +//! order ([`RepoCi::next`]). +//! - **The run ends only when every pull request is settled**: green, merged +//! or closed, stopped as CoderHelm's own problem, or held by a typed +//! person-only reason ([`crate::person_only::PersonOnly`], +//! [`RepoCi::hold_for_person`]). They are offered for merge in the plan's +//! order. + +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; + +use crate::run_prs::RunPr; + +/// The run record field with the ledger ([`RepoCi`], as JSON). +pub const FIELD: &str = "repo_ci"; + +/// One pull request of the run, with its own CI fix rounds. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PrCi { + pub url: String, + /// `owner/name`. + pub repo: String, + pub number: u64, + pub branch: String, + /// The repositories whose change this one builds on: they are fixed and + /// merge first. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub after: Vec, + /// CI fix rounds started on it. + #[serde(default)] + pub rounds: u32, + /// Rounds in a row, up to now, after which the same failure came back. + #[serde(default)] + pub idle: u32, + /// The failure its last round was asked to fix (its signature). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub asked: String, + /// Why CoderHelm stopped its rounds here: its own problem, said as such. + /// Empty while they go on. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub stopped: String, + /// The typed person-only reason that holds it ([`crate::person_only::PersonOnly::line`]). + /// Empty when there is none. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub person: String, + /// That reason's code ([`crate::person_only::PersonOnly::code`]). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub person_code: String, +} + +impl PrCi { + /// `owner/name#12`. + pub fn label(&self) -> String { + format!("{}#{}", self.repo, self.number) + } + + /// No more rounds go to it while it stays red: stopped or held for a + /// person. + pub fn settled_red(&self) -> bool { + !self.stopped.is_empty() || !self.person.is_empty() + } + + fn builds_on(&self, repo: &str) -> bool { + self.after.iter().any(|r| r.eq_ignore_ascii_case(repo)) + } +} + +/// Every pull request of the run, in the plan's order (the merge order). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RepoCi { + pub prs: Vec, + /// The pull request whose round is on the run's record now (parked for + /// a fresh step, or running); empty when none. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub fixing: String, +} + +/// What one pull request's CI says now. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Ci { + /// Its checks still run, or could not be read. + Pending, + /// Every check passed, or it runs none. + Green, + /// A check failed. + Red, + Merged, + Closed, +} + +/// What the run does next about its pull requests' CI. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Next { + /// A CI fix round on this pull request (its URL) now. + Fix(String), + /// CI still runs on these, or they wait on the repositories they build + /// on: look again later. + Wait(Vec), + /// Every pull request is green, merged or closed. + Done, + /// Every pull request is settled, and these are red: stopped as + /// CoderHelm's own problem, or held by a person-only reason. + Settled { + stopped: Vec, + person: Vec, + }, +} + +/// Whether a pull request's next round starts. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Begin { + /// It starts, as this round number of that pull request. + Go(u32), + /// Its rounds stop: CoderHelm's own problem, in these words. + Stop(String), +} + +impl RepoCi { + 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() + .filter(|l| !l.prs.is_empty()) + } + + /// The ledger for the run's pull requests, in the plan's `order` (its + /// repositories, the merge order; pull requests in a repository the + /// plan doesn't name come after, as the run lists them), keeping what + /// `prev` counted for each. A pull request builds on every repository + /// the plan orders before its own; with no plan order, on none. + pub fn of(prs: &[RunPr], order: &[String], prev: Option<&RepoCi>) -> RepoCi { + let rank = |repo: &str| order.iter().position(|r| r.eq_ignore_ascii_case(repo)); + let mut sorted: Vec<&RunPr> = prs.iter().collect(); + sorted.sort_by_key(|p| rank(&p.repo).unwrap_or(usize::MAX)); + let mut out = RepoCi::default(); + for p in sorted { + let after = match rank(&p.repo) { + Some(i) => order[..i] + .iter() + .filter(|r| prs.iter().any(|o| o.repo.eq_ignore_ascii_case(r))) + .cloned() + .collect(), + None => Vec::new(), + }; + let kept = prev.and_then(|l| l.prs.iter().find(|e| e.url == p.url)); + out.prs.push(PrCi { + url: p.url.clone(), + repo: p.repo.clone(), + number: p.pr_number, + branch: p.branch.clone(), + after, + ..kept.cloned().unwrap_or_default() + }); + } + if let Some(l) = prev { + if out.prs.iter().any(|p| p.url == l.fixing) { + out.fixing = l.fixing.clone(); + } + } + out + } + + pub fn entry(&self, url: &str) -> Option<&PrCi> { + self.prs.iter().find(|p| p.url == url) + } + + fn entry_mut(&mut self, url: &str) -> Option<&mut PrCi> { + self.prs.iter_mut().find(|p| p.url == url) + } + + /// What the run does next, from each pull request's CI now (`seen`, by + /// URL; one not seen is read as still running). + pub fn next(&self, seen: &HashMap) -> Next { + let ci = |p: &PrCi| seen.get(&p.url).copied().unwrap_or(Ci::Pending); + // A repository others build on holds them while it is red and still + // being fixed, or while its CI runs. + let holds = |p: &PrCi| match ci(p) { + Ci::Pending => true, + Ci::Red => !p.settled_red(), + _ => false, + }; + let mut fix: Option<(u32, usize, &str)> = None; + let mut waiting = Vec::new(); + let mut stopped = Vec::new(); + let mut person = Vec::new(); + for (i, p) in self.prs.iter().enumerate() { + match ci(p) { + Ci::Green | Ci::Merged | Ci::Closed => {} + Ci::Pending => waiting.push(p.url.clone()), + Ci::Red if !p.stopped.is_empty() => stopped.push(p.url.clone()), + Ci::Red if !p.person.is_empty() => person.push(p.url.clone()), + Ci::Red => { + let held = self + .prs + .iter() + .any(|d| d.url != p.url && p.builds_on(&d.repo) && holds(d)); + if held { + waiting.push(p.url.clone()); + } else if fix.is_none_or(|(r, j, _)| (p.rounds, i) < (r, j)) { + fix = Some((p.rounds, i, &p.url)); + } + } + } + } + if let Some((_, _, url)) = fix { + return Next::Fix(url.to_string()); + } + if !waiting.is_empty() { + return Next::Wait(waiting); + } + if stopped.is_empty() && person.is_empty() { + Next::Done + } else { + Next::Settled { stopped, person } + } + } + + /// A round is about to start on `url` against the failure `sig`: the + /// single repository loop's rule decides whether it goes on + /// ([`crate::run_round::ci_cycle_goes_on`], with `usual` rounds). The + /// same failure its last round was asked to fix is a round without + /// progress; another failure is progress. + pub fn begin(&mut self, url: &str, sig: &str, usual: u32) -> Begin { + let Some(p) = self.entry_mut(url) else { + return Begin::Stop(format!("{url} is not a pull request of this run")); + }; + p.idle = if !p.asked.is_empty() && p.asked == sig { + p.idle + 1 + } else { + 0 + }; + if !crate::run_round::ci_cycle_goes_on(p.rounds, usual, p.idle) { + p.stopped = if p.idle > 0 { + format!( + "CoderHelm's CI fix rounds on {} met the same failure after {} round(s) in a \ + row, {} round(s) in all: its own dead end", + p.label(), + p.idle, + p.rounds + ) + } else { + format!( + "CoderHelm's CI fix rounds on {} reached their bound of {} round(s): its own \ + limit", + p.label(), + p.rounds + ) + }; + let why = p.stopped.clone(); + if self.fixing == url { + self.fixing.clear(); + } + return Begin::Stop(why); + } + p.rounds += 1; + p.asked = sig.to_string(); + let n = p.rounds; + self.fixing = url.to_string(); + Begin::Go(n) + } + + /// The round on `url` ended (whatever it pushed: CI on its head says + /// next whether it made progress). + pub fn after_round(&mut self, url: &str) { + if self.fixing == url { + self.fixing.clear(); + } + } + + /// `url` stays red for a reason only a person can clear: no more rounds + /// go to it, and the run's ending names the reason. + pub fn hold_for_person(&mut self, url: &str, p: &crate::person_only::PersonOnly) { + if let Some(e) = self.entry_mut(url) { + e.person = p.line(); + e.person_code = p.code().to_string(); + } + self.after_round(url); + } + + /// What a round on `url` is told about the run's other pull requests. + pub fn brief(&self, url: &str) -> String { + let Some((i, p)) = self.prs.iter().enumerate().find(|(_, p)| p.url == url) else { + return String::new(); + }; + let others: Vec = self + .prs + .iter() + .filter(|o| o.url != url) + .map(PrCi::label) + .collect(); + let mut out = format!( + "\n\nThis pull request is part {} of {} of one run that changes several \ + repositories; the others are {}. Fix this repository's failures here; a change \ + another repository needs belongs to that one's pull request.", + i + 1, + self.prs.len(), + others.join(", ") + ); + if !p.after.is_empty() { + out.push_str(&format!( + " This change builds on {}: they merge first, and their pull requests carry what \ + this one uses.", + p.after.join(", ") + )); + } + out + } + + /// The pull requests' lines for the run's ending, for `urls`. + pub fn lines(&self, urls: &[String], f: impl Fn(&PrCi) -> String) -> Vec { + urls.iter().filter_map(|u| self.entry(u)).map(f).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pr(repo: &str, n: u64) -> RunPr { + RunPr { + repo: repo.into(), + pr_number: n, + branch: format!("coderhelm/book-{n}"), + url: format!("https://github.com/{repo}/pull/{n}"), + outcome: String::new(), + } + } + + fn seen(pairs: &[(&RunPr, Ci)]) -> HashMap { + pairs.iter().map(|(p, c)| (p.url.clone(), *c)).collect() + } + + #[test] + fn the_plan_orders_the_ledger_and_keeps_its_counts() { + let api = pr("acme/orders-api", 4); + let web = pr("acme/shop", 9); + let order = vec!["acme/orders-api".to_string(), "acme/shop".to_string()]; + let mut l = RepoCi::of(&[web.clone(), api.clone()], &order, None); + assert_eq!(l.prs[0].repo, "acme/orders-api"); + assert!(l.prs[0].after.is_empty()); + assert_eq!(l.prs[1].after, vec!["acme/orders-api".to_string()]); + assert_eq!(l.begin(&web.url, "s1", 10), Begin::Go(1)); + let again = RepoCi::from_json(&l.to_json()).unwrap(); + let kept = RepoCi::of(&[api.clone(), web.clone()], &order, Some(&again)); + assert_eq!(kept.entry(&web.url).unwrap().rounds, 1); + assert_eq!(kept.fixing, web.url); + // No plan order: nothing builds on anything. + let free = RepoCi::of(&[api, web], &[], None); + assert!(free.prs.iter().all(|p| p.after.is_empty())); + } + + #[test] + fn a_repository_waits_while_the_one_it_builds_on_is_red_or_running() { + let api = pr("acme/orders-api", 4); + let web = pr("acme/shop", 9); + let order = vec!["acme/orders-api".to_string(), "acme/shop".to_string()]; + let mut l = RepoCi::of(&[api.clone(), web.clone()], &order, None); + let both_red = seen(&[(&api, Ci::Red), (&web, Ci::Red)]); + assert_eq!(l.next(&both_red), Next::Fix(api.url.clone())); + let running = seen(&[(&api, Ci::Pending), (&web, Ci::Red)]); + assert_eq!( + l.next(&running), + Next::Wait(vec![api.url.clone(), web.url.clone()]) + ); + let green = seen(&[(&api, Ci::Green), (&web, Ci::Red)]); + assert_eq!(l.next(&green), Next::Fix(web.url.clone())); + // A provider whose rounds stopped holds nothing. + l.prs[0].stopped = "stopped".into(); + assert_eq!(l.next(&both_red), Next::Fix(web.url.clone())); + let done = seen(&[(&api, Ci::Merged), (&web, Ci::Green)]); + assert_eq!(l.next(&done), Next::Done); + } + + #[test] + fn the_same_failure_twice_in_a_row_stops_as_its_own_problem() { + let api = pr("acme/orders-api", 4); + let mut l = RepoCi::of(std::slice::from_ref(&api), &[], None); + assert_eq!(l.begin(&api.url, "a", 10), Begin::Go(1)); + // Another failure after it: progress. + assert_eq!(l.begin(&api.url, "b", 10), Begin::Go(2)); + assert_eq!(l.begin(&api.url, "b", 10), Begin::Go(3)); + let Begin::Stop(why) = l.begin(&api.url, "b", 10) else { + panic!("a second round without progress goes on") + }; + assert!(why.contains("CoderHelm") && why.contains("its own dead end")); + assert!(l.fixing.is_empty()); + assert_eq!(l.entry(&api.url).unwrap().rounds, 3); + } +} diff --git a/services/worker/src/passes/incidents/xu_every_repo_gets_its_ci_rounds.rs b/services/worker/src/passes/incidents/xu_every_repo_gets_its_ci_rounds.rs new file mode 100644 index 00000000..b2f1c1a1 --- /dev/null +++ b/services/worker/src/passes/incidents/xu_every_repo_gets_its_ci_rounds.rs @@ -0,0 +1,359 @@ +//! xu. A ticket asked the bookstore's orders service to return a book's +//! price in cents and the storefront to show it. The plan changed both +//! repositories and the run opened a pull request in each. CI failed on the +//! storefront's: a price test still expected the old shape. The run's CI +//! loop read both heads, saw a red one, and finished with the pull requests +//! open, saying CoderHelm fixes CI only inside a single repository. +//! Nothing fixed the storefront, and the red check was left for a person. +//! +//! Why: the loop for a run with several pull requests only read CI. The +//! fix rounds, the mode diagnosis and the progress rule lived in the +//! single repository loop, which reads one repository and one branch from +//! the run record. +//! +//! Guarantee: each pull request of such a run is kept on its own entry +//! (`common::repo_ci`). A red one gets the same CI fix round a single +//! repository takes (`mode_cause`, then `run_fix_round` on its branch), +//! counted on its entry, and the run waits for CI on what it pushed. One +//! that builds on another repository's change (the plan's order) waits +//! while that one is red or its CI runs; the others go on by themselves. +//! Rounds go on while the failure changes; rounds in a row that meet the +//! same failure stop that pull request's rounds as CoderHelm's own problem, +//! never a person's. The run ends only when every pull request is settled, +//! offered for merge in the plan's order, and it names a person only for a +//! typed person-only reason. + +use std::collections::HashMap; + +use common::person_only::{admit, Grantor, Want}; +use common::repo_ci::{Begin, Ci, Next, RepoCi}; +use common::run_prs::RunPr; + +const RESUME: &str = include_str!("../resume.rs"); +const USUAL: u32 = 10; + +const ORDERS: &str = "acme/orders-api"; +const SHOP: &str = "acme/shop"; + +fn pr(repo: &str, n: u64) -> RunPr { + RunPr { + repo: repo.into(), + pr_number: n, + branch: "coderhelm/price-in-cents".into(), + url: format!("https://github.com/{repo}/pull/{n}"), + outcome: String::new(), + } +} + +/// One pull request in the replay: what CI says after each of its rounds +/// (`None` green, `Some` red with that failure), and what it says now. +struct Repo { + after_rounds: Vec>, + now: Ci, + failure: &'static str, + /// CI on its head still runs for this many looks. + running: u32, +} + +/// How a replayed run ended, and what it did on the way. +#[derive(Debug, Default)] +struct Ended { + /// Every round, by pull request URL, in the order they ran. + rounds: Vec, + /// Pull requests offered for merge, in order. + offered: Vec, + /// Own problems recorded. + own: Vec, + stopped: Vec, + person: Vec, + /// For each look, the pull requests the run waited on. + waits: Vec>, +} + +/// Runs the ledger the way `resume_multi_repo` does: one decision per look, +/// a round on the pull request it names, CI on what that round pushed. +fn replay(ledger: &mut RepoCi, world: &mut HashMap) -> Ended { + let mut out = Ended::default(); + for _ in 0..200 { + let seen: HashMap = world.iter().map(|(u, r)| (u.clone(), r.now)).collect(); + match ledger.next(&seen) { + Next::Fix(url) => { + let r = world.get_mut(&url).unwrap(); + match ledger.begin(&url, r.failure, USUAL) { + Begin::Go(n) => { + out.rounds.push(url.clone()); + let next = r + .after_rounds + .get(n as usize - 1) + .copied() + .unwrap_or_else(|| r.after_rounds.last().copied().flatten()); + match next { + Some(f) => r.failure = f, + None => r.failure = "", + } + // CI runs on what the round pushed. + r.now = Ci::Pending; + r.running = 1; + ledger.after_round(&url); + } + Begin::Stop(why) => out.own.push(why), + } + } + Next::Wait(urls) => { + out.waits.push(urls); + for r in world.values_mut() { + if r.now == Ci::Pending { + if r.running > 0 { + r.running -= 1; + } else if r.failure.is_empty() { + r.now = Ci::Green; + } else { + r.now = Ci::Red; + } + } + } + } + Next::Done => { + out.offered = ledger.prs.iter().map(|p| p.url.clone()).collect(); + for p in &ledger.prs { + world.get_mut(&p.url).unwrap().now = Ci::Merged; + } + return out; + } + Next::Settled { stopped, person } => { + out.offered = ledger.prs.iter().map(|p| p.url.clone()).collect(); + out.stopped = stopped; + out.person = person; + return out; + } + } + } + panic!("the run never settled: {out:?}"); +} + +fn repo(now: Ci, failure: &'static str, after_rounds: &[Option<&'static str>]) -> Repo { + Repo { + after_rounds: after_rounds.to_vec(), + now, + failure, + running: 0, + } +} + +fn plan() -> Vec { + vec![ORDERS.to_string(), SHOP.to_string()] +} + +/// The storefront's pull request is red and the orders service's green: +/// the storefront gets its round, CI goes green, and both are offered for +/// merge, the orders service first. +#[test] +fn a_red_pull_request_in_one_repository_is_fixed_and_merged() { + let (api, web) = (pr(ORDERS, 31), pr(SHOP, 52)); + let mut ledger = RepoCi::of(&[web.clone(), api.clone()], &plan(), None); + let mut world = HashMap::from([ + (api.url.clone(), repo(Ci::Green, "", &[])), + ( + web.url.clone(), + repo( + Ci::Red, + "price.test.ts: expected 1299, got \"12.99\"", + &[None], + ), + ), + ]); + let end = replay(&mut ledger, &mut world); + assert_eq!(end.rounds, vec![web.url.clone()]); + assert_eq!(end.offered, vec![api.url.clone(), web.url.clone()]); + assert!(end.own.is_empty() && end.stopped.is_empty() && end.person.is_empty()); + assert!(world.values().all(|r| r.now == Ci::Merged)); +} + +/// Both red, no plan order between them: each gets its own rounds, the one +/// with fewer rounds first, and a second failure after a fix is progress. +#[test] +fn both_red_both_get_their_rounds_and_go_green() { + let (api, web) = (pr(ORDERS, 31), pr(SHOP, 52)); + let mut ledger = RepoCi::of(&[api.clone(), web.clone()], &[], None); + let mut world = HashMap::from([ + ( + api.url.clone(), + repo( + Ci::Red, + "orders.rs: mismatched types", + &[Some("orders_test.rs: price_cents missing"), None], + ), + ), + ( + web.url.clone(), + repo(Ci::Red, "price.test.ts: expected 1299", &[None]), + ), + ]); + let end = replay(&mut ledger, &mut world); + // Independent: the storefront's round doesn't wait for the orders + // service to go green. + assert_eq!( + end.rounds, + vec![api.url.clone(), web.url.clone(), api.url.clone()] + ); + assert!(end.own.is_empty() && end.stopped.is_empty()); + assert!(world.values().all(|r| r.now == Ci::Merged)); + assert_eq!(ledger.entry(&api.url).unwrap().rounds, 2); + assert_eq!(ledger.entry(&web.url).unwrap().rounds, 1); +} + +/// A pull request whose rounds keep meeting the same failure stops after +/// the bound, as CoderHelm's own problem: no person is named, the other +/// pull request is still fixed and offered, and the run's ending is the +/// stop. +#[test] +fn a_stuck_pull_request_stops_after_the_bound_as_its_own_problem() { + let (api, web) = (pr(ORDERS, 31), pr(SHOP, 52)); + let mut ledger = RepoCi::of(&[api.clone(), web.clone()], &[], None); + let same = "checkout.spec.ts: timeout waiting for #pay"; + let mut world = HashMap::from([ + ( + api.url.clone(), + repo(Ci::Red, "orders.rs: mismatched types", &[None]), + ), + (web.url.clone(), repo(Ci::Red, same, &[Some(same)])), + ]); + let end = replay(&mut ledger, &mut world); + let stuck = ledger.entry(&web.url).unwrap(); + // Two rounds met the same failure in a row: the third never starts. + assert_eq!(stuck.rounds, 2); + assert_eq!(end.rounds.iter().filter(|u| **u == web.url).count(), 2); + assert_eq!(end.stopped, vec![web.url.clone()]); + assert!(end.person.is_empty() && stuck.person.is_empty()); + assert_eq!(end.own.len(), 1); + assert!(end.own[0].contains("CoderHelm") && end.own[0].contains("its own dead end")); + for words in ["a person", "you ", "manual", "hand"] { + assert!(!end.own[0].to_lowercase().contains(words), "{}", end.own[0]); + } + // The other repository was fixed meanwhile. + assert_eq!(world[&api.url].now, Ci::Green); + // While the failure changes, the rounds go on past two. + let mut moving = RepoCi::of(std::slice::from_ref(&web), &[], None); + let mut world = HashMap::from([( + web.url.clone(), + repo(Ci::Red, "a", &[Some("b"), Some("c"), Some("d"), None]), + )]); + let end = replay(&mut moving, &mut world); + assert_eq!(end.rounds.len(), 4); + assert!(end.own.is_empty()); +} + +/// The storefront builds on the orders service's change (the plan's +/// order): it waits while the orders service is red or its CI runs, gets +/// its round once that one is green, and they are offered in that order. +/// A stopped provider never holds the rest. +#[test] +fn a_dependent_repository_waits_for_the_one_it_builds_on() { + let (api, web) = (pr(ORDERS, 31), pr(SHOP, 52)); + let mut ledger = RepoCi::of(&[web.clone(), api.clone()], &plan(), None); + assert_eq!(ledger.prs[1].after, vec![ORDERS.to_string()]); + let mut world = HashMap::from([ + ( + api.url.clone(), + repo(Ci::Red, "orders.rs: price_cents not found", &[None]), + ), + ( + web.url.clone(), + repo(Ci::Red, "api.ts: property price_cents missing", &[None]), + ), + ]); + let end = replay(&mut ledger, &mut world); + assert_eq!(end.rounds, vec![api.url.clone(), web.url.clone()]); + // While the orders service's CI ran, the storefront waited on it. + assert!(end.waits.iter().any(|w| w.contains(&web.url))); + assert_eq!(end.offered, vec![api.url.clone(), web.url.clone()]); + + // The orders service stuck: once its rounds stop, the storefront goes + // on by itself. + let mut ledger = RepoCi::of(&[api.clone(), web.clone()], &plan(), None); + let mut world = HashMap::from([ + (api.url.clone(), repo(Ci::Red, "x", &[Some("x")])), + (web.url.clone(), repo(Ci::Red, "y", &[None])), + ]); + let end = replay(&mut ledger, &mut world); + assert_eq!(end.stopped, vec![api.url.clone()]); + assert_eq!(world[&web.url].now, Ci::Green); + let web_first = end.rounds.iter().position(|u| *u == web.url).unwrap(); + let api_last = end.rounds.iter().rposition(|u| *u == api.url).unwrap(); + assert!(api_last < web_first, "{:?}", end.rounds); +} + +/// Only a typed person-only reason holds a red pull request for a person; +/// words that name what CoderHelm owns never do. +#[test] +fn only_a_typed_person_only_reason_holds_a_red_pull_request() { + let (api, web) = (pr(ORDERS, 31), pr(SHOP, 52)); + let mut ledger = RepoCi::of(&[api.clone(), web.clone()], &plan(), None); + let grant = admit( + Want::Grant(Grantor::RepoAdmin), + "actions:write for the GitHub App on acme/shop, to start the deploy preview", + ) + .expect("a permission only an admin grants"); + ledger.hold_for_person(&web.url, &grant); + let seen = HashMap::from([(api.url.clone(), Ci::Green), (web.url.clone(), Ci::Red)]); + assert_eq!( + ledger.next(&seen), + Next::Settled { + stopped: vec![], + person: vec![web.url.clone()] + } + ); + assert!(ledger + .entry(&web.url) + .unwrap() + .person + .contains("actions:write")); + // CoderHelm's own sandbox is never a person's to grant. + assert!(admit( + Want::Grant(Grantor::RepoAdmin), + "the sandbox's network allowlist blocks the package registry" + ) + .is_err()); +} + +/// The run's CI loop for several pull requests runs the single repository +/// round, keeps the ledger, and names a person only through the typed +/// reason. The sentence that left red CI open is gone. +#[test] +fn the_multi_repository_loop_runs_rounds_through_the_ledger() { + let start = RESUME + .find("\nasync fn resume_multi_repo(") + .expect("resume_multi_repo"); + let end = RESUME[start..] + .find("\nstruct RepoRed") + .map(|i| start + i) + .expect("RepoRed"); + let multi = &RESUME[start..end]; + for call in [ + "RepoCi::of(", + "ledger.next(&seen)", + "ledger.begin(", + "mode_cause(", + "run_repo_round(", + "stop_repo_rounds(", + "stop_red(", + "ready_in_merge_order(", + "claim_for_round(", + ] { + assert!(multi.contains(call), "resume_multi_repo lost {call}"); + } + let round = super::fixture::fn_src(RESUME, "\nasync fn run_repo_round("); + assert!(round.contains("run_fix_round(")); + assert!(round.contains("hold_for_person(")); + assert!(round.contains("person_only::{admit")); + let stop = super::fixture::fn_src(RESUME, "\nasync fn stop_repo_rounds("); + assert!(stop.contains("own_problems::record(")); + assert!(!stop.contains("wait_for_review(") && !stop.contains("NEEDS_INPUT")); + // The parked round runs for the pull request it belongs to. + assert!(multi.contains("ledger.entry(&ledger.fixing)")); + let low = RESUME.to_lowercase(); + assert!(!low.contains("one repository at a time")); + assert!(!low.contains("so it finished with the pull requests open")); + // The single repository loop and these rounds read the same rules. + assert_eq!(RESUME.matches("{CI_FIX_RULES}").count(), 2); +} diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index f27bbb2e..908d3309 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -32,6 +32,22 @@ const MAX_RESUME_POLLS: i64 = 720; /// UNDER the coarse MAX_CI_FIX_CYCLES ceiling and fires much sooner. const MAX_STALL_CYCLES: u32 = 2; +/// What every CI fix round is told before its failure: the single +/// repository loop's and each pull request's of a run that spans several +/// (`resume_multi_repo`). +pub(crate) const CI_FIX_RULES: &str = "Rules:\n\ + - Only fix what CI is complaining about. Don't refactor or add features.\n\ + - Fix ONLY failures caused by this PR's own changes. NEVER fix pre-existing \ + lint warnings/unused imports/style issues in files this PR does not touch, \ + even when CI logs mention them — they pre-date this PR; note them in your \ + summary instead.\n\ + - If the failure is in a test, fix the code (not the test) unless the test itself is wrong.\n\ + - If tests need updating because the feature changed behavior intentionally, update the tests.\n\ + - For lint/formatting failures (Prettier, ESLint): read the existing file first, match its style exactly (trailing commas, line length, quote style, indentation). Write the COMPLETE file content.\n\ + - NEVER replace a real file with a stub or placeholder to make an error go away — write the complete, working implementation. If you broke a file, use restore_file to recover it, then fix it properly.\n\ + - Before you finish, call run_checks to verify your fix builds and type-checks against real output. Do not finish on a red result if run_checks is available.\n\ + - You may create new test files or edit existing ones if needed.\n\n"; + /// Deterministic FNV-1a hash — stable across processes/deploys (unlike a /// randomized hasher), so a stored signature compares correctly next invocation. fn stable_hash(s: &str) -> u64 { @@ -1812,15 +1828,16 @@ pub async fn run( .map(|t| t.with_timezone(&chrono::Utc)); // A run that opened pull requests in several repositories waits on each - // pull request's own CI: its record holds one repo and one branch, which - // needn't belong together (see `resume_multi_repo`). + // pull request's own CI and fixes each red one in rounds of its own + // (`resume_multi_repo`, `common::repo_ci`): its record's one repo and + // branch describe only its primary pull request. let pr_urls: Vec = run_record .get("pr_urls") .and_then(|v| v.as_l().ok()) .map(|l| l.iter().filter_map(|x| x.as_s().ok().cloned()).collect()) .unwrap_or_default(); if pr_urls.len() > 1 { - return resume_multi_repo(state, &msg, &pr_urls, created_at).await; + return resume_multi_repo(state, &msg, &run_record, created_at, &start).await; } // A fix round parked for a fresh invocation runs first, with its whole @@ -3272,18 +3289,7 @@ pub async fn run( let mut feedback = format!( "CI workflow failed on PR #{pr_number} (branch: {branch}). Fix the failures.\n\n\ - Rules:\n\ - - Only fix what CI is complaining about. Don't refactor or add features.\n\ - - Fix ONLY failures caused by this PR's own changes. NEVER fix pre-existing \ - lint warnings/unused imports/style issues in files this PR does not touch, \ - even when CI logs mention them — they pre-date this PR; note them in your \ - summary instead.\n\ - - If the failure is in a test, fix the code (not the test) unless the test itself is wrong.\n\ - - If tests need updating because the feature changed behavior intentionally, update the tests.\n\ - - For lint/formatting failures (Prettier, ESLint): read the existing file first, match its style exactly (trailing commas, line length, quote style, indentation). Write the COMPLETE file content.\n\ - - NEVER replace a real file with a stub or placeholder to make an error go away — write the complete, working implementation. If you broke a file, use restore_file to recover it, then fix it properly.\n\ - - Before you finish, call run_checks to verify your fix builds and type-checks against real output. Do not finish on a red result if run_checks is available.\n\ - - You may create new test files or edit existing ones if needed.\n\n\ + {CI_FIX_RULES}\ Failure summary:\n{failure_logs}{repro_brief}{logs_brief}\n\n\ Full logs:\n{logs}{review_context}{base_note}{lock_context}" ); @@ -5240,6 +5246,11 @@ async fn run_fix_round( // The round asked for the description through its tool, or // handed it to a person: either way it is rebuilt now. let rebuild_description = handed_off || r.description_rebuild; + // A CI round's account says where the fix lives: what runs the + // next round reads it (`common::red_reach`). + if round.kind == run_round::Kind::CiFix { + save_fix_account(state, &msg.team_id, &msg.run_id, &r.evidence.notes).await; + } *refused = std::mem::take(&mut r.refused); let outside_plan = std::mem::take(&mut r.outside_plan); // What this round was asked and looked up reaches the next one. @@ -5587,29 +5598,7 @@ async fn run_pending_round( return Ok(()); } // Claim the run, as every resume that works does. - let claimed = state - .dynamo - .update_item() - .table_name(&state.config.runs_table_name) - .key("team_id", attr_s(&msg.team_id)) - .key("run_id", attr_s(&msg.run_id)) - .update_expression( - "SET #s = :new_s, status_run_id = :sri, current_pass = :cp, updated_at = :t", - ) - .condition_expression("#s = :expected") - .expression_attribute_names("#s", "status") - .expression_attribute_values(":expected", attr_s("awaiting_ci")) - .expression_attribute_values(":new_s", attr_s("running")) - .expression_attribute_values( - ":sri", - common::run_ending::working(common::run_ending::Working::Running, &msg.run_id) - .sri_attr(), - ) - .expression_attribute_values(":cp", attr_s("implement")) - .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) - .send() - .await - .is_ok(); + let claimed = claim_for_round(state, msg).await; if !claimed { info!( run_id = msg.run_id, @@ -10766,88 +10755,690 @@ async fn requeue_after_model_error( true } -/// Send a delayed resume message to the CI fix queue. -/// `delay_seconds` can be 0 (immediate) or up to 900 (15 min, SQS max). -/// CI for a run that opened pull requests in several repositories. Each -/// pull request's own head is checked: all green, every one is marked ready -/// and the run completes; any failure, the run is handed to a person (this -/// loop fixes CI in one repository, not across several); otherwise it checks -/// again later, within [`MAX_RESUME_POLLS`]. +/// Claims a waiting run for a round (`awaiting_ci` to `running`), as every +/// resume that works does. False when it isn't waiting (another invocation +/// has it, or it ended). +async fn claim_for_round(state: &WorkerState, msg: &ResumeMessage) -> bool { + state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(&msg.run_id)) + .update_expression( + "SET #s = :new_s, status_run_id = :sri, current_pass = :cp, updated_at = :t", + ) + .condition_expression("#s = :expected") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":expected", attr_s("awaiting_ci")) + .expression_attribute_values(":new_s", attr_s("running")) + .expression_attribute_values( + ":sri", + common::run_ending::working(common::run_ending::Working::Running, &msg.run_id) + .sri_attr(), + ) + .expression_attribute_values(":cp", attr_s("implement")) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await + .is_ok() +} + +/// CI for a run that opened pull requests in several repositories +/// (`common::repo_ci`). Each pull request's own head is read. A red one gets +/// the CI fix round a single repository's run takes (the mode diagnosis +/// first, `mode_cause`; then `run_fix_round` on that pull request's branch), +/// counted on its own entry of the ledger, and the run waits for CI on what +/// it pushed. A pull request whose change builds on another repository's +/// waits while that one is red or its CI runs. Rounds on a pull request go +/// on while they make progress; past the bound they stop as CoderHelm's own +/// problem. The run ends only when every pull request is settled: all green +/// (or merged), each is offered in the plan's order and the run completes; a +/// stop ends it with CoderHelm's typed stop and the checks named; a red one +/// only a person can clear (a typed `PersonOnly`) is named as such. +/// Otherwise it checks again later. async fn resume_multi_repo( state: &WorkerState, msg: &ResumeMessage, - pr_urls: &[String], + run_record: &RunRecord, created_at: Option>, + start: &std::time::Instant, ) -> Result<(), Box> { + use common::repo_ci::{Begin, Ci, Next, RepoCi}; let github = GitHubClient::new( &state.secrets.github_app_id, &state.secrets.github_private_key, msg.installation_id, &state.http, )?; - let mut open = Vec::new(); - let mut failed = Vec::new(); - let mut waiting = Vec::new(); - for url in pr_urls { - let Some((owner, name, number)) = common::pr_outcome::parse_pr_url(url) else { + let text = |k: &str| { + run_record + .get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + // The plan's repositories in its order: the merge order, and what + // builds on what. + let order: Vec = + common::plan_repos::PlanRepos::from_json(&text(common::plan_repos::FIELD)) + .map(|p| p.parts.into_iter().map(|p| p.repo).collect()) + .unwrap_or_default(); + let prev = RepoCi::from_json(&text(common::repo_ci::FIELD)); + let mut ledger = RepoCi::of( + &common::run_prs::from_item(run_record), + &order, + prev.as_ref(), + ); + + // A round parked for one of them runs first, with its whole budget. + if let Some(pending) = + run_round::Round::from_item(run_record).filter(|r| r.state == run_round::State::Pending) + { + if let Some(p) = ledger.entry(&ledger.fixing).cloned() { + if !claim_for_round(state, msg).await { + info!(run_id = %msg.run_id, "Could not claim the run for its parked round, skipping"); + return Ok(()); + } + let base = pr_base(&github, &p).await; + let ctx = repo_fix_context(state, msg, run_record, &p, &base).await?; + info!(run_id = %msg.run_id, pr = %p.url, "Multi-repo run: running a parked CI fix round"); + let round = pending.resumed(chrono::Utc::now()); + return run_repo_round( + state, + msg, + run_record, + &mut ledger, + (&p, ctx, round), + created_at, + start, + ) + .await; + } + } + + let mut seen = std::collections::HashMap::new(); + let mut heads = std::collections::HashMap::new(); + let mut bases = std::collections::HashMap::new(); + for p in &ledger.prs { + let Some((owner, name)) = p.repo.split_once('/') else { continue; }; - let pr = match github.get_pull_request(&owner, &name, number).await { - Ok(p) => p, + let pr = match github.get_pull_request(owner, name, p.number).await { + Ok(pr) => pr, Err(e) => { - warn!(run_id = %msg.run_id, pr = %url, error = %e, "Could not read a pull request — checking again later"); - waiting.push(url.clone()); + warn!(run_id = %msg.run_id, pr = %p.url, error = %e, "Could not read a pull request — checking again later"); + seen.insert(p.url.clone(), Ci::Pending); continue; } }; if pr["state"].as_str() == Some("closed") { + let merged = pr["merged"].as_bool() == Some(true) || pr["merged_at"].is_string(); + seen.insert(p.url.clone(), if merged { Ci::Merged } else { Ci::Closed }); continue; } let head = pr["head"]["sha"].as_str().unwrap_or("").to_string(); - match evaluate_ci_verdict(&github, &owner, &name, &head).await { - CiVerdict::Failed => failed.push(url.clone()), - CiVerdict::Pending => waiting.push(url.clone()), + bases.insert( + p.url.clone(), + pr["base"]["ref"].as_str().unwrap_or("main").to_string(), + ); + let ci = match evaluate_ci_verdict(&github, owner, name, &head).await { + CiVerdict::Failed => Ci::Red, + CiVerdict::Pending => Ci::Pending, // CI's green result settles the checks the PR opened without. CiVerdict::Green => { - super::pr::settle_unverified_by_ci(&github, &owner, &name, number).await + super::pr::settle_unverified_by_ci(&github, owner, name, p.number).await; + Ci::Green } - CiVerdict::NoChecks => {} - } - open.push((owner, name, number)); + CiVerdict::NoChecks => Ci::Green, + }; + heads.insert(p.url.clone(), head); + seen.insert(p.url.clone(), ci); } let events = load_unprocessed_events(state, &msg.team_id, &msg.run_id) .await .unwrap_or_default(); - let n_open = open.len(); - let finish = |note: Option| async move { - if let Some(n) = note { - super::add_progress_note(state, &msg.team_id, &msg.run_id, &n).await; + // What was read of each red pull request stopped in this invocation. + let mut reds: std::collections::HashMap = Default::default(); + loop { + match ledger.next(&seen) { + Next::Fix(url) => { + let Some(p) = ledger.entry(&url).cloned() else { + return Ok(()); + }; + let head = heads.get(&url).cloned().unwrap_or_default(); + let base = bases + .get(&url) + .cloned() + .unwrap_or_else(|| "main".to_string()); + let red = repo_red(&github, &p, &head).await; + let ctx = repo_fix_context(state, msg, run_record, &p, &base).await?; + let (owner, repo) = p.repo.split_once('/').unwrap_or_default(); + let pr_ref = PrRef { + owner, + repo, + branch: &p.branch, + number: p.number, + url: &p.url, + }; + // A mode CoderHelm's own commits dropped is put back first, + // as on a single repository's pull request, and CI decides + // again: not a round. + if let Some(done) = mode_cause( + state, + msg, + &ctx.ticket_msg, + &ctx.github, + &pr_ref, + &ctx.usage, + wall_clock_secs(created_at, start), + &events, + ) + .await + { + restore_primary(state, msg, run_record).await; + return done; + } + match ledger.begin(&url, &red.sig, MAX_CI_FIX_CYCLES as u32) { + Begin::Stop(why) => { + let p = ledger.entry(&url).cloned().unwrap_or(p); + warn!(run_id = %msg.run_id, pr = %url, reason = %why, "Multi-repo run: CI fix rounds on this pull request stop"); + stop_repo_rounds(state, msg, &github, &p, &head, &red, &why).await; + save_repo_ci(state, msg, &ledger).await; + reds.insert(url, red); + // The next red one, or the run's ending. + continue; + } + Begin::Go(number) => { + if !claim_for_round(state, msg).await { + info!(run_id = %msg.run_id, "Could not claim the run for a CI fix round, skipping"); + return Ok(()); + } + save_repo_ci(state, msg, &ledger).await; + mark_events_processed(state, &msg.run_id, &events).await; + super::record_ci_outcome( + state, + &msg.team_id, + &msg.run_id, + super::CiOutcome::FixAttempt, + ) + .await; + let mut feedback = format!( + "CI workflow failed on PR #{} (branch: {}) in {}. Fix the failures.\n\n\ + {CI_FIX_RULES}{}\n\nFailure summary:\n{}\n\nFull logs:\n{}", + p.number, + p.branch, + p.repo, + ledger.brief(&url).trim_start(), + red.excerpt, + red.logs + ); + // The same failure met again: this round is told what + // the last one concluded and takes another approach. + let idle = ledger.entry(&url).map_or(0, |e| e.idle); + if idle > 0 { + let last = + run_text(state, &msg.team_id, &msg.run_id, "last_fix_account") + .await; + let gap = common::content_gap::names_gap(&format!( + "{}\n{}", + red.excerpt, red.logs + )); + feedback.push_str(&common::content_gap::repeat_brief( + idle, + &last, + gap.as_ref(), + )); + } + feedback.push_str(common::content_gap::CAUSE_ASK); + feedback.push_str(common::red_reach::ASK); + // A round that didn't finish on this head left its + // work on its WIP branch: this one goes on from it. + let carried = super::round::carried(&github, owner, repo, &p.branch).await; + if !carried.is_empty() { + feedback = format!("{feedback}\n\n{}", super::round::CONTINUING); + } + let mut round = run_round::Round::start( + run_round::Kind::CiFix, + number, + &head, + &feedback, + true, + chrono::Utc::now(), + ); + round.wip_branch = carried; + info!(run_id = %msg.run_id, pr = %url, number, "Multi-repo run: CI fix round on this pull request"); + return run_repo_round( + state, + msg, + run_record, + &mut ledger, + (&p, ctx, round), + created_at, + start, + ) + .await; + } + } + } + Next::Wait(waiting) => { + save_repo_ci(state, msg, &ledger).await; + info!(run_id = %msg.run_id, waiting = ?waiting, "Multi-repo run: CI still running, or waiting on the repositories it builds on — checking again later"); + send_delayed_resume(state, msg, 120).await; + return Ok(()); + } + Next::Done => { + info!(run_id = %msg.run_id, prs = ledger.prs.len(), "Multi-repo run: CI green on every pull request — completing"); + save_repo_ci(state, msg, &ledger).await; + ready_in_merge_order(state, msg, &github, &ledger, &seen).await; + mark_events_processed(state, &msg.run_id, &events).await; + set_run_complete(state, &msg.team_id, &msg.run_id, created_at).await; + return Ok(()); + } + Next::Settled { stopped, person } => { + save_repo_ci(state, msg, &ledger).await; + ready_in_merge_order(state, msg, &github, &ledger, &seen).await; + mark_events_processed(state, &msg.run_id, &events).await; + let held = ledger.lines(&person, |p| format!("{}: {}", p.url, p.person)); + if let Some(url) = stopped.first() { + // CoderHelm's own stop, already recorded as its own + // problem: the run ends with its typed stop and the + // checks named, never a person's to-do. + let Some(p) = ledger.entry(url).cloned() else { + return Ok(()); + }; + let head = heads.get(url).cloned().unwrap_or_default(); + let red = match reds.remove(url) { + Some(r) => r, + None => repo_red(&github, &p, &head).await, + }; + let base = bases + .get(url) + .cloned() + .unwrap_or_else(|| "main".to_string()); + let ctx = repo_fix_context(state, msg, run_record, &p, &base).await?; + let (owner, repo) = p.repo.split_once('/').unwrap_or_default(); + let mut context = ledger.lines(&stopped, |e| e.stopped.clone()).join(". "); + if !held.is_empty() { + context.push_str(&format!(". Only a person can clear {}", held.join("; "))); + } + let tried = vec![format!("{} CI fix round(s) on {}", p.rounds, p.label())]; + return stop_red( + state, + &ctx.ticket_msg, + &msg.run_id, + &github, + &PrRef { + owner, + repo, + branch: &p.branch, + number: p.number, + url: &p.url, + }, + (&red.checks, &red.excerpt, &tried), + &context, + &ctx.usage, + wall_clock_secs(created_at, start), + ) + .await; + } + // Only a typed person-only reason keeps these red: the run + // says so, named, and nothing else. + info!(run_id = %msg.run_id, held = ?held, "Multi-repo run: what is left red waits on a person-only reason"); + super::add_progress_note( + state, + &msg.team_id, + &msg.run_id, + &format!( + "CI is green on every other pull request of this run. Only a person can \ + clear what keeps the rest red: {}. The ready decision holds each red one \ + while its checks fail.", + held.join("; ") + ), + ) + .await; + set_run_complete(state, &msg.team_id, &msg.run_id, created_at).await; + return Ok(()); + } } - for (o, n, num) in &open { - mark_pr_ready(state, &msg.team_id, &github, o, n, *num).await; + } +} + +/// What a red pull request's CI says: its failing checks, their logs (the +/// failing step's own output, the checks' annotations and what CI +/// reporters posted), the one line that names the failure, and that +/// failure's signature (as the single repository loop reads it). +struct RepoRed { + checks: Vec, + logs: String, + excerpt: String, + sig: String, +} + +async fn repo_red(github: &GitHubClient, p: &common::repo_ci::PrCi, head: &str) -> RepoRed { + let (owner, repo) = p.repo.split_once('/').unwrap_or_default(); + let git_ref = if head.is_empty() { &p.branch } else { head }; + let failing = failing_now(github, owner, repo, git_ref).await; + let checks: Vec = failing + .iter() + .map(|(c, w)| w.clone().unwrap_or_else(|| c.name.clone())) + .collect::>() + .into_iter() + .collect(); + let run_ids: std::collections::BTreeSet = failing + .iter() + .filter_map(|(c, _)| c.workflow_run_id) + .collect(); + let mut all = Vec::new(); + for id in &run_ids { + match github.get_workflow_run_logs(owner, repo, *id).await { + Ok(l) => all.push(focus_failing_log(&l, MAX_LOG_CHARS / run_ids.len().max(1))), + Err(e) => { + warn!(owner, repo, workflow_run_id = id, error = %e, "Could not read a failing job's log") + } } - mark_events_processed(state, &msg.run_id, &events).await; - set_run_complete(state, &msg.team_id, &msg.run_id, created_at).await; + } + let logs = ci_evidence( + github, + owner, + repo, + &p.branch, + p.number, + &all.join("\n\n--- Next workflow ---\n\n"), + ) + .await; + let excerpt = failure_excerpt(&logs); + let sig = ci_failure_signature(&format!("{}\n{excerpt}\n{logs}", checks.join("\n"))); + RepoRed { + checks, + logs, + excerpt, + sig, + } +} + +/// The base branch of a pull request of the run. +async fn pr_base(github: &GitHubClient, p: &common::repo_ci::PrCi) -> String { + let (owner, repo) = p.repo.split_once('/').unwrap_or_default(); + github + .get_pull_request(owner, repo, p.number) + .await + .ok() + .and_then(|pr| pr["base"]["ref"].as_str().map(str::to_string)) + .unwrap_or_else(|| "main".to_string()) +} + +/// What a round on one pull request of the run works with: its repository, +/// with the run's ticket. +async fn repo_fix_context( + state: &WorkerState, + msg: &ResumeMessage, + run_record: &RunRecord, + p: &common::repo_ci::PrCi, + base: &str, +) -> Result> { + let text = |k: &str| { + run_record + .get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() }; - if !failed.is_empty() { - info!(run_id = %msg.run_id, failed = ?failed, "Multi-repo run: CI failed — finishing with the failing checks named"); - finish(Some(format!( - "CI failed on {}. CoderHelm fixes CI one repository at a time and this run spans several, so it finished with the pull requests open; the ready decision holds each one while its checks fail.", - failed.join(", ") - ))) - .await; - return Ok(()); + let issue_number = run_record + .get("issue_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + let (owner, repo) = p.repo.split_once('/').unwrap_or_default(); + fix_context( + state, + msg, + run_record, + &FixTarget { + owner, + repo, + base_branch: base, + ticket_id: &text("ticket_id"), + title: &text("title"), + issue_number, + }, + ) + .await +} + +/// Runs one CI fix round on one pull request of the run (`run_fix_round`, +/// the round every CI fix takes) and keeps what it came to on that pull +/// request's entry. A round that changed no code and found the fix needs a +/// GitHub permission only a person grants holds that pull request for them +/// (`common::red_reach`, typed by `common::person_only::admit`); any other +/// round is read by CI on its head next. +async fn run_repo_round( + state: &WorkerState, + msg: &ResumeMessage, + run_record: &RunRecord, + ledger: &mut common::repo_ci::RepoCi, + (p, mut ctx, round): (&common::repo_ci::PrCi, FixContext, run_round::Round), + created_at: Option>, + start: &std::time::Instant, +) -> Result<(), Box> { + let (owner, repo) = p.repo.split_once('/').unwrap_or_default(); + let pr = PrRef { + owner, + repo, + branch: &p.branch, + number: p.number, + url: &p.url, + }; + let mut refused = Vec::new(); + let end = run_fix_round( + state, + msg, + &mut ctx, + &pr, + round, + &mut refused, + created_at, + start, + ) + .await; + // The record names its primary pull request again: a round that + // waited wrote this one's number and branch. + restore_primary(state, msg, run_record).await; + match end? { + // Parked for a fresh step: the round stays this pull request's. + RoundEnd::Parked => { + save_repo_ci(state, msg, ledger).await; + return Ok(()); + } + RoundEnd::Limited(why) => { + ledger.after_round(&p.url); + save_repo_ci(state, msg, ledger).await; + return super::end_at_usage_limit( + state, + &ctx.ticket_msg, + &msg.run_id, + &why, + &ctx.usage, + wall_clock_secs(created_at, start), + ) + .await; + } + RoundEnd::Done { files: 0 } => { + let account = run_text(state, &msg.team_id, &msg.run_id, "last_fix_account").await; + let reach = common::red_reach::after_round( + &common::red_reach::Red { + repo: &p.repo, + ..Default::default() + }, + &account, + ); + if let common::red_reach::Reach::Permission { grant, what } = reach { + use common::person_only::{admit, Grantor, Want}; + match admit( + Want::Grant(Grantor::RepoAdmin), + &format!("{grant} for the GitHub App on {}, to {what}", p.repo), + ) { + Ok(person) => ledger.hold_for_person(&p.url, &person), + // Words that name what CoderHelm owns: its own problem, + // and the bound decides its next round. + Err(own) => { + super::own_problems::record(state, &msg.team_id, &msg.run_id, &own).await + } + } + } + ledger.after_round(&p.url); + } + RoundEnd::Done { .. } => { + super::record_ci_outcome( + state, + &msg.team_id, + &msg.run_id, + super::CiOutcome::FixCommitted, + ) + .await; + ledger.after_round(&p.url); + } + // A round at a dead end: CI on the head says whether anything moved, + // and the bound decides the next one. + RoundEnd::Incomplete => ledger.after_round(&p.url), } - if waiting.is_empty() { - info!(run_id = %msg.run_id, prs = n_open, "Multi-repo run: CI green on every pull request — completing"); - finish(None).await; - return Ok(()); + save_repo_ci(state, msg, ledger).await; + let waiting = set_run_awaiting_ci( + state, + &ctx.ticket_msg, + &msg.run_id, + &p.url, + p.number, + &p.branch, + &ctx.usage, + wall_clock_secs(created_at, start), + ) + .await; + restore_primary(state, msg, run_record).await; + if waiting? { + send_delayed_resume(state, msg, 120).await; } - info!(run_id = %msg.run_id, waiting = ?waiting, "Multi-repo run: CI still running — checking again later"); - send_delayed_resume(state, msg, 120).await; Ok(()) } +/// A pull request's CI fix rounds stopped: CoderHelm's own problem, typed +/// and alerted, and the pull request says what fails, with the checks and +/// the rounds it took. Never a person's to-do. +async fn stop_repo_rounds( + state: &WorkerState, + msg: &ResumeMessage, + github: &GitHubClient, + p: &common::repo_ci::PrCi, + head: &str, + red: &RepoRed, + why: &str, +) { + let gave_up = if p.idle > 0 { + super::GaveUp::Stalled + } else { + super::GaveUp::Budget + }; + if let Some(problem) = gave_up.own_problem(why) { + super::own_problems::record(state, &msg.team_id, &msg.run_id, &problem).await; + } + let (owner, repo) = p.repo.split_once('/').unwrap_or_default(); + let tried = vec![format!("{} CI fix round(s) on this pull request", p.rounds)]; + let section = ci_failing_section(head, &red.checks, &red.excerpt, &tried, why); + match github.get_pull_request(owner, repo, p.number).await { + Ok(pr) => { + let body = with_ci_failing(pr["body"].as_str().unwrap_or(""), §ion); + if let Err(e) = + crate::passes::description::save(github, owner, repo, p.number, &body).await + { + warn!(run_id = %msg.run_id, error = %e, "Could not write what fails on the pull request"); + } + } + Err(e) => { + warn!(run_id = %msg.run_id, error = %e, "Could not read the pull request to say what fails") + } + } +} + +/// Every open pull request of the run goes through the one ready decision, +/// in the plan's order (the merge order): a green one is offered, a red +/// one stays a draft with what fails named. +async fn ready_in_merge_order( + state: &WorkerState, + msg: &ResumeMessage, + github: &GitHubClient, + ledger: &common::repo_ci::RepoCi, + seen: &std::collections::HashMap, +) { + use common::repo_ci::Ci; + for p in &ledger.prs { + if matches!(seen.get(&p.url), Some(Ci::Merged | Ci::Closed)) { + continue; + } + if let Some((owner, repo)) = p.repo.split_once('/') { + mark_pr_ready(state, &msg.team_id, github, owner, repo, p.number).await; + } + } +} + +/// Keeps the ledger on the run record (`common::repo_ci::FIELD`). +async fn save_repo_ci(state: &WorkerState, msg: &ResumeMessage, ledger: &common::repo_ci::RepoCi) { + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(&msg.run_id)) + .condition_expression("attribute_exists(run_id)") + .update_expression("SET #f = :v") + .expression_attribute_names("#f", common::repo_ci::FIELD) + .expression_attribute_values(":v", attr_s(&ledger.to_json())) + .send() + .await + { + warn!(run_id = %msg.run_id, error = %e, "Could not keep the run's CI ledger"); + } +} + +/// A round on one pull request of a run that spans several repositories +/// waits with that pull request's number and branch on the record +/// (`set_run_awaiting_ci`): the record's `pr_url`, `pr_number` and `branch` +/// are put back to its primary pull request's (`common::run_prs::primary`), +/// so they keep describing one pull request with its `repo`. +async fn restore_primary(state: &WorkerState, msg: &ResumeMessage, run_record: &RunRecord) { + let text = |k: &str| { + run_record + .get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let url = text("pr_url"); + let number = run_record + .get("pr_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + if url.is_empty() || number == 0 { + return; + } + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(&msg.run_id)) + .condition_expression("attribute_exists(run_id)") + .update_expression("SET pr_url = :u, pr_number = :n, branch = :b") + .expression_attribute_values(":u", attr_s(&url)) + .expression_attribute_values(":n", attr_n(number)) + .expression_attribute_values(":b", attr_s(&text("branch"))) + .send() + .await + { + warn!(run_id = %msg.run_id, error = %e, "Could not put the run's primary pull request back on its record"); + } +} + /// The CI wait kept for the pull request's current head while something /// else (an outside step) holds the run: a head with nothing pending /// replaces whatever an older head left (its pending checks are dropped); @@ -11264,6 +11855,8 @@ pub(crate) fn poll_delay( } } +/// Send a delayed resume message to the CI fix queue. +/// `delay_seconds` can be 0 (immediate) or up to 900 (15 min, SQS max). async fn send_delayed_resume(state: &WorkerState, msg: &ResumeMessage, delay_seconds: i32) { let delay_seconds = poll_delay( delay_seconds,