diff --git a/docs/incidents/xu_every_repo_gets_its_ci_rounds.md b/docs/incidents/xu_every_repo_gets_its_ci_rounds.md index 47cdd9a8..96a7d8eb 100644 --- a/docs/incidents/xu_every_repo_gets_its_ci_rounds.md +++ b/docs/incidents/xu_every_repo_gets_its_ci_rounds.md @@ -7,9 +7,9 @@ **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. +- **A red pull request gets the same round a single repository gets.** The mode diagnosis first (`read_modes`, `mode_repair::on_red`, the same one the single repository loop's `mode_cause` uses): a mode CoderHelm's own commits dropped is put back and CI decides again. Its stuck record is that pull request's own, and a repair that is retried or stops making progress marks only that pull request: the step goes on to the others, and a stopped repair settles it as CoderHelm's own problem. 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. +**Where it's enforced:** `common::repo_ci::{RepoCi::of, next, begin, stop, keep_mode, after_round, hold_for_person, brief}`, the worker's `resume::{resume_multi_repo, read_modes, 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/repo_ci.rs b/services/common/src/repo_ci.rs index 6a1f5d46..d7d8f5ec 100644 --- a/services/common/src/repo_ci.rs +++ b/services/common/src/repo_ci.rs @@ -68,6 +68,11 @@ pub struct PrCi { /// That reason's code ([`crate::person_only::PersonOnly::code`]). #[serde(default, skip_serializing_if = "String::is_empty")] pub person_code: String, + /// The mode repair's stuck record for this pull request (the worker's + /// `mode_repair::StuckState`, as JSON): its tries count for it alone. + /// Empty when nothing is stuck. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub mode_stuck: String, } impl PrCi { @@ -272,9 +277,7 @@ impl RepoCi { ) }; let why = p.stopped.clone(); - if self.fixing == url { - self.fixing.clear(); - } + self.after_round(url); return Begin::Stop(why); } p.rounds += 1; @@ -284,6 +287,22 @@ impl RepoCi { Begin::Go(n) } + /// `url`'s work stops as CoderHelm's own problem, in these words: no + /// more rounds go to it, and the others go on. + pub fn stop(&mut self, url: &str, why: &str) { + if let Some(e) = self.entry_mut(url) { + e.stopped = why.to_string(); + } + self.after_round(url); + } + + /// Keeps `url`'s mode repair record (`stuck`, empty to clear it). + pub fn keep_mode(&mut self, url: &str, stuck: &str) { + if let Some(e) = self.entry_mut(url) { + e.mode_stuck = stuck.to_string(); + } + } + /// 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) { diff --git a/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs b/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs index 7303ea74..717ec5f6 100644 --- a/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs +++ b/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs @@ -155,7 +155,13 @@ fn a_red_check_from_dropped_modes_is_fixed_by_a_mode_commit_not_handed_off() { ); // What the diagnosis does: a commit and a wait on CI, or CoderHelm's // own problem tried again; never a failed run. - let cause = fn_src(RESUME, "async fn mode_cause("); + // `mode_cause` acts on the diagnosis `read_modes` makes (the one + // the multi-repository loop shares). + let cause = format!( + "{}{}", + fn_src(RESUME, "async fn mode_cause("), + fn_src(RESUME, "async fn read_modes(") + ); for part in [ "mr::on_red(", "own_problems::record(", @@ -395,9 +401,9 @@ fn a_stuck_repair_retries_while_it_makes_progress_then_stops() { other => panic!("{other:?}"), } - let cause = fn_src(RESUME, "async fn mode_cause("); - assert!(cause.contains("mr::stuck_step(")); - assert!(cause.contains("if retry && matches!(waiting, Ok(true))")); + assert!(fn_src(RESUME, "async fn read_modes(").contains("mr::stuck_step(")); + assert!(fn_src(RESUME, "async fn mode_cause(") + .contains("if read == ModeRead::Retry && matches!(waiting, Ok(true))")); let sweep = fn_src(REPAIR, "pub async fn sweep("); let raced = sweep.find("if r.raced {").expect("a raced repair"); assert!(sweep[raced..].find("release(state, &c)").unwrap() < 200); diff --git a/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs b/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs index 234d43e5..d845fd05 100644 --- a/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs +++ b/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs @@ -319,15 +319,10 @@ fn no_pr_work_is_limited_to_one_repository() { } let text = std::fs::read_to_string(&f).unwrap_or_default(); let low = text.to_lowercase(); + // No exception: a run spanning several repositories fixes CI on each + // of its pull requests (`xu`), so nothing says otherwise. for l in LIMITS { - // The one place that says how a run spanning several - // repositories ends when CI fails: it says so to people, true - // and named, rather than fixing them one by one. - let told = p.ends_with("/passes/resume.rs") - && low.contains( - "coderhelm fixes ci one repository at a time and this run spans several", - ); - if low.contains(l) && !(told && *l == "one repository at a time") { + if low.contains(l) { found.push(format!("{p}: {l}")); } } 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 index b2f1c1a1..48e91c73 100644 --- 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 @@ -13,8 +13,10 @@ //! //! 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 +//! repository takes (`read_modes`, then `run_fix_round` on its branch), +//! counted on its entry, and the run waits for CI on what it pushed. A +//! mode repair that is retried or stops making progress marks only its +//! own pull request; the step goes on to the others. 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 @@ -144,62 +146,76 @@ fn plan() -> Vec { vec![ORDERS.to_string(), SHOP.to_string()] } +/// A replayed run of the orders service's pull request and the +/// storefront's, as it ended. +struct Two { + api: RunPr, + web: RunPr, + ledger: RepoCi, + world: HashMap, + end: Ended, +} + +/// Replays a two-repository run: the orders service's and the +/// storefront's pull requests (`api`, `web`), in the plan's `order` (empty +/// when nothing builds on anything). +fn two(order: &[String], api: Repo, web: Repo) -> Two { + let (a, w) = (pr(ORDERS, 31), pr(SHOP, 52)); + let mut ledger = RepoCi::of(&[w.clone(), a.clone()], order, None); + let mut world = HashMap::from([(a.url.clone(), api), (w.url.clone(), web)]); + let end = replay(&mut ledger, &mut world); + Two { + api: a, + web: w, + ledger, + world, + end, + } +} + /// 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 t = two( + &plan(), + repo(Ci::Green, "", &[]), + 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)); + ); + assert_eq!(t.end.rounds, vec![t.web.url.clone()]); + assert_eq!(t.end.offered, vec![t.api.url.clone(), t.web.url.clone()]); + assert!(t.end.own.is_empty() && t.end.stopped.is_empty() && t.end.person.is_empty()); + assert!(t.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 t = two( + &[], + repo( + Ci::Red, + "orders.rs: mismatched types", + &[Some("orders_test.rs: price_cents missing"), None], ), - ]); - let end = replay(&mut ledger, &mut world); + repo(Ci::Red, "price.test.ts: expected 1299", &[None]), + ); // 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()] + t.end.rounds, + vec![t.web.url.clone(), t.api.url.clone(), t.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); + assert!(t.end.own.is_empty() && t.end.stopped.is_empty()); + assert!(t.world.values().all(|r| r.now == Ci::Merged)); + assert_eq!(t.ledger.entry(&t.api.url).unwrap().rounds, 2); + assert_eq!(t.ledger.entry(&t.web.url).unwrap().rounds, 1); } /// A pull request whose rounds keep meeting the same failure stops after @@ -208,39 +224,34 @@ fn both_red_both_get_their_rounds_and_go_green() { /// 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(); + let t = two( + &[], + repo(Ci::Red, "orders.rs: mismatched types", &[None]), + repo(Ci::Red, same, &[Some(same)]), + ); + let stuck = t.ledger.entry(&t.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")); + assert_eq!(t.end.rounds.iter().filter(|u| **u == t.web.url).count(), 2); + assert_eq!(t.end.stopped, vec![t.web.url.clone()]); + assert!(t.end.person.is_empty() && stuck.person.is_empty()); + assert_eq!(t.end.own.len(), 1); + let own = &t.end.own[0]; + assert!(own.contains("CoderHelm") && own.contains("its own dead end")); for words in ["a person", "you ", "manual", "hand"] { - assert!(!end.own[0].to_lowercase().contains(words), "{}", end.own[0]); + assert!(!own.to_lowercase().contains(words), "{own}"); } // The other repository was fixed meanwhile. - assert_eq!(world[&api.url].now, Ci::Green); + assert_eq!(t.world[&t.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(), + let t = two( + &[], + repo(Ci::Green, "", &[]), 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()); + ); + assert_eq!(t.end.rounds.len(), 4); + assert!(t.end.own.is_empty()); } /// The storefront builds on the orders service's change (the plan's @@ -249,38 +260,73 @@ fn a_stuck_pull_request_stops_after_the_bound_as_its_own_problem() { /// 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()]); + let t = two( + &plan(), + repo(Ci::Red, "orders.rs: price_cents not found", &[None]), + repo(Ci::Red, "api.ts: property price_cents missing", &[None]), + ); + assert_eq!(t.ledger.prs[1].after, vec![ORDERS.to_string()]); + assert_eq!(t.end.rounds, vec![t.api.url.clone(), t.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()]); + assert!(t.end.waits.iter().any(|w| w.contains(&t.web.url))); + assert_eq!(t.end.offered, vec![t.api.url.clone(), t.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); + let t = two( + &plan(), + repo(Ci::Red, "x", &[Some("x")]), + repo(Ci::Red, "y", &[None]), + ); + assert_eq!(t.end.stopped, vec![t.api.url.clone()]); + assert_eq!(t.world[&t.web.url].now, Ci::Green); + let web_first = t.end.rounds.iter().position(|u| *u == t.web.url).unwrap(); + let api_last = t.end.rounds.iter().rposition(|u| *u == t.api.url).unwrap(); + assert!(api_last < web_first, "{:?}", t.end.rounds); +} + +/// A mode repair on one pull request that is retried or stops making +/// progress marks only that pull request: the step goes on to the other +/// red one, and a stopped repair settles its pull request as CoderHelm's +/// own problem. Its stuck record is that pull request's own. +#[test] +fn a_stuck_mode_repair_holds_only_its_own_pull_request() { + let (api, web) = (pr(ORDERS, 31), pr(SHOP, 52)); + let mut ledger = RepoCi::of(&[api.clone(), web.clone()], &[], None); + let both_red = HashMap::from([(api.url.clone(), Ci::Red), (web.url.clone(), Ci::Red)]); + assert_eq!(ledger.next(&both_red), Next::Fix(api.url.clone())); + // A retry: the repaired one waits for its next look, the other goes. + ledger.keep_mode( + &api.url, + r#"{"tries":1,"paths":["bin/ship.sh"],"why":"x","stopped":false}"#, + ); + let retried = HashMap::from([(api.url.clone(), Ci::Pending), (web.url.clone(), Ci::Red)]); + assert_eq!(ledger.next(&retried), Next::Fix(web.url.clone())); + assert!(ledger.entry(&web.url).unwrap().mode_stuck.is_empty()); + // Stopped: that one settles as CoderHelm's own stop, the other goes on. + ledger.stop( + &api.url, + "acme/orders-api#31: CoderHelm could not put back a mode its commits dropped", + ); + assert_eq!(ledger.next(&both_red), Next::Fix(web.url.clone())); + let web_green = HashMap::from([(api.url.clone(), Ci::Red), (web.url.clone(), Ci::Green)]); + assert_eq!( + ledger.next(&web_green), + Next::Settled { + stopped: vec![api.url.clone()], + person: vec![] + } + ); + assert!(ledger.entry(&api.url).unwrap().person.is_empty()); + // The worker acts on it so: no early end of the step on a mode repair. + let start = RESUME.find("\nasync fn resume_multi_repo(").unwrap(); + let end = start + RESUME[start..].find("\nstruct RepoRed").unwrap(); + let multi = &RESUME[start..end]; + assert!(multi.contains("read_modes(")); + assert!(multi.contains("ledger.keep_mode(")); + assert!(multi.contains("ledger.stop(")); + assert!(!multi.contains("mode_cause(")); + assert!(!multi.contains("return done")); } /// Only a typed person-only reason holds a red pull request for a person; @@ -333,8 +379,10 @@ fn the_multi_repository_loop_runs_rounds_through_the_ledger() { "RepoCi::of(", "ledger.next(&seen)", "ledger.begin(", - "mode_cause(", - "run_repo_round(", + "read_modes(", + "run_fix_round(", + "hold_for_person(", + "person_only::{admit", "stop_repo_rounds(", "stop_red(", "ready_in_merge_order(", @@ -342,10 +390,8 @@ fn the_multi_repository_loop_runs_rounds_through_the_ledger() { ] { 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")); + // No second round runner beside `run_fix_round`. + assert!(!RESUME.contains("fn run_repo_round(")); 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")); @@ -357,3 +403,51 @@ fn the_multi_repository_loop_runs_rounds_through_the_ledger() { // The single repository loop and these rounds read the same rules. assert_eq!(RESUME.matches("{CI_FIX_RULES}").count(), 2); } + +/// What a round works with can fail to build (the team's model settings or +/// GitHub not answering). It is built before the round is claimed or +/// counted, so a failure leaves the run waiting and the ledger as it was, +/// and the next step picks the same pull request again with nothing spent. +#[test] +fn a_context_that_fails_to_build_leaves_the_step_to_run_again() { + let (api, web) = (pr(ORDERS, 31), pr(SHOP, 52)); + let ledger = RepoCi::of(&[api.clone(), web.clone()], &plan(), None); + let seen = HashMap::from([(api.url.clone(), Ci::Green), (web.url.clone(), Ci::Red)]); + // The step picks the storefront; its context fails, so `begin` never + // ran and nothing is saved: the next step reads the same ledger and + // picks it again, with no round counted. + assert_eq!(ledger.next(&seen), Next::Fix(web.url.clone())); + let kept = RepoCi::from_json(&ledger.to_json()).unwrap(); + let again = RepoCi::of(&[api, web.clone()], &plan(), Some(&kept)); + assert_eq!(again.next(&seen), Next::Fix(web.url.clone())); + let e = again.entry(&web.url).unwrap(); + assert_eq!((e.rounds, e.idle), (0, 0)); + assert!(again.fixing.is_empty()); + + // The worker builds it first, retries on failure, and never strands + // the run with a `?` after the claim. + let start = RESUME.find("\nasync fn resume_multi_repo(").unwrap(); + let end = start + RESUME[start..].find("\nstruct RepoRed").unwrap(); + let multi = &RESUME[start..end]; + assert!( + !multi.contains("repo_fix_context("), + "built only through context_or_retry" + ); + let builds: Vec = multi + .match_indices("context_or_retry(") + .map(|(i, _)| i) + .collect(); + let claims: Vec = multi + .match_indices("claim_for_round(") + .map(|(i, _)| i) + .collect(); + assert_eq!(claims.len(), 2); + // The parked round's context comes before its claim; the new round's + // before `begin` counts it and before its claim. + assert!(builds[0] < claims[0]); + let begin = multi.find("ledger.begin(").unwrap(); + assert!(builds[1] < begin && begin < claims[1]); + let retry = super::fixture::fn_src(RESUME, "\nasync fn context_or_retry("); + assert!(retry.contains("send_delayed_resume(")); + assert!(!retry.contains('?')); +} diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 908d3309..5f41ad5c 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -10573,23 +10573,71 @@ async fn mode_cause( .ok()?["base"]["ref"] .as_str()? .to_string(); + let prev = read_stuck(state, &msg.team_id, &msg.run_id).await; + let (read, keep) = read_modes(state, msg, github, pr, &base, prev.as_ref()).await; + if read == ModeRead::Nothing { + return None; + } + save_stuck(state, &msg.team_id, &msg.run_id, keep.as_ref()).await; + mark_events_processed(state, &msg.run_id, events).await; + let waiting = set_run_awaiting_ci( + state, + ticket_msg, + &msg.run_id, + pr.url, + pr.number, + pr.branch, + usage, + duration, + ) + .await; + if read == ModeRead::Retry && matches!(waiting, Ok(true)) { + send_delayed_resume(state, msg, 300).await; + } + Some(waiting.map(|_| ())) +} + +/// What a mode diagnosis came to, for either CI loop. +#[derive(Debug, Clone, PartialEq, Eq)] +enum ModeRead { + /// CoderHelm dropped no mode on the branch. + Nothing, + /// The modes were put back in one commit: CI decides again on it. + Fixed, + /// Modes CoderHelm dropped and couldn't put back yet: tried again + /// later while the tries make progress. + Retry, + /// Its tries made no progress: it stopped retrying, with why. Its own + /// problem, recorded once. + Stopped(String), +} + +/// Diagnoses a red pull request's modes against `base` and puts back what +/// CoderHelm's own commits dropped (`mode_repair::on_red`), with `prev` the +/// pull request's stuck record. Returns what it came to and the stuck +/// record to keep (`None` clears it). A stuck repair is CoderHelm's own +/// problem, alerted and on the run page, never a person's. +async fn read_modes( + state: &WorkerState, + msg: &ResumeMessage, + github: &GitHubClient, + pr: &PrRef<'_>, + base: &str, + prev: Option<&super::mode_repair::StuckState>, +) -> (ModeRead, Option) { use super::mode_repair::{self as mr, ModeFix, StuckStep}; - // Retry: another look in a while. A stop is still CoderHelm's own - // problem: the run waits on CI, never on a person. - let mut retry = false; - match mr::on_red(github, pr.owner, pr.repo, &base, pr.branch).await { - ModeFix::Nothing => return None, + match mr::on_red(github, pr.owner, pr.repo, base, pr.branch).await { + ModeFix::Nothing => (ModeRead::Nothing, prev.cloned()), ModeFix::Fixed(note) => { super::add_progress_note(state, &msg.team_id, &msg.run_id, ¬e).await; - save_stuck(state, &msg.team_id, &msg.run_id, None).await; + (ModeRead::Fixed, None) } ModeFix::Stuck { why, paths } => { - let prev = read_stuck(state, &msg.team_id, &msg.run_id).await; let own = |text: String| common::person_only::OwnProblem { subject: common::person_only::OwnSubject::Tooling, text, }; - match mr::stuck_step(prev.as_ref(), paths, why) { + match mr::stuck_step(prev, paths, why) { StuckStep::Retry(s) => { let p = own(format!( "{} (try {} of {})", @@ -10598,39 +10646,28 @@ async fn mode_cause( mr::MAX_STUCK_TRIES )); super::own_problems::record(state, &msg.team_id, &msg.run_id, &p).await; - save_stuck(state, &msg.team_id, &msg.run_id, Some(&s)).await; - retry = true; + (ModeRead::Retry, Some(s)) } StuckStep::Stop { state: s, first } => { + let why = format!( + "{}. {} tries made no progress, so CoderHelm stopped retrying", + s.why, + mr::MAX_STUCK_TRIES + ); if first { - let p = own(format!( - "{}. {} tries made no progress, so CoderHelm stopped retrying", - s.why, - mr::MAX_STUCK_TRIES - )); - super::own_problems::record(state, &msg.team_id, &msg.run_id, &p).await; + super::own_problems::record( + state, + &msg.team_id, + &msg.run_id, + &own(why.clone()), + ) + .await; } - save_stuck(state, &msg.team_id, &msg.run_id, Some(&s)).await; + (ModeRead::Stopped(why), Some(s)) } } } } - mark_events_processed(state, &msg.run_id, events).await; - let waiting = set_run_awaiting_ci( - state, - ticket_msg, - &msg.run_id, - pr.url, - pr.number, - pr.branch, - usage, - duration, - ) - .await; - if retry && matches!(waiting, Ok(true)) { - send_delayed_resume(state, msg, 300).await; - } - Some(waiting.map(|_| ())) } /// A stuck mode repair's record on the run (`mode_repair::StuckState`). @@ -10787,7 +10824,8 @@ async fn claim_for_round(state: &WorkerState, msg: &ResumeMessage) -> bool { /// 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), +/// first, `read_modes`, with a stuck record of its own; 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 @@ -10831,139 +10869,153 @@ async fn resume_multi_repo( 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(()); + // The round this step runs: a round parked for one of them first, with + // its whole budget; else the next red one's (`RepoCi::next`). + let (p, mut ctx, round) = 'pick: { + 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() { + let base = pr_base(&github, &p).await; + let Some(ctx) = context_or_retry(state, msg, run_record, &p, &base).await else { + return Ok(()); + }; + 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(()); + } + info!(run_id = %msg.run_id, pr = %p.url, "Multi-repo run: running a parked CI fix round"); + break 'pick (p, ctx, pending.resumed(chrono::Utc::now())); } - 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, p.number).await { - Ok(pr) => pr, - Err(e) => { - 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); + 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, p.number).await { + Ok(pr) => pr, + Err(e) => { + 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; } - }; - 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(); - 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, p.number).await; - Ci::Green - } - 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(); - // 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; + let head = pr["head"]["sha"].as_str().unwrap_or("").to_string(); + 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, p.number).await; + Ci::Green } - 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; + 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(); + // 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 (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: not a round. Its + // stuck record is this pull request's own, and whatever the + // repair came to, the step goes on to the others: CI runs on + // a restore commit, a retry waits for the next look, and a + // repair that stopped making progress stops this pull + // request's work as CoderHelm's own problem. + let prev = serde_json::from_str(&p.mode_stuck).ok(); + let (read, keep) = + read_modes(state, msg, &github, &pr_ref, &base, prev.as_ref()).await; + if read != ModeRead::Nothing { + ledger.keep_mode( + &url, + &keep + .and_then(|k| serde_json::to_string(&k).ok()) + .unwrap_or_default(), + ); } - 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(()); + match read { + ModeRead::Nothing => {} + ModeRead::Fixed | ModeRead::Retry => { + seen.insert(url, Ci::Pending); + save_repo_ci(state, msg, &ledger).await; + continue; } - 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!( + ModeRead::Stopped(why) => { + warn!(run_id = %msg.run_id, pr = %url, reason = %why, "Multi-repo run: the mode repair on this pull request stopped"); + ledger.stop(&url, &format!("{}: {why}", p.label())); + save_repo_ci(state, msg, &ledger).await; + continue; + } + } + // What the round works with is built before anything + // is claimed or counted: a failure here leaves the run + // waiting and the ledger as it was, and the next step + // picks the same pull request again. + let Some(ctx) = context_or_retry(state, msg, run_record, &p, &base).await + else { + return Ok(()); + }; + let red = repo_red(&github, &p, &head).await; + 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, @@ -10973,135 +11025,238 @@ async fn resume_multi_repo( 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(), - )); + // 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"); + break 'pick (p, ctx, round); } - 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); + } + } + 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 Some(ctx) = context_or_retry(state, msg, run_record, &p, &base).await + else { + return Ok(()); + }; + 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 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( + let tried = vec![format!("{} CI fix round(s) on {}", p.rounds, p.label())]; + return stop_red( state, - msg, - run_record, - &mut ledger, - (&p, ctx, round), - created_at, - start, + &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; } - } - } - 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( + // 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, - &ctx.ticket_msg, + &msg.team_id, &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!( + &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(()); + ) + .await; + set_run_complete(state, &msg.team_id, &msg.run_id, created_at).await; + return Ok(()); + } } } + }; + // The round every CI fix takes (`run_fix_round`), on this pull + // request's branch; what it came to is kept on its 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. + 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), } + 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; + } + Ok(()) } /// What a red pull request's CI says: its failing checks, their logs (the @@ -11168,6 +11323,27 @@ async fn pr_base(github: &GitHubClient, p: &common::repo_ci::PrCi) -> String { .unwrap_or_else(|| "main".to_string()) } +/// [`repo_fix_context`], or `None` when it can't be built now (the team's +/// model settings or GitHub didn't answer): nothing is claimed or counted +/// yet, the run stays waiting, and a resume shortly tries the same step +/// again. Never an error that leaves the run stranded. +async fn context_or_retry( + state: &WorkerState, + msg: &ResumeMessage, + run_record: &RunRecord, + p: &common::repo_ci::PrCi, + base: &str, +) -> Option { + match repo_fix_context(state, msg, run_record, p, base).await { + Ok(ctx) => Some(ctx), + Err(e) => { + warn!(run_id = %msg.run_id, pr = %p.url, error = %e, "Multi-repo run: could not build what the round works with — trying the step again shortly"); + send_delayed_resume(state, msg, 120).await; + None + } + } +} + /// What a round on one pull request of the run works with: its repository, /// with the run's ticket. async fn repo_fix_context( @@ -11206,121 +11382,6 @@ async fn repo_fix_context( .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), - } - 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; - } - 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.