diff --git a/docs/incidents.md b/docs/incidents.md index 7bc930c9b..fd64dcd99 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -61,6 +61,7 @@ pipeline still calls it there. | ad. `ad_hand_back_reply` | A coder ended its step with "I couldn't finish, please complete the remaining tasks manually". Nothing it lacked was a credential, access, a product decision, an ambiguous ticket or an approval; its words alone handed the work to a person. | A model reply that hands the work back for a reason not on the human-only list is not an ending: the implement pass tells the coder to change its approach and runs it again, and a reply that still changes nothing is a step without progress, which climbs the supervisor's ladder (one task, other tools, a re-split, the strongest model, then the stuck task deferred with its reason) until the run finishes with what is done. Only a reply naming something on the list makes a hand-back. Every coder's system prompt carries the same stance (`ownership::coder_stance`), and a source scan fails on a hand-off phrase in any prompt or message (`ownership`). | | ae. `ae_budget_rounds` | Two loops of fix rounds still stopped on their own budget after the supervisor took every other ending. At eight automatic pushes the CI-only rounds on a finished run's pull request marked it ready, completed the run with its checks red and said a comment naming a change would start the next round, even while each round turned another red check green; at two rounds the self-review on CoderHelm's own pull request said the same and left its findings holding the draft, even while each round closed one. | Both loops follow `supervisor::next_round`: rounds go on while they make progress (checks that were red turn green, findings close), past the cap up to twice it and below the spend ceiling; a round without progress changes approach (one item, a fresh context with small edits, a re-split, the strongest model). When the rounds end, the findings left move to "Deferred" with the reason and stop holding the draft, and the run finishes; red checks are reverted to the last green head and deferred, or, when nothing can come out, the run fails with what fails and why. No message asks for a comment to go on: the phrases are on the `ownership` hand-off list. | | af. `af_lockfiles_out_of_sync` | A security update's pull request changed three `package.json` files (a pnpm workspace root and two npm packages with their own lockfiles) and none of the lockfiles, so every CI job failed at its frozen install. A retry planned its bumps by rule, then handed the red pull request to a model instead of building the plan. The model changed nothing; landing "nothing" removed the round's work branch, so the next attempt wrote to a branch that was gone (every write a 404, a hand edit of a lockfile among them). The round was called unfinished and the run ended failed after one attempt of three, with the same vague sentence twice. | A lockfile out of sync with its manifest is repaired by code before any model round, for any ticket and every package manager CoderHelm writes lockfiles for: each manager writes its own lockfile in the sandbox (with another mode and the LTS Node as fallbacks), one commit, and one that can't be written never hides the others. Any run that changes a manifest gets its lockfile written before the pull request opens. A retry of a dependency fix rebuilds its change from its plan on the same branch. A model's write to a lockfile is refused and pointed to the regenerate tool. Every attempt of a CI fix round opens its work branch first; a fault inside the round (no work branch, a compare or push GitHub refuses, a sandbox failure, anything else) is classified and has a way around it, and the catch-all runs the round again from a clean state, then once in a fresh step, before the supervisor's ending is asked. An attempt that changed nothing is followed by the repairs by code, then fresh evidence, then the strongest model. A run about to complete with red checks goes back to its CI fix round first, and an ending for red checks names the recorded cause, once. | +| ag. `ag_red_ci_ships_what_passes` | Three ways were left for a run to end badly over red checks or a refused landing. A dependency fix whose CI stayed red was taken apart by planned task (one task per lockfile, so a lockfile went back without its manifest), and after three reverts the run ended failed with bumps left in that passed on their own. A run stopped after its work opened its pull request with manifests changed and lockfiles unwritten, and waited for CI to fail first. A review fix or feedback round whose finished work GitHub refused to land was recorded as unfinished at once. | Red checks after every fix take out only what breaks them. A dependency fix takes out its newest commit of verified bumps, defers those bumps with what CI printed, holds their findings out of later bundles and keeps the commits before it, again while CI stays red, never emptying the pull request. Any other run is taken apart task by task (up to eight reverts) down to the part that passes; what ships is green with the rest under "Deferred". A stopped run's lockfiles are written by their package managers before its pull request opens, and one that can't be written is named without stopping it. Every kind of fix round takes one classified decision about a fault (`round::plan_for_fault`): while it may continue it runs again in a fresh step, keeping its work when only the landing failed and starting from the pull request's head otherwise. | ## Adding a case diff --git a/services/common/src/dep_fix.rs b/services/common/src/dep_fix.rs index 676d0ba9b..fb6ece5f9 100644 --- a/services/common/src/dep_fix.rs +++ b/services/common/src/dep_fix.rs @@ -1049,6 +1049,45 @@ pub struct DepRun { pub budget_stop: bool, pub uses: Vec, pub done: bool, + /// Each commit of verified bumps on the branch, oldest first: what the + /// pull request's own CI can take out again, one at a time + /// ([`DepRun::take_out_last_commit`]). + pub commits: Vec, +} + +/// One commit of verified bumps. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct BatchCommit { + /// The head the commit was made on: its files are the branch without + /// this commit and everything after it. + pub before: String, + pub head: String, + pub bumps: Vec, +} + +/// What [`DepRun::take_out_last_commit`] took out. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TakenOut { + /// The head whose files the branch goes back to. + pub restore_to: String, + /// Each bump taken out, as its deferral line. + pub lines: Vec, +} + +/// Why a bump the sandbox verified is deferred after all: the pull +/// request's own CI failed with it applied. `failure` is what CI printed. +pub fn ci_deferral_reason(failure: &str) -> String { + let failure = failure.trim(); + if failure.is_empty() { + "the pull request's CI failed with it applied; taken out so the bumps before it ship" + .to_string() + } else { + format!( + "the pull request's CI failed with it applied ({}); taken out so the bumps before it ship", + crate::truncate_str(failure, 300) + ) + } } impl DepRun { @@ -1421,6 +1460,13 @@ impl DepRun { if let Some(u) = self.uses.get_mut(self.batch) { u.applied += g.bumps.len(); } + if head != self.head { + self.commits.push(BatchCommit { + before: self.head.clone(), + head: head.to_string(), + bumps: g.bumps.clone(), + }); + } self.applied.extend(g.bumps); self.head = head.to_string(); // A green probe of the rest was on the old head: probed again. A red @@ -1531,6 +1577,42 @@ impl DepRun { /// Ends the run where it stands (no step left): what is committed /// ships, everything not yet verified is deferred `later`. + /// The pull request's CI is red after every fix: the newest commit of + /// verified bumps comes out, its bumps deferred with `why` (not to come + /// back by themselves: they broke the checks), and the commits before + /// it stay. `None` when one commit or none is left: the pull request is + /// never emptied. Called again while CI stays red, it takes out the one + /// before, so only what breaks CI is deferred. + pub fn take_out_last_commit(&mut self, why: &str) -> Option { + if self.commits.len() < 2 { + return None; + } + let c = self.commits.pop()?; + let mut lines = Vec::new(); + for &i in &c.bumps { + let Some(b) = self.plan.bumps.get(i).cloned() else { + continue; + }; + let d = Deferral { + package: b.package, + from: b.from, + to: b.to, + manifest: b.manifest, + finding_ids: b.finding_ids, + reason: why.to_string(), + later: false, + }; + lines.push(d.line()); + self.deferred.push(d); + } + self.applied.retain(|i| !c.bumps.contains(i)); + self.head = c.before.clone(); + Some(TakenOut { + restore_to: c.before, + lines, + }) + } + pub fn finish_now(&mut self, why: &str) { self.give_up_unverified(why); self.done = true; diff --git a/services/common/src/dep_fix/tests.rs b/services/common/src/dep_fix/tests.rs index d8eb6ee05..6b89e7a48 100644 --- a/services/common/src/dep_fix/tests.rs +++ b/services/common/src/dep_fix/tests.rs @@ -1251,3 +1251,58 @@ fn proof_a_fix_ticket_never_asks_for_documentation() { let body = crate::security_fixes::ticket_body(&units[0], &members, &cfg); assert!(body.contains("Never edit documentation"), "{body}"); } + +/// The pull request's own CI stays red after the fixes: the newest commit +/// of verified bumps comes out and the earlier ones stay, one at a time, +/// and the pull request is never emptied. +#[test] +fn red_ci_takes_out_the_newest_commit_of_bumps_and_keeps_the_rest() { + let mut run = DepRun::new(ten_bumps(), "base", 3.0); + for (bumps, head) in [(vec![0, 1, 2], "h1"), (vec![3, 4], "h2"), (vec![5], "h3")] { + run.groups = vec![Group { + bumps, + green: true, + ..Default::default() + }]; + run.on_commit(0, head); + } + assert_eq!(run.commits.len(), 3); + assert_eq!(run.applied, vec![0, 1, 2, 3, 4, 5]); + // A green set with nothing to write is no commit of its own. + run.groups = vec![Group { + bumps: vec![6], + green: true, + ..Default::default() + }]; + run.on_commit(0, "h3"); + assert_eq!(run.commits.len(), 3); + + let why = ci_deferral_reason("npm error ETARGET No matching version found for lib-05@2.1.5"); + let out = run.take_out_last_commit(&why).expect("three commits"); + assert_eq!(out.restore_to, "h2"); + assert_eq!(out.lines.len(), 1); + assert!(out.lines[0].starts_with("`lib-05` 2.1.0 to 2.1.5 deferred: the pull request's CI failed with it applied (npm error ETARGET"), "{}", out.lines[0]); + assert_eq!(run.applied, vec![0, 1, 2, 3, 4, 6]); + assert_eq!(run.head, "h2"); + // It broke the checks: it doesn't come back by itself. + let d = run.deferred.last().unwrap(); + assert_eq!(d.package, "lib-05"); + assert!(!d.later); + assert!(run.report_md().contains("lib-05"), "{}", run.report_md()); + + // Still red: the one before it. Then one commit is left, and it stays. + let out = run.take_out_last_commit(&why).expect("two commits"); + assert_eq!(out.restore_to, "h1"); + assert_eq!(out.lines.len(), 2); + assert_eq!(run.applied, vec![0, 1, 2, 6]); + assert_eq!(run.take_out_last_commit(&why), None); + assert_eq!(run.commits.len(), 1); + assert_eq!(run.applied, vec![0, 1, 2, 6]); + + // A saved run from before commits were kept reads with none, and + // nothing is taken out of it. + let mut old: DepRun = serde_json::from_str("{\"applied\":[0,1]}").unwrap(); + assert!(old.commits.is_empty()); + assert_eq!(old.take_out_last_commit(&why), None); + assert!(ci_deferral_reason(" ").contains("CI failed with it applied;")); +} diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 8496301bb..97e13b26e 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -1239,6 +1239,38 @@ Rules: } super::round::Landed::Nothing => {} super::round::Landed::Refused(why) => { + // The same classified decision as every fix round's + // (`round::plan_for_fault`): while the round may + // continue it runs again in a fresh step, on its work + // branch when only the landing failed, from the pull + // request's head otherwise. + let plan = super::round::plan_for_fault( + feedback_round.kind, + &why, + super::round::after_fault_parked(feedback_round.may_continue()), + ); + warn!( + run_id = %msg.run_id, + fault = ?plan.class, + way_around = ?super::round::way_around(plan.class), + next = ?plan.next, + error = %why, + "Feedback round met a fault" + ); + if plan.next != super::round::AfterFault::Supervisor { + let mut again = feedback_round.clone(); + if plan.clean { + super::round::start_clean(&land_pr, &mut again).await; + } + super::round::record(state, &msg.team_id, &msg.run_id, &again).await; + let mut next = msg.clone(); + next.round_attempt = feedback_round.attempt; + if send_delayed_feedback(state, &next, 5).await { + super::add_progress_note(state, &msg.team_id, &msg.run_id, &plan.note) + .await; + return Ok(()); + } + } super::round::finish_incomplete( state, &msg.team_id, diff --git a/services/worker/src/passes/generators.rs b/services/worker/src/passes/generators.rs index e9908449f..3ba3e4754 100644 --- a/services/worker/src/passes/generators.rs +++ b/services/worker/src/passes/generators.rs @@ -2195,6 +2195,35 @@ pub(crate) async fn run_lock_repair( /// package manager in the sandbox and committed on `w.branch`. Says why /// when nothing could run; never an error. pub(crate) async fn repair_lockfiles(w: &Work<'_>, nonce: usize) -> LockRepair { + repair_lockfiles_with( + &LockWork { + state: w.state, + msg: w.msg, + github: w.github, + branch: w.branch, + run_id: w.run_id, + deadline: w.deadline, + provider: w.provider, + }, + nonce, + ) + .await +} + +/// What a lockfile repair needs of a run: less than a whole [`Work`], so +/// a path with no plan in hand (a stopped run's pull request) can call it. +pub(crate) struct LockWork<'a> { + pub state: &'a crate::WorkerState, + pub msg: &'a crate::models::TicketMessage, + pub github: &'a GitHubClient, + pub branch: &'a str, + pub run_id: &'a str, + pub deadline: Option, + pub provider: &'a crate::agent::provider::ModelProvider, +} + +/// [`repair_lockfiles`], from the pieces it needs. +pub(crate) async fn repair_lockfiles_with(w: &LockWork<'_>, nonce: usize) -> LockRepair { let state = w.state; if state.config.sandbox_bucket_name.is_empty() || state.config.sandbox_project_name.is_empty() { return LockRepair::not_run("no sandbox is set up"); diff --git a/services/worker/src/passes/incidents/ag_red_ci_ships_what_passes.rs b/services/worker/src/passes/incidents/ag_red_ci_ships_what_passes.rs new file mode 100644 index 000000000..33811f13f --- /dev/null +++ b/services/worker/src/passes/incidents/ag_red_ci_ships_what_passes.rs @@ -0,0 +1,273 @@ +//! ag. After #646 three ways were left for a run to end badly over red +//! checks or a refused landing: +//! +//! - a dependency fix whose pull request's CI stayed red had its work taken +//! apart by planned task (one task per lockfile: a lockfile put back +//! without its manifest), and after three reverts the run ended failed +//! with bumps still in the pull request that passed on their own; +//! - a run stopped after its work opened its pull request with the +//! manifests it had changed and lockfiles nobody had written, and waited +//! for CI to fail before the lockfiles were regenerated; +//! - a review fix or feedback round whose finished work GitHub refused to +//! land was recorded as "didn't finish" at once, while a CI fix round +//! with the same refusal ran again. +//! +//! Guarantee: red checks after every fix take out only what breaks them. A +//! dependency fix takes out its newest commit of verified bumps, defers +//! those bumps with what CI printed and keeps the commits before it, again +//! while CI stays red, never emptying the pull request. Any other run is +//! taken apart task by task down to the part that passes. What ships is +//! green with the rest under "Deferred". A stopped run's lockfiles are +//! written by their package managers before its pull request opens. Every +//! kind of fix round takes the same classified decision about a fault: +//! while it may continue it runs again, keeping its work when only the +//! landing failed. + +use super::fixture::fn_src; +use crate::passes::generators::LockRepair; +use crate::passes::round::{self, AfterFault, Fault}; +use crate::passes::supervisor::{self, Revert}; +use crate::passes::{resume, stop_pr}; +use common::dep_fix::{self, DepPlan, DepRun, Group, PlanBump}; +use common::run_round::Kind; + +fn bump(i: usize) -> PlanBump { + PlanBump { + package: format!("lib-{i:02}"), + from: "2.1.0".into(), + to: "2.1.5".into(), + manifest: "pnpm-lock.yaml".into(), + finding_ids: vec![format!("f{i}")], + ..Default::default() + } +} + +/// A dependency run that committed three verified sets. +fn run_with_three_sets() -> DepRun { + let plan = DepPlan { + bumps: (0..6).map(bump).collect(), + deferred: vec![], + }; + let mut run = DepRun::new(plan, "base", 3.0); + for (bumps, head) in [(vec![0, 1, 2], "h1"), (vec![3, 4], "h2"), (vec![5], "h3")] { + run.groups = vec![Group { + bumps, + green: true, + ..Default::default() + }]; + run.on_commit(0, head); + } + run +} + +#[test] +fn a_dependency_fix_with_red_ci_defers_only_the_set_that_breaks_it() { + let mut run = run_with_three_sets(); + assert_eq!(run.applied.len(), 6); + let failure = "npm error ETARGET No matching version found for lib-05@2.1.5"; + let why = dep_fix::ci_deferral_reason(failure); + + // CI is red after every fix: the newest set comes out, five bumps stay. + let out = run.take_out_last_commit(&why).expect("a set to take out"); + assert_eq!( + out.restore_to, "h2", + "the branch goes back to the set before" + ); + assert_eq!(run.applied, vec![0, 1, 2, 3, 4]); + let note = resume::dep_revert_note(&out.lines, run.commits.len()); + assert!( + note.contains("took out the newest verified set of 1 bump"), + "{note}" + ); + assert!(note.contains("kept the 2 sets before it"), "{note}"); + // The pull request names the bump and the exact failure. + assert!(note.contains("`lib-05` 2.1.0 to 2.1.5 deferred"), "{note}"); + assert!(note.contains(failure), "{note}"); + // Its finding stays open and is held out of later bundles; the others + // are fixed by the pull request. + assert_eq!(run.fixed_ids(), vec!["f0", "f1", "f2", "f3", "f4"]); + let held: Vec<&str> = run + .deferred + .iter() + .filter(|d| !d.later) + .flat_map(|d| d.finding_ids.iter().map(String::as_str)) + .collect(); + assert_eq!(held, vec!["f5"]); + + // Still red: the set before it. The last set is never taken out: the + // pull request is not emptied. + assert!(run.take_out_last_commit(&why).is_some()); + assert_eq!(run.applied, vec![0, 1, 2]); + assert_eq!(run.take_out_last_commit(&why), None); + assert_eq!(run.applied, vec![0, 1, 2]); + + // The pipeline: the revert asks the dependency run first, and only a + // written revert moves the run's saved state. + let src = include_str!("../resume.rs"); + let revert = fn_src(src, "async fn revert_to_green("); + assert!( + revert.find("revert_dep_commit(").unwrap() < revert.find("sup::revert_for(").unwrap(), + "a dependency run is taken apart by task again" + ); + let dep = fn_src(src, "async fn revert_dep_commit("); + let write = dep.find("apply_revert(").unwrap(); + assert!(dep.find("take_out_last_commit(").unwrap() < write); + assert!(write < dep.find("dep_fix::save(").unwrap()); + assert!(write < dep.find("dep_fix::settle(").unwrap()); + // And the driver records each commit it makes. + let common_src = include_str!("../../../../common/src/dep_fix.rs"); + assert!(common_src.contains("self.commits.push(BatchCommit {")); +} + +#[test] +fn a_plan_is_taken_apart_down_to_the_part_that_passes() { + let done: Vec<(String, String)> = (1..=6) + .map(|i| (format!("src/part{i}.ts"), format!("part {i}"))) + .collect(); + // No earlier green head: the last task comes out, then the one before, + // past the three reverts that used to end the run failed. + let mut left = done.clone(); + let mut reverts = 0u32; + while let Revert::Task { path, .. } = supervisor::revert_for(&[], &left, reverts) { + assert_eq!(path, left.last().unwrap().0); + left.pop(); + reverts += 1; + } + assert_eq!( + left.len(), + 1, + "one task stays: the pull request is never emptied" + ); + assert_eq!(reverts, 5); + assert!( + reverts > 3, + "the old cap ended the run with three tasks that could still come out" + ); + // A green earlier head is still taken first. + let heads = vec![("c9".to_string(), false), ("c8".to_string(), true)]; + assert_eq!( + supervisor::revert_for(&heads, &done, 4), + Revert::ToHead("c8".into()) + ); + // The bound stays. + assert_eq!( + supervisor::revert_for(&heads, &done, supervisor::MAX_REVERTS), + Revert::Nothing + ); +} + +#[test] +fn a_stopped_runs_lockfiles_are_written_before_its_pull_request_opens() { + let src = include_str!("../stop_pr.rs"); + let open = &src[src.find("pub async fn open_with(").unwrap()..]; + let locks = open + .find("lockfiles_before_stop(") + .expect("the lockfiles step"); + assert!( + locks < open.find(".get_diff(").unwrap(), + "the diff is read before the lockfiles are written" + ); + // (Spelled in two parts: a scan counts the places that open pull + // requests by this call's text.) + let opens = format!(".create_pull{}", "_request("); + assert!(locks < open.find(&opens).unwrap()); + let step = fn_src(src, "async fn lockfiles_before_stop("); + assert!(step.contains("generators::repair_lockfiles_with(")); + + // Said on the run only when there was something to write. + assert_eq!(stop_pr::stop_lock_note(&LockRepair::default()), None); + let wrote = LockRepair { + written: vec!["pnpm-lock.yaml".into()], + ..Default::default() + }; + let note = stop_pr::stop_lock_note(&wrote).unwrap(); + assert!( + note.starts_with("Before the pull request: CoderHelm regenerated"), + "{note}" + ); + // One that couldn't be written is named, and the stop still opens. + let failed = LockRepair { + failed: vec![("yarn.lock".into(), "yarn exited 1".into())], + ..Default::default() + }; + assert!(stop_pr::stop_lock_note(&failed) + .unwrap() + .contains("couldn't be written")); + assert!( + !step.contains("return Err("), + "a lockfile failure must not stop the pull request" + ); +} + +#[test] +fn every_kind_of_fix_round_takes_the_same_decision_about_a_fault() { + const PUSH: &str = "the one commit couldn't be pushed (HTTP status client error (422 Unprocessable Entity): Update is not a fast forward)"; + const CLASH: &str = "the pull request changed the same files meanwhile (src/a.ts)"; + const OTHER: &str = "the model's reply could not be read"; + + // A round with a step left runs again; one without is the round that + // didn't finish. The same rule the CI fix round follows. + assert_eq!(round::after_fault_parked(true), AfterFault::Redrive); + assert_eq!(round::after_fault_parked(false), AfterFault::Supervisor); + for kind in [ + Kind::ReviewFix, + Kind::Feedback, + Kind::SecurityFix, + Kind::PlannedWork, + ] { + // Only the landing failed: the work is kept for the next try. + let plan = round::plan_for_fault(kind, PUSH, round::after_fault_parked(true)); + assert_eq!(plan.class, Fault::PushRejected); + assert_eq!(plan.next, AfterFault::Redrive); + assert!( + !plan.clean, + "{kind:?}: finished work is thrown away over a refused push" + ); + assert!(plan.note.contains("fresh step"), "{}", plan.note); + assert!(!plan.note.contains("didn't finish"), "{}", plan.note); + // The pull request moved under it, or anything else: from its head. + for error in [CLASH, OTHER] { + let plan = round::plan_for_fault(kind, error, round::after_fault_parked(true)); + assert!(plan.clean, "{kind:?}: {error}"); + assert_eq!(plan.next, AfterFault::Redrive); + } + let plan = round::plan_for_fault(kind, PUSH, round::after_fault_parked(false)); + assert_eq!(plan.next, AfterFault::Supervisor); + } + assert!(round::keeps_work(Fault::Unreadable) && round::keeps_work(Fault::GitHubBusy)); + assert!(!round::keeps_work(Fault::WipMissing) && !round::keeps_work(Fault::Sandbox)); + + // One decision, three callers: none decides a refusal on its own. + let resume_src = include_str!("../resume.rs"); + let feedback_src = include_str!("../feedback.rs"); + assert_eq!( + resume_src.matches("super::round::plan_for_fault(").count(), + 2 + ); + assert_eq!( + feedback_src + .matches("super::round::plan_for_fault(") + .count(), + 1 + ); + let fix_round = fn_src(resume_src, "async fn run_fix_round("); + assert_eq!( + fix_round.matches("round_fault(").count(), + 2, + "a refusal and an error" + ); + assert!( + !fix_round.contains("couldn't land on the pull request"), + "run_fix_round calls a refused landing unfinished at once" + ); + let fault = fn_src(resume_src, "async fn round_fault("); + let ended = fault.find("finish_incomplete(").unwrap(); + assert!(fault.find("AfterFault::Supervisor").unwrap() < ended); + assert!(fault.contains("park_round(")); + let refused = &feedback_src[feedback_src.find("Landed::Refused(why) => {").unwrap()..]; + assert!( + refused.find("send_delayed_feedback(").unwrap() + < refused.find("finish_incomplete(").unwrap(), + "a feedback round's refused landing is called unfinished before it is tried again" + ); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 3457efd6a..518a27d05 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -22,6 +22,7 @@ mod ac_partial_and_red_ci; mod ad_hand_back_reply; mod ae_budget_rounds; mod af_lockfiles_out_of_sync; +mod ag_red_ci_ships_what_passes; mod b_open_pr_retry; mod c_codegen_egress; mod d_echoed_markers; diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 7153e7935..6fb208aad 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -2863,29 +2863,27 @@ pub async fn run( // and the catch-all runs the round again from a clean state // (now, then once in a fresh step) before the supervisor's // ending is asked. Never a dead round, never "failed" here. - let class = super::round::fault_of(&why); let redrives = run_number(state, &msg.team_id, &msg.run_id, "round_redrives").await; - let next = super::round::after_fault( - attempt, - max_attempts, - super::round::may_start(start, std::time::Instant::now()), - redrives, + let fault_plan = super::round::plan_for_fault( + ci_round.kind, + &why, + super::round::after_fault( + attempt, + max_attempts, + super::round::may_start(start, std::time::Instant::now()), + redrives, + ), ); + let next = fault_plan.next.clone(); warn!( run_id = msg.run_id, - fault = ?class, - way_around = ?super::round::way_around(class), + fault = ?fault_plan.class, + way_around = ?super::round::way_around(fault_plan.class), next = ?next, error = %why, "CI fix attempt met a fault" ); - super::add_progress_note( - state, - &msg.team_id, - &msg.run_id, - &super::round::fault_note(ci_round.kind, class, &why, &next), - ) - .await; + super::add_progress_note(state, &msg.team_id, &msg.run_id, &fault_plan.note).await; tried.push(format!( "attempt {attempt} didn't land: {}", common::truncate_str(&why, 240) @@ -3999,16 +3997,17 @@ async fn run_fix_round( Ok(RoundEnd::Done { files: 0 }) } super::round::Landed::Refused(why) => { - super::round::finish_incomplete( + round_fault( state, - &msg.team_id, - &msg.run_id, + msg, + (&ctx.ticket_msg, &ctx.usage), + pr, &gh, - &round, - &format!("its changes couldn't land on the pull request: {why}"), + round, + &why, + (created_at, start), ) - .await; - Ok(RoundEnd::Incomplete) + .await } } } @@ -4030,21 +4029,71 @@ async fn run_fix_round( ) .await; } - error!(run_id = msg.run_id, error = %e, "Fix round failed"); - super::round::finish_incomplete( + warn!(run_id = msg.run_id, error = %e, "Fix round met an error; taking the way around it"); + round_fault( state, - &msg.team_id, - &msg.run_id, + msg, + (&ctx.ticket_msg, &ctx.usage), + pr, &gh, - &round, - &run_round::errored(round.kind, &common::run_fail::error_text(err)), + round, + &common::run_fail::error_text(err), + (created_at, start), ) - .await; - Ok(RoundEnd::Incomplete) + .await } } } +/// A fix round met a fault (its changes couldn't land, its pass errored): +/// the same classified decision as the CI fix round's +/// (`round::plan_for_fault`). While the round may continue it runs again +/// in a fresh step: on its work branch when only the landing failed, from +/// the pull request's head otherwise. Only a round with no step left is +/// recorded as the one that didn't finish. +#[allow(clippy::too_many_arguments)] +async fn round_fault( + state: &WorkerState, + msg: &ResumeMessage, + ctx: (&TicketMessage, &TokenUsage), + pr: &PrRef<'_>, + gh: &super::round::Pr<'_>, + mut round: run_round::Round, + why: &str, + (created_at, start): (Option>, &std::time::Instant), +) -> Result> { + let plan = super::round::plan_for_fault( + round.kind, + why, + super::round::after_fault_parked(round.may_continue()), + ); + warn!( + run_id = msg.run_id, + fault = ?plan.class, + way_around = ?super::round::way_around(plan.class), + next = ?plan.next, + error = %why, + "Fix round met a fault" + ); + if plan.next == super::round::AfterFault::Supervisor { + super::round::finish_incomplete( + state, + &msg.team_id, + &msg.run_id, + gh, + &round, + &format!("its changes couldn't land on the pull request: {why}"), + ) + .await; + return Ok(RoundEnd::Incomplete); + } + super::add_progress_note(state, &msg.team_id, &msg.run_id, &plan.note).await; + if plan.clean { + super::round::start_clean(gh, &mut round).await; + } + park_round(state, msg, ctx, pr, &round, true, created_at, start).await +} + /// A parked round, picked up by a fresh invocation with its whole budget: /// it runs before anything else the resume would do. async fn run_pending_round( @@ -6069,7 +6118,11 @@ async fn revert_to_green( excerpt: &str, ) -> Option { use super::supervisor::{self as sup, Revert}; - use crate::clients::github::FileOp; + // A dependency fix run takes out its newest commit of verified bumps + // and keeps the ones before it: only what breaks CI is deferred. + if let Some(note) = revert_dep_commit(state, msg, ticket_msg, github, pr, excerpt).await { + return Some(note); + } let reverts = run_number(state, &msg.team_id, &msg.run_id, "sup_reverts").await; // Earlier heads of the pull request, newest first, and whether their // checks passed (at most ten are read). @@ -6185,6 +6238,108 @@ async fn revert_to_green( ) } }; + apply_revert(state, msg, github, pr, files, ¬e).await?; + if let Some(mut p) = plan { + if !deferred.is_empty() { + p.tasks = super::plan_coverage::with_deferred(&p.tasks, &deferred); + super::save_checked_tasks(state, ticket_msg, &msg.run_id, &p.tasks).await; + } + } + Some(note) +} + +/// What fails, for a deferral's reason: the cause the fix round recorded +/// (`ci_cause`), else the failing checks' own line. +async fn recorded_failure( + state: &WorkerState, + team_id: &str, + run_id: &str, + excerpt: &str, +) -> String { + let cause = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("ci_cause") + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| i.get("ci_cause").and_then(|v| v.as_s().ok()).cloned()) + .unwrap_or_default(); + if cause.trim().is_empty() { + excerpt.trim().to_string() + } else { + cause + } +} + +/// The revert for a dependency fix run whose pull request's CI stays red: +/// the branch goes back to the files it had before the run's newest commit +/// of verified bumps, those bumps are deferred with what CI printed, and +/// the commits before it stay (`DepRun::take_out_last_commit`). The +/// findings follow the run's state, and the pull request names each bump +/// under "Deferred". +/// `None` when the run isn't one, or one commit or none is left. +async fn revert_dep_commit( + state: &WorkerState, + msg: &ResumeMessage, + ticket_msg: &TicketMessage, + github: &GitHubClient, + pr: &PrRef<'_>, + excerpt: &str, +) -> Option { + if !common::security_fixes::is_ticket(&ticket_msg.ticket_id) { + return None; + } + let mut run = super::dep_fix::load(state, ticket_msg, &msg.run_id).await?; + let failure = recorded_failure(state, &msg.team_id, &msg.run_id, excerpt).await; + let out = run.take_out_last_commit(&common::dep_fix::ci_deferral_reason(&failure))?; + let changed = github + .compare_changed_files(pr.owner, pr.repo, &out.restore_to, pr.branch) + .await + .ok()?; + let mut files = Vec::new(); + for path in &changed { + let was = github + .read_file_if_exists(pr.owner, pr.repo, path, &out.restore_to) + .await + .ok()?; + files.push((path.clone(), was)); + } + let note = dep_revert_note(&out.lines, run.commits.len()); + apply_revert(state, msg, github, pr, files, ¬e).await?; + super::dep_fix::save(state, ticket_msg, &msg.run_id, &run).await; + super::dep_fix::settle(state, ticket_msg, &run).await; + Some(note) +} + +/// The pull request's "Deferred" line for a commit of bumps CI took out. +pub(crate) fn dep_revert_note(lines: &[String], commits_left: usize) -> String { + format!( + "CI stayed red after the fix attempts: took out the newest verified set of {} bump{} and \ + kept the {} set{} before it. {}. CI decides again.", + lines.len(), + if lines.len() == 1 { "" } else { "s" }, + commits_left, + if commits_left == 1 { "" } else { "s" }, + lines.join("; ") + ) +} + +/// Writes a revert as one commit and names it under "Deferred" on the pull +/// request. `None` when there is nothing to write or GitHub refused it. +async fn apply_revert( + state: &WorkerState, + msg: &ResumeMessage, + github: &GitHubClient, + pr: &PrRef<'_>, + files: Vec<(String, Option)>, + note: &str, +) -> Option<()> { + use crate::clients::github::FileOp; if files.is_empty() { return None; } @@ -6209,12 +6364,6 @@ async fn revert_to_green( return None; } add_run_number(state, &msg.team_id, &msg.run_id, "sup_reverts").await; - if let Some(mut p) = plan { - if !deferred.is_empty() { - p.tasks = super::plan_coverage::with_deferred(&p.tasks, &deferred); - super::save_checked_tasks(state, ticket_msg, &msg.run_id, &p.tasks).await; - } - } if let Ok(p) = github.get_pull_request(pr.owner, pr.repo, pr.number).await { let body = p["body"].as_str().unwrap_or(""); let line = format!("- {note}"); @@ -6227,7 +6376,7 @@ async fn revert_to_green( .update_pr_body(pr.owner, pr.repo, pr.number, &now) .await; } - Some(note) + Some(()) } /// A number kept on the run record (0 when absent). diff --git a/services/worker/src/passes/round.rs b/services/worker/src/passes/round.rs index 4155c09a7..1acec57f6 100644 --- a/services/worker/src/passes/round.rs +++ b/services/worker/src/passes/round.rs @@ -540,6 +540,60 @@ pub(crate) fn after_fault( } } +/// [`after_fault`] for a round that makes one attempt per invocation (a +/// review fix, a person's feedback, a security fix, planned work): it runs +/// again in a fresh invocation while it may continue, and only then is +/// left as the round that didn't finish. +pub(crate) fn after_fault_parked(may_continue: bool) -> AfterFault { + after_fault(1, 1, false, if may_continue { 0 } else { MAX_REDRIVES }) +} + +/// Whether the round's work branch is kept for the next try. Its work is +/// there and only the landing failed when GitHub refused the push, the +/// compare or didn't answer; any other fault starts again from the pull +/// request's head (a clash must: the work was written on an older head). +pub(crate) fn keeps_work(f: Fault) -> bool { + matches!( + f, + Fault::PushRejected | Fault::Unreadable | Fault::GitHubBusy + ) +} + +/// What a round does about a fault it met: its class, what comes next and +/// the line for the run page. The one decision every kind of round takes +/// (`resume`'s CI fix loop, `run_fix_round`, the feedback pass). +pub(crate) struct FaultPlan { + pub class: Fault, + pub next: AfterFault, + pub note: String, + /// The work branch goes, and the next try starts from the pull + /// request's head. + pub clean: bool, +} + +pub(crate) fn plan_for_fault(kind: Kind, error: &str, next: AfterFault) -> FaultPlan { + let class = fault_of(error); + FaultPlan { + class, + note: fault_note(kind, class, error, &next), + clean: !keeps_work(class) || next == AfterFault::Supervisor, + next, + } +} + +/// A clean state for a round's next try: its work branch goes, and the +/// round starts from the pull request's head as it is now. +pub(crate) async fn start_clean(pr: &Pr<'_>, round: &mut Round) { + if !round.wip_branch.is_empty() && round.wip_branch != pr.branch { + let _ = pr + .github + .delete_branch(pr.owner, pr.repo, &round.wip_branch) + .await; + } + round.wip_branch = String::new(); + round.base_sha = branch_head(pr.github, pr.owner, pr.repo, pr.branch).await; +} + /// What a fault and its way around read like on the run page. pub(crate) fn fault_note(kind: Kind, f: Fault, error: &str, next: &AfterFault) -> String { let what = match f { diff --git a/services/worker/src/passes/stop_pr.rs b/services/worker/src/passes/stop_pr.rs index 472cc81dd..b1dbd4cd4 100644 --- a/services/worker/src/passes/stop_pr.rs +++ b/services/worker/src/passes/stop_pr.rs @@ -248,6 +248,62 @@ pub async fn open( open_with(state, msg, run_id, branch, reason, &[], true, &judged).await } +/// Regenerates the lockfiles a stopped run's branch calls for +/// (`generators::repair_lockfiles_with`). Returns the line for the run +/// page, or `None` when the branch changes no manifest a lockfile reads. +async fn lockfiles_before_stop( + state: &WorkerState, + msg: &TicketMessage, + github: &GitHubClient, + run_id: &str, + branch: &str, +) -> Option { + let provider = match crate::agent::provider::ModelProvider::load_for_team( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + ) + .await + { + Ok(p) => p.for_run( + run_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + "", + "", + ), + Err(e) => { + tracing::warn!(run_id, error = %e, "Lockfiles before a stopped run's pull request: no provider scope"); + return None; + } + }; + let repair = super::generators::repair_lockfiles_with( + &super::generators::LockWork { + state, + msg, + github, + branch, + run_id, + deadline: None, + provider: &provider, + }, + 0, + ) + .await; + stop_lock_note(&repair) +} + +/// What the stop says about its lockfiles: nothing when none needed +/// writing. +pub(crate) fn stop_lock_note(repair: &super::generators::LockRepair) -> Option { + if repair.written.is_empty() && repair.failed.is_empty() && repair.not_run.is_none() { + return None; + } + Some(format!( + "Before the pull request: CoderHelm {}.", + repair.note() + )) +} + /// [`open`], with what the checks left open going under Open items (on the /// pull request that is already there too), and the notification only when /// `notify` says this stop hasn't sent one. @@ -280,6 +336,13 @@ pub async fn open_with( msg.installation_id, &state.http, )?; + // A stopped run's pull request never goes up with a manifest and its + // lockfile out of sync: the lockfiles the branch's changes call for + // are written by their package managers first, by code. What can't be + // written is said on the run; the stop still opens its pull request. + if let Some(note) = lockfiles_before_stop(state, msg, &github, run_id, branch).await { + super::add_progress_note(state, &msg.team_id, run_id, ¬e).await; + } let diff = github .get_diff(&msg.repo_owner, &msg.repo_name, &msg.base_branch, branch) .await?; diff --git a/services/worker/src/passes/supervisor.rs b/services/worker/src/passes/supervisor.rs index c5ba29083..37f2fb9b4 100644 --- a/services/worker/src/passes/supervisor.rs +++ b/services/worker/src/passes/supervisor.rs @@ -371,8 +371,11 @@ pub fn end_of_rounds(left: &[String], why: &str, ci_failing: &[String]) -> Endin // ── Red checks ────────────────────────────────────────────────────────────── /// How many reverts the supervisor makes on one pull request before the -/// run ends with what still fails. -pub const MAX_REVERTS: u32 = 3; +/// run ends with what still fails. Enough to take a plan apart task by task +/// down to the part that passes (three used to end a run failed with tasks +/// left that could still have come out); the run's spend ceiling and its +/// fix cycles bound it as well. +pub const MAX_REVERTS: u32 = 8; /// What the supervisor takes out so what ships is green. #[derive(Debug, Clone, PartialEq, Eq)] @@ -1086,7 +1089,7 @@ mod tests { } for needs in [ "super::round::after_fault(", - "super::round::fault_of(", + "super::round::plan_for_fault(", "break 'attempt Some(", ] { if !ci_fix.contains(needs) { @@ -1126,6 +1129,46 @@ mod tests { )); } } + // Red checks take out only what breaks them: a dependency run's + // newest commit of bumps before any task of the plan. Every kind + // of fix round takes the one fault decision. A stopped run's + // lockfiles are written before its pull request opens. + let revert = body(&resume, "\nasync fn revert_to_green("); + match ( + revert.find("revert_dep_commit("), + revert.find("sup::revert_for("), + ) { + (Some(d), Some(t)) if d < t => {} + _ => bad.push("resume.rs: revert_to_green takes a dependency run apart by task".into()), + } + let fix_round = body(&resume, "\nasync fn run_fix_round("); + if fix_round.contains("finish_incomplete(") + && fix_round.matches("finish_incomplete(").count() > 1 + { + bad.push( + "resume.rs: run_fix_round calls a fault unfinished without the decision".into(), + ); + } + if !body(&resume, "\nasync fn round_fault(").contains("super::round::plan_for_fault(") { + bad.push("resume.rs: round_fault doesn't take the shared fault decision".into()); + } + if !find("passes/feedback.rs").contains("super::round::plan_for_fault(") { + bad.push( + "feedback.rs: a refused landing doesn't take the shared fault decision".into(), + ); + } + let stop = find("passes/stop_pr.rs"); + let open = &stop[stop.find("pub async fn open_with(").unwrap_or(0)..]; + match ( + open.find("lockfiles_before_stop("), + open.find(".create_pull_request("), + ) { + (Some(l), Some(c)) if l < c => {} + _ => bad.push( + "stop_pr.rs: a stopped run's pull request opens before its lockfiles are written" + .into(), + ), + } let passes = find("passes/mod.rs"); let from = passes.find("let mut fixed_by_code = false;").unwrap_or(0); let to = passes[from..]