diff --git a/docs/incidents.md b/docs/incidents.md index 285219a9b..8a10e9b22 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -50,6 +50,7 @@ pipeline still calls it there. | r. `r_github_limit` | A fix round hit GitHub's hourly limit. 29 writes and the diff came back "403 rate limit exceeded", and the run ended "the coder wrote no file ... That is CoderHelm's miss". | GitHub refusing for a while (its rate limit, a 5xx, no answer) never ends a run and is never blamed on the coder. The model is told the run pauses, the pass ends, and the run goes on as itself at GitHub's reset, with its page saying when. The wait adds no step and no pass. Writes GitHub rejected for a real reason are reported with that reason. A review waits for the reset without spending its retries. | | s. `s_silent_draft` | A new-feature run finished with CI green and CoderHelm's review approving, and its pull request stayed a draft. Four of CoderHelm's own sandbox checks had failed on the head, the mark-ready step returned without a word, and the run page said completed. The same day, mark-ready messages that hit GitHub's rate limit were dropped and five more pull requests stayed drafts. | One decision settles every pull request a finished run leaves, on every path. With CI green and the review approving, CoderHelm's own sandbox failures and checklist items never hold the draft: the pull request is marked ready with them under Open items. A hold that remains names each reason and what to do at the top of the description, at warn in the log, and on the run, which is `needs_input` while a person must act. A mark-ready GitHub refuses is tried again after its reset, a bounded number of times, and the last refusal is recorded on the run. A sweep decides again for finished runs left a draft with no recorded reason, respecting a person's draft and a closed pull request. | | t. `t_unrun_check_hold` | A check's gate couldn't install its package's dependencies (`pnpm: command not found` in CoderHelm's sandbox). The tooling failure went under Open items as a check the change didn't pass, and the pull request stayed a draft after CI passed. | A check CoderHelm's own tools couldn't run becomes an Open item CI settles, never a hold. A line written the old way stops holding once CI is green on the head and leaves the description when the pull request is marked ready. A check the change really failed still holds. | +| u. `u_stacked_plan_check` | A run stacked on an earlier part's open pull request reset to the default branch in every step, rebuilt and force-pushed its branch each time, and measured its plan against the other branch: 13 files that branch already changed read as not done, the coder found nothing to write, and the guard stopped the run after seven continuations. | A later step keeps the base an earlier step stacked it on; a planned file the stacked-on branch already changes is done there, and the plan check's note says so; a fall in the done count is reported on the run page, and its recovery counts as progress a bounded number of times. | ## Adding a case diff --git a/services/worker/src/passes/covering.rs b/services/worker/src/passes/covering.rs index 392a18891..f9753e2e3 100644 --- a/services/worker/src/passes/covering.rs +++ b/services/worker/src/passes/covering.rs @@ -598,7 +598,7 @@ pub async fn unfinished_tasks( if tasks.is_empty() { return Vec::new(); } - let Some(changed) = super::plan_coverage::changed_files( + let Some(changes) = super::plan_coverage::plan_changes( github, &msg.repo_owner, &msg.repo_name, @@ -609,7 +609,8 @@ pub async fn unfinished_tasks( else { return Vec::new(); }; - super::plan_coverage::coverage(&tasks, &changed) + changes + .coverage(&tasks) .required_missing() .into_iter() .map(|t| t.task.clone()) diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index dca0a3516..42921e00b 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -35,3 +35,4 @@ mod q_run_ceiling; mod r_github_limit; mod s_silent_draft; mod t_unrun_check_hold; +mod u_stacked_plan_check; diff --git a/services/worker/src/passes/incidents/u_stacked_plan_check.rs b/services/worker/src/passes/incidents/u_stacked_plan_check.rs new file mode 100644 index 000000000..430112ef1 --- /dev/null +++ b/services/worker/src/passes/incidents/u_stacked_plan_check.rs @@ -0,0 +1,163 @@ +//! u. A ticket whose earlier part was still an open pull request ran on +//! that pull request's branch. Its plan had 38 tasks. In step 2, measured +//! against the default branch, 37 were done. From step 3 on, every step +//! started again from the default branch, read the branch (already built on +//! the other pull request) as copying its commits, rebuilt it on that branch +//! and force-pushed it, and measured the plan against that branch instead: +//! the 13 files the other pull request already changed into their planned +//! form dropped out of the diff. The plan check read 23 of 38, the coder +//! found those files already done and wrote nothing, and after seven +//! continuations the guard stopped the run: "it continued 7 times without +//! finishing another task". +//! +//! Guarantee: a later step of a run keeps the base an earlier step stacked +//! it on (no rebuild, no force push, one base for the plan check); a planned +//! file the stacked-on branch already changes is done there and the note +//! says so; and a fall in the done count is reported and, a bounded number +//! of times, its recovery counts as progress. + +use super::fixture::*; +use crate::passes::plan_coverage::{self, Next, PlanChanges}; +use crate::passes::run_guard::{GuardState, Progress, Trip, MAX_TASK_DROPS}; +use crate::passes::stack; + +const DEP: &str = "coderhelm/gh-40-title-size"; + +fn plan(n: usize) -> String { + (0..n) + .map(|i| format!("- [ ] apps/web/src/blocks/b{i}.tsx: [modify] Read the title size")) + .collect::>() + .join("\n") +} + +fn files(range: std::ops::Range) -> Vec { + range + .map(|i| format!("apps/web/src/blocks/b{i}.tsx")) + .collect() +} + +#[test] +fn files_the_stacked_on_branch_already_changed_are_done_there() { + let tasks = plan_coverage::plan_tasks(&plan(38)); + // The branch's own diff against the stacked-on branch: 24 files (one + // planned task is genuinely left). The other branch changes 13 more. + let own = files(0..24); + let changes = PlanChanges { + own: own.clone(), + on_base: files(24..37), + }; + let cov = changes.coverage(&tasks); + assert_eq!(cov.done.len(), 37); + assert_eq!(cov.on_base.len(), 13); + assert_eq!(cov.required_missing().len(), 1); + let note = plan_coverage::progress_note(&cov); + assert!(note.contains("37 of 38")); + assert!(note.contains("b30.tsx (changed by the branch this one is stacked on)")); + assert!(!note.contains("b3.tsx (changed by")); + // The round is told only the one task left, not the 13. + let told = plan_coverage::round_feedback(&cov); + assert!(told.contains("b37.tsx")); + assert!(!told.contains("- [ ] `apps/web/src/blocks/b30.tsx`")); + + // The old check, the branch's own diff alone, read 23 of 38 forever. + let old = plan_coverage::coverage(&tasks, &own); + assert_eq!(old.required_missing().len(), 14); + + // With the last file written, the plan is complete. + let all = PlanChanges { + own: files(0..24).into_iter().chain(files(37..38)).collect(), + on_base: files(24..37), + }; + assert_eq!( + plan_coverage::next(&all.coverage(&tasks), 0, true), + Next::Complete + ); +} + +#[test] +fn only_a_stacked_base_adds_its_changes() { + assert!(plan_coverage::stacked_base(DEP, BASE)); + assert!(!plan_coverage::stacked_base(BASE, BASE)); + assert!(!plan_coverage::stacked_base(DEP, "")); +} + +#[test] +fn a_later_step_keeps_the_base_an_earlier_step_stacked_it_on() { + assert!(stack::keeps_base(true, DEP, BASE)); + // A new run, or a message that names the default branch, starts there. + assert!(!stack::keeps_base(false, DEP, BASE)); + assert!(!stack::keeps_base(true, BASE, BASE)); + assert!(!stack::keeps_base(true, "", BASE)); + + // The pipeline asks before it sets the default branch for good, and a + // kept base is what the run stacks on when the ticket names none. + let src = include_str!("../mod.rs"); + let rp = fn_src(src, "\nasync fn run_passes("); + let reset = rp + .find("std::mem::replace(&mut msg.base_branch, default_branch)") + .expect("the default branch replaces the incoming base, which is kept"); + assert!(rp[reset..reset + 600].contains("stack::keeps_base(msg.same_run()")); + let stacked = rp.find("stack::for_ticket(&github, msg, &own)").unwrap(); + assert!(rp[stacked..stacked + 300].contains("kept_stack")); + assert!(!rp.contains("msg.base_branch = default_branch;")); +} + +#[test] +fn every_plan_check_reads_the_stacked_base() { + let pc = include_str!("../plan_coverage.rs"); + let gaps = fn_src(pc, "\npub async fn close_gaps("); + assert!(gaps.contains("plan_changes(")); + assert!(!gaps.contains("coverage(&tasks, &changed)")); + let cov = include_str!("../covering.rs"); + assert!(cov.contains("plan_coverage::plan_changes(")); +} + +#[test] +fn a_fall_in_the_count_is_news_and_its_recovery_is_progress() { + // The incident's counts: 1, 37, then 23 (the base moved), 17, 23, ... + let mut g = GuardState::default(); + assert!(g.apply(&Progress::TasksDone(1))); + assert!(g.apply(&Progress::TasksDone(37))); + g.on_continuation(1.0); + assert!(!g.apply(&Progress::TasksDone(23)), "a fall is not progress"); + assert_eq!(g.task_drops, 1); + g.on_continuation(1.0); + assert!(!g.apply(&Progress::TasksDone(17))); + assert_eq!(g.task_drops, 2); + g.on_continuation(1.0); + assert!( + g.apply(&Progress::TasksDone(23)), + "lost work done again is progress" + ); + assert_eq!(g.continuations, 0); + assert_eq!(g.tasks_done, 37, "the best stays the best"); + + // A count that keeps falling and rising still ends: past the bound, + // only a new best counts. + for _ in 0..4 { + g.on_continuation(1.0); + g.apply(&Progress::TasksDone(17)); + g.on_continuation(1.0); + g.apply(&Progress::TasksDone(23)); + } + assert!(g.task_drops > MAX_TASK_DROPS); + assert_eq!(g.trip(), Some(Trip::Continuations)); +} + +#[test] +fn a_record_from_before_counts_from_its_best() { + // Guard state saved before this change has no last count. + let g: GuardState = serde_json::from_str(r#"{"tasks_done":37}"#).unwrap(); + let mut g = g; + assert!(!g.apply(&Progress::TasksDone(37))); + assert!(!g.apply(&Progress::TasksDone(23))); + assert_eq!(g.task_drops, 1); +} + +#[test] +fn the_guard_reports_a_fall_on_the_run_page() { + let src = include_str!("../run_guard.rs"); + let p = fn_src(src, "\npub async fn progress("); + assert!(p.contains("add_progress_note(")); + assert!(p.contains("fewer tasks done than before")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 690d03464..5c819ef6f 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -2009,7 +2009,18 @@ async fn run_passes( } } }; - msg.base_branch = default_branch; + let incoming_base = std::mem::replace(&mut msg.base_branch, default_branch); + // A later step of the same run keeps the open pull request branch an + // earlier step stacked it on (`stack::kept`). + let kept_stack = if stack::keeps_base(msg.same_run(), &incoming_base, &msg.base_branch) { + stack::kept(&github, &msg.repo_owner, &msg.repo_name, &incoming_base).await + } else { + None + }; + if let Some(d) = &kept_stack { + info!(run_id, base = %d.branch, pr = d.number, "Continuation: keeping the stacked base"); + msg.base_branch = d.branch.clone(); + } // create_run_record() ran BEFORE run_passes and persisted the UNRESOLVED // incoming base_branch, which defaults to `main`. Now that the repo's real @@ -2448,6 +2459,9 @@ async fn run_passes( .collect(); stack::for_ticket(&github, msg, &own).await }; + if stacked_on.is_none() { + stacked_on = kept_stack.filter(|d| d.branch == msg.base_branch); + } // Building what CoderHelm's own covering pull request lacks: on its // branch, so the work goes onto it without copying anything. if let Some((_, dep)) = &continue_in { @@ -5714,7 +5728,7 @@ async fn run_passes( &plan_result.tasks, ) .await; - if let Some(changed) = plan_coverage::changed_files( + if let Some(changes) = plan_coverage::plan_changes( &github, &msg.repo_owner, &msg.repo_name, @@ -5724,7 +5738,7 @@ async fn run_passes( .await { let cov = plan_coverage::settle_generated( - plan_coverage::coverage(&tasks, &changed), + changes.coverage(&tasks), &settled_generated, ); save_checked_tasks( @@ -6435,7 +6449,7 @@ async fn resumed_optional( let tasks = plan_coverage::tasks_for(github, &msg.repo_owner, &msg.repo_name, branch, &plan.tasks) .await; - let Some(changed) = plan_coverage::changed_files( + let Some(changes) = plan_coverage::plan_changes( github, &msg.repo_owner, &msg.repo_name, @@ -6446,7 +6460,7 @@ async fn resumed_optional( else { return Vec::new(); }; - plan_coverage::optional_findings(&plan_coverage::coverage(&tasks, &changed)) + plan_coverage::optional_findings(&changes.coverage(&tasks)) } /// Keeps a branch's commits on `coderhelm-wip/` when a run stops before its diff --git a/services/worker/src/passes/plan_coverage.rs b/services/worker/src/passes/plan_coverage.rs index b75f2f7ff..b7bd3d6c8 100644 --- a/services/worker/src/passes/plan_coverage.rs +++ b/services/worker/src/passes/plan_coverage.rs @@ -180,6 +180,10 @@ pub fn plan_tasks(tasks_md: &str) -> Vec { pub struct Coverage { pub done: Vec, pub missing: Vec, + /// The done tasks whose file only the branch this one is stacked on + /// changes: the pull request ships on top of it, so they are done there, + /// not in this branch's own diff. + pub on_base: Vec, } impl Coverage { @@ -248,10 +252,23 @@ pub fn settle_generated(mut cov: Coverage, settled: &[String]) -> Coverage { /// the coder's account: a task whose file the diff doesn't touch is not done /// whatever the coder's summary says. pub fn coverage(tasks: &[PlanTask], changed: &[String]) -> Coverage { + stacked_coverage(tasks, changed, &[]) +} + +/// [`coverage`] for a branch stacked on another open pull request's branch: +/// `on_base` is what that branch changes against the repository's default +/// branch. A task whose file only it changes is done there: the pull request +/// ships on top of it, and the coder, reading the branch, finds the file +/// already in its planned form. Counting such a task as missing sent a run +/// round after round with nothing to write until it was stopped. +pub fn stacked_coverage(tasks: &[PlanTask], changed: &[String], on_base: &[String]) -> Coverage { let mut cov = Coverage::default(); for t in tasks { if path_changed(&t.path, changed) { cov.done.push(t.clone()); + } else if path_changed(&t.path, on_base) { + cov.on_base.push(t.path.clone()); + cov.done.push(t.clone()); } else { cov.missing.push(t.clone()); } @@ -259,6 +276,52 @@ pub fn coverage(tasks: &[PlanTask], changed: &[String]) -> Coverage { cov } +/// What the plan check reads: the branch's own diff against its base and, +/// when that base is another open pull request's branch (not the +/// repository's default), the files that branch changes. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PlanChanges { + pub own: Vec, + pub on_base: Vec, +} + +impl PlanChanges { + pub fn coverage(&self, tasks: &[PlanTask]) -> Coverage { + stacked_coverage(tasks, &self.own, &self.on_base) + } +} + +/// Whether `base` is another branch the run is stacked on, not the +/// repository's default branch. +pub fn stacked_base(base: &str, default: &str) -> bool { + !default.is_empty() && !base.is_empty() && base != default +} + +/// [`changed_files`] plus, for a stacked base, what that base changes +/// against the repository's default branch. `None` when the branch's own +/// diff can't be read; a base whose diff can't be read adds nothing. +pub async fn plan_changes( + github: &GitHubClient, + owner: &str, + repo: &str, + base: &str, + branch: &str, +) -> Option { + let own = changed_files(github, owner, repo, base, branch).await?; + let default = github + .get_default_branch(owner, repo) + .await + .unwrap_or_default(); + let on_base = if stacked_base(base, &default) { + changed_files(github, owner, repo, &default, base) + .await + .unwrap_or_default() + } else { + Vec::new() + }; + Some(PlanChanges { own, on_base }) +} + /// What follows a coverage check. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Next { @@ -363,7 +426,12 @@ pub fn progress_note(cov: &Coverage) -> String { cov.total() )]; for t in &cov.done { - lines.push(format!("- [x] {}", t.path)); + let note = if cov.on_base.contains(&t.path) { + " (changed by the branch this one is stacked on)" + } else { + "" + }; + lines.push(format!("- [x] {}{note}", t.path)); } for t in &cov.missing { let note = if t.optional { @@ -537,19 +605,20 @@ pub async fn close_gaps( } let mut rounds = 0; loop { - let changed = changed_files( + let cov = plan_changes( w.github, &w.msg.repo_owner, &w.msg.repo_name, &w.msg.base_branch, w.branch, ) - .await?; - let cov = coverage(&tasks, &changed); + .await? + .coverage(&tasks); info!( run_id = w.run_id, done = cov.done.len(), missing = cov.missing.len(), + on_base = cov.on_base.len(), rounds, "Plan check" ); diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index dbaa6cfcd..e94377dae 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -76,6 +76,9 @@ pub const MAX_TRANSITIONS_WITHOUT_PROGRESS: u32 = 40; /// prompted this guard spent $41.96 in eleven), so this is five full steps with /// nothing to show, about half of that run. pub const MAX_SPEND_WITHOUT_PROGRESS_USD: f64 = 20.0; +/// Times the plan check's count may fall and its recovery still count as +/// progress; past that, only a new best does. +pub const MAX_TASK_DROPS: u32 = 2; /// The most pass transitions a normal large ticket makes between two progress /// events, with every fix round every check is allowed. A pass count is bounded @@ -191,8 +194,15 @@ pub struct GuardState { /// Spend since the last progress, from every model call of every step. #[serde(default)] pub spend_usd: f64, + /// The most tasks done so far. #[serde(default)] pub tasks_done: usize, + /// The last plan check's count (`None` before the first one). + #[serde(default)] + pub tasks_last: Option, + /// How many times the count fell below the one before it. + #[serde(default)] + pub task_drops: u32, #[serde(default)] pub work_done: bool, #[serde(default)] @@ -225,9 +235,21 @@ impl GuardState { pub fn apply(&mut self, p: &Progress) -> bool { let real = match p { Progress::TasksDone(n) => { - let more = *n > self.tasks_done; - self.tasks_done = self.tasks_done.max(*n); - more + let n = *n; + let prev = self.tasks_last.unwrap_or(self.tasks_done); + if n < prev { + self.task_drops = self.task_drops.saturating_add(1); + } + self.tasks_last = Some(n); + let more = n > self.tasks_done; + // Work the count lost (the base moved, a rebuild, a revert) + // being done again is progress, not a repeat of old news: + // measured from the last count, a bounded number of times so + // a count that keeps falling and rising still ends. + let recovered = + !more && n > prev && self.task_drops > 0 && self.task_drops <= MAX_TASK_DROPS; + self.tasks_done = self.tasks_done.max(n); + more || recovered } Progress::WorkDone => !std::mem::replace(&mut self.work_done, true), Progress::PrOpen => !std::mem::replace(&mut self.pr_open, true), @@ -551,9 +573,33 @@ pub async fn progress(state: &WorkerState, team_id: &str, run_id: &str, p: Progr // What was spent before this news counts against the time before it: real // progress clears the guard's count, never the run's lifetime one. l.guard.spend_usd += spent; + let drops = l.guard.task_drops; + let before = l.guard.tasks_last.unwrap_or(l.guard.tasks_done); if l.guard.apply(&p) { info!(run_id, progress = ?p, "Run guard: progress"); } + if l.guard.task_drops > drops { + // Never silent: a fall in finished tasks is work to find, not a run + // that merely stopped moving. + warn!( + run_id, + before, + now = l.guard.tasks_last.unwrap_or(0), + best = l.guard.tasks_done, + "Run guard: the plan check finds fewer tasks done than before" + ); + super::add_progress_note( + state, + team_id, + run_id, + &format!( + "The plan check now finds {} planned task(s) done, down from {before}: the \ + branch or what it is measured against changed. The run goes on from here.", + l.guard.tasks_last.unwrap_or(0) + ), + ) + .await; + } save(state, team_id, run_id, &l.guard, 0, 0, spent).await; } diff --git a/services/worker/src/passes/stack.rs b/services/worker/src/passes/stack.rs index ba33f3a41..0827b0f42 100644 --- a/services/worker/src/passes/stack.rs +++ b/services/worker/src/passes/stack.rs @@ -580,6 +580,42 @@ pub async fn for_ticket( Some(d) } +/// Whether a step of a run looks for the base an earlier step stacked it +/// on: only a later step of the same run whose message still names a base +/// other than the repository's default. +pub fn keeps_base(same_run: bool, incoming: &str, default: &str) -> bool { + same_run && super::plan_coverage::stacked_base(incoming, default) +} + +/// A later step of the same run keeps the base an earlier step stacked it +/// on, while that base is still an open pull request's branch in this +/// repository. Every step used to start again from the default branch: the +/// branch, already built on the other pull request, then read as copying +/// its commits, was rebuilt and force-pushed in every step, and the plan +/// check measured against a base that flipped between steps. +pub async fn kept( + github: &GitHubClient, + owner: &str, + repo: &str, + base: &str, +) -> Option { + let open = github.list_open_pulls(owner, repo).await.ok()?; + let full = format!("{owner}/{repo}").to_ascii_lowercase(); + let p = open.as_array()?.iter().find(|p| { + p["head"]["ref"].as_str() == Some(base) + && p["head"]["repo"]["full_name"] + .as_str() + .is_some_and(|f| f.eq_ignore_ascii_case(&full)) + })?; + Some(Dependency { + number: p["number"].as_u64().unwrap_or(0), + branch: base.to_string(), + title: p["title"].as_str().unwrap_or("").to_string(), + why: "An earlier step of this run stacked it on this pull request's branch.".to_string(), + ..Default::default() + }) +} + /// Right after the run's branch is ready, before any implementation: a /// branch kept from an earlier attempt (or retried) may carry copies of /// another open pull request's commits (that pull request's branch was