diff --git a/docs/incidents.md b/docs/incidents.md index 72d34d785..b2e78c04b 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -101,6 +101,7 @@ pipeline still calls it there. | br. `br_description_writer_upgrade` | After the description writer was upgraded (a final review in the one save, the repository's template as the structure), a pull request opened the day before kept its old text: six checks "Not run: still running when this was written", the file to read first and the way back said twice, filler and a raw page id. Its head had not moved and its checked text was unchanged, so its stamp said current and nothing rebuilt it. | The stamp names the writer version (`description::WRITER`, raised with every change to what a description says or how it is laid out); a description built by another writer, or before the version, is not current. The pull request watch's sweep catches up open pull requests CoderHelm opened, whatever the age of their run: a few per team each sweep (`pr_watch::CATCH_UP_PER_TEAM`), inside its GitHub budget, each rebuilt once and marked on its run. A description still wholly CoderHelm's is built again from the facts of the head alone: nothing of the old text is kept, not even in a fold, except a line that closes an issue. A description with no CoderHelm stamp, or whose checked text a person changed, is left as it is. | | bs. `bs_cut_plan_revision` | A ticket with a long history was planned, and the plan check sent the plan back with two open items. The revision reached the output limit partway through its last block. The planner was told the coder's note ("make a change in small edit_file calls"), wrote only its decision block again, and the worker read only that last turn: no tasks, no design. The run failed with "empty or malformed plan ... retry the run" and the first plan was thrown away. | A planner's cut answer is continued where it stopped and read together with what came before the cut, file by file (`plan_sections`). A cut turn's note fits its loop: the coder's edit note only where there are edit tools, the planner's "continue the document" note, a shorter answer for everyone else. A revision that comes back empty, cut off or malformed never replaces a valid file, and a send-back asks for only the files that change. Files still missing are asked for alone, twice at most, the second with a larger output budget. A plan still not usable is planned again in a fresh step, then reported as CoderHelm's own failure, saying what it lacked. No run tells a person to retry it. | | bt. `bt_proof_answer_closes` | A security update's own review asked for proof of the build and unit tests on the head. The fix rounds changed no code: the second ran every check on the head, all passing, and one runtime check it started was cut short by the step's time. The ledger counted that as a block, the round pushed nothing so no review read the head again, and the draft was held for a person ("Fix them on the branch, or remove a finding") while the merge standing said no person was needed. | A round that pushed nothing is read by a review of the same head, with the round's account in the reviewer's context, and a finding answered with proof closes there. A command, check or codegen a step is too short to start is owed: the pass continues in a fresh step that runs it first, and a round cut short by time is never a block. Nothing on CoderHelm's side holds a draft for a person: what is left after every approach is listed as CoderHelm's note and the pull request goes ready, with CoderHelm's verdict kept so nothing merges over it. A stuck run is sent back to its review on the next look of the ready sweep or the pull request's watch. | +| bu. `bu_held_draft_after_release` | A release fixed how a held draft is finished, and the run it was for never got there. Its hold had been decided 22 minutes before the release and the draft sweep re-decides a hold only once it is an hour old: the first sweep after the release came six seconds early and only peeked. The next skipped the installation for GitHub's budget, logging "it looks again in about 1 min", though nothing ran until the next scheduled sweep. The pull request watch spent its hourly cap on merged pull requests and looked at the held draft in none of three sweeps. A person reset the run 67 minutes after the release. | A hold carries the version of the code that decided it, and the sweep decides a hold other code wrote on its first pass after a release, decisions before peeks. A sweep GitHub's budget skipped runs again once the budget refills (one follow-up per gap, claimed). The pull request watch looks at held drafts first. | ## Adding a case diff --git a/services/common/src/draft_hold.rs b/services/common/src/draft_hold.rs index 2ed0bcc22..3e5401fe8 100644 --- a/services/common/src/draft_hold.rs +++ b/services/common/src/draft_hold.rs @@ -110,6 +110,12 @@ pub struct DraftHold { /// drafts run, and it is still being proven (or failed its proof). #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub ready: bool, + /// The version of the code that decided it (the worker's + /// `checks_version`). A hold another version wrote is decided again on + /// the next sweep: a release that changes what holds a draft reaches + /// every held draft at once, never an hour later. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub version: String, } /// A wait whose reason hasn't changed on the same head for this long is a @@ -139,6 +145,7 @@ impl DraftHold { checked_at: now, head: String::new(), ready: false, + version: String::new(), }) } @@ -179,6 +186,11 @@ impl DraftHold { self } + /// Whether code other than `version` decided it. + pub fn other_version(&self, version: &str) -> bool { + self.version != version + } + /// Whether a person must act (the run waits on them). pub fn needs_person(&self) -> bool { matches!(self.kind, Kind::Held | Kind::Failed) diff --git a/services/worker/src/clients/github_budget.rs b/services/worker/src/clients/github_budget.rs index 20fe49972..b6efaaa9f 100644 --- a/services/worker/src/clients/github_budget.rs +++ b/services/worker/src/clients/github_budget.rs @@ -466,6 +466,8 @@ pub fn held(installation_id: u64) -> bool { pub struct SweepGate { caller: &'static str, skipped: HashSet, + /// The shortest wait a skip named, in seconds. + soonest: Option, } impl SweepGate { @@ -473,9 +475,18 @@ impl SweepGate { Self { caller, skipped: HashSet::new(), + soonest: None, } } + /// Seconds until an installation this sweep skipped may spend again + /// (the shortest wait), `None` when it skipped none. The skip line says + /// "it looks again in about N min": the sweep's caller makes that true + /// (`sweep_follow_up`). + pub fn retry_in(&self) -> Option { + self.soonest + } + /// Installations this sweep skipped. pub fn skipped(&self) -> usize { self.skipped.len() @@ -499,6 +510,7 @@ impl SweepGate { return true; }; self.skipped.insert(installation_id); + self.soonest = Some(self.soonest.map_or(wait_secs, |s| s.min(wait_secs))); info!( installation = installation_id, caller = self.caller, diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index bfc8d7475..4a98d76d6 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -680,6 +680,9 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe descriptions_rebuilt = ?watch.caught_up, "Pull request watch sweep done" ); + // A sweep GitHub's budget skipped looks again once the budget + // refills, not at the next scheduled sweep. + passes::ready::sweep_follow_up(&state, &[drafts.retry_in, watch.retry_in]).await; // Deploy counts that stopped between passes carry on without // waiting for someone to open Analytics. let resumed = as_sweep(who::SWEEP_DEPLOYS, passes::deploy_stats::sweep(&state)).await; diff --git a/services/worker/src/passes/incidents/bu_held_draft_after_release.rs b/services/worker/src/passes/incidents/bu_held_draft_after_release.rs new file mode 100644 index 000000000..1b7eb1404 --- /dev/null +++ b/services/worker/src/passes/incidents/bu_held_draft_after_release.rs @@ -0,0 +1,165 @@ +//! bu. A release fixed how a finished run's held draft is finished (a round +//! that answered a review finding with proof is read by a review of the +//! same head). The run it was for never got there. Its hold had been +//! decided 22 minutes before the release, and the draft sweep re-decides a +//! held draft only once its hold is an hour old: the first sweep after the +//! release came six seconds early and only peeked. The next one, a quarter +//! hour later, found less than half of GitHub's hourly budget left and +//! skipped the installation, logging "it looks again in about 1 min"; the +//! budget refilled ten seconds later, but nothing ran until the next +//! scheduled sweep. The pull request watch, which also finishes held +//! drafts, looked at none of its candidates for three sweeps: its hourly +//! cap went to merged pull requests looked at less recently. A person reset +//! the run 67 minutes after the release. +//! +//! Guarantee: a hold carries the version of the code that decided it, and +//! the sweep decides a hold other code wrote on its first pass after a +//! release, decisions before peeks. A sweep GitHub's budget skipped runs +//! again once the budget refills, as its log line says. The pull request +//! watch looks at held drafts first. + +use crate::passes::{pr_watch, ready}; +use common::draft_hold::{DraftHold, Kind, Reason}; + +const OLD: &str = "older-code"; +const NEW: &str = "this-code"; + +fn held_by(version: &str, checked_secs_ago: i64) -> DraftHold { + let mut h = DraftHold::new( + Kind::Held, + vec![Reason::new( + "1 finding from CoderHelm's review is still open", + "", + )], + 7, + "", + ) + .unwrap(); + h.version = version.into(); + h.checked_at = (chrono::Utc::now() - chrono::Duration::seconds(checked_secs_ago)).to_rfc3339(); + h +} + +fn candidate(status: &str, hold: Option) -> ready::Candidate { + ready::Candidate { + team_id: "TEAM#1".into(), + run_id: "01RUNHELD".into(), + status: status.into(), + owner: "acme".into(), + repo: "api".into(), + pr: 7, + installation_id: 41, + hold, + } +} + +#[test] +fn a_hold_older_code_decided_is_decided_again_on_the_first_sweep() { + let now = chrono::Utc::now(); + // Decided 59 minutes 54 seconds ago, by the code before the release. + let stuck = candidate("completed", Some(held_by(OLD, 3594))); + assert_eq!( + ready::sweep_step(&stuck, now, NEW), + ready::SweepStep::Decide + ); + // The same hold decided by this code is only peeked at until it is old. + let current = candidate("completed", Some(held_by(NEW, 3594))); + assert_eq!( + ready::sweep_step(¤t, now, NEW), + ready::SweepStep::Peek + ); + // A run waiting on a person for its draft is decided again too. + let waiting = candidate("needs_input", Some(held_by(OLD, 60))); + assert_eq!( + ready::sweep_step(&waiting, now, NEW), + ready::SweepStep::Decide + ); + // A run still working is left to finish. + let working = candidate("running", Some(held_by(OLD, 60))); + assert_eq!( + ready::sweep_step(&working, now, NEW), + ready::SweepStep::Skip + ); + // A hold stored before holds carried a version is other code's. + let stored: DraftHold = serde_json::from_value(serde_json::json!({ + "kind": "held", + "reasons": [{"what": "1 finding from CoderHelm's review is still open"}], + "pr_number": 7, + "checked_at": now.to_rfc3339() + })) + .unwrap(); + assert!(stored.other_version(NEW)); + // Every hold the ready decision records names this code. + let src = include_str!("../ready.rs"); + let record = super::fixture::fn_src(src, "\nasync fn record_hold("); + assert!(record.contains("hold.version = super::proof::checks_version()")); +} + +#[test] +fn decisions_come_before_peeks_so_a_short_budget_reaches_them() { + let now = chrono::Utc::now(); + let peek = |n: &str| ready::Candidate { + run_id: n.into(), + ..candidate("completed", Some(held_by(NEW, 60))) + }; + let stuck = ready::Candidate { + run_id: "stuck".into(), + ..candidate("completed", Some(held_by(OLD, 60))) + }; + let order = ready::sweep_order(vec![peek("a"), peek("b"), stuck, peek("c")], now, NEW); + let ids: Vec<&str> = order.iter().map(|c| c.run_id.as_str()).collect(); + assert_eq!(ids, vec!["stuck", "a", "b", "c"]); +} + +#[test] +fn a_sweep_the_budget_skipped_runs_again_once_it_refills() { + use crate::clients::github_budget::SweepGate; + use common::github_budget::{caller as who, Budget}; + let id = 990_041; + let now = chrono::Utc::now().timestamp().max(0) as u64; + // Less than half the hour's budget left, refilling in ten seconds. + crate::clients::github::record_budget( + id, + Budget { + remaining: 2_268, + limit: 5_000, + reset: now + 10, + }, + ); + let mut gate = SweepGate::new(who::SWEEP_DRAFTS); + assert!(!gate.check(id, 15, now)); + let wait = gate.retry_in().expect("the skip names its wait"); + assert!(wait <= 60, "{wait}"); + // The sweeps run again in about that long, not at the next schedule. + let delay = ready::follow_up_delay(&[Some(wait), None]).unwrap(); + assert!((30..=60).contains(&delay), "{delay}"); + assert_eq!(ready::follow_up_delay(&[None, None]), None); + // A wait past the next scheduled sweep is that sweep's. + assert_eq!(ready::follow_up_delay(&[Some(2_000)]), None); + assert_eq!(ready::follow_up_delay(&[Some(400), Some(90)]), Some(90)); + // Wired after the sweeps, with both sweeps' waits. + let main = include_str!("../../main.rs"); + assert!( + main.contains("passes::ready::sweep_follow_up(&state, &[drafts.retry_in, watch.retry_in])") + ); +} + +#[test] +fn the_pull_request_watch_looks_at_held_drafts_first() { + let c = |run: &str, at: &str, held: bool| pr_watch::Candidate { + run_id: run.into(), + looked_at: at.into(), + draft_held: held, + ..Default::default() + }; + let picked = pr_watch::order( + vec![ + c("merged-1", "", false), + c("merged-2", "2026-01-01T00:00:00Z", false), + c("held", "2026-01-02T00:00:00Z", true), + ], + 2, + ); + let ids: Vec<&str> = picked.iter().map(|c| c.run_id.as_str()).collect(); + assert_eq!(ids, vec!["held", "merged-1"]); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 3e832ae61..34a3090a9 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -60,6 +60,7 @@ mod br_description_writer_upgrade; mod bs_cut_plan_revision; mod bt_proof_answer_closes; mod bu_coder_shell_refusals; +mod bu_held_draft_after_release; mod c_codegen_egress; mod d_echoed_markers; mod e_large_generated_output; diff --git a/services/worker/src/passes/incidents/s_silent_draft.rs b/services/worker/src/passes/incidents/s_silent_draft.rs index fa9d51a75..48b1d3e5a 100644 --- a/services/worker/src/passes/incidents/s_silent_draft.rs +++ b/services/worker/src/passes/incidents/s_silent_draft.rs @@ -243,7 +243,10 @@ fn the_sweep_heals_a_finished_run_left_a_draft_with_no_reason() { installation_id: 41, hold: None, }; - assert_eq!(ready::sweep_step(&casualty, now), ready::SweepStep::Decide); + assert_eq!( + ready::sweep_step(&casualty, now, ""), + ready::SweepStep::Decide + ); // A person's draft and a closed pull request are respected by the // decision it makes. let theirs = Facts { diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 1b8dbcfd0..f2ea85a41 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -315,6 +315,9 @@ pub struct Candidate { pub writer: String, /// When the run last changed (RFC 3339). pub updated_at: String, + /// Its pull request is held as a draft (`draft_hold` on the run): the + /// run's work waits on CoderHelm's next look, so it is looked at first. + pub draft_held: bool, } pub fn candidate_of(item: &HashMap) -> Option { @@ -358,15 +361,20 @@ pub fn candidate_of(item: &HashMap) -> Option .unwrap_or_default(), writer: s(DESCRIPTION_WRITER), updated_at: s("updated_at"), + draft_held: item.contains_key(common::draft_hold::FIELD), }; (pr > 0 && c.installation_id > 0 && !c.team_id.is_empty() && !c.run_id.is_empty()).then_some(c) } -/// The candidates a sweep reads, least recently looked at first. +/// The candidates a sweep reads: pull requests held as drafts first (their +/// run's work waits on this look), then least recently looked at first. A +/// held draft once went three sweeps without a look while the sweep's +/// hourly budget went to merged pull requests looked at less recently. pub fn order(mut all: Vec, max: usize) -> Vec { all.sort_by(|a, b| { - a.looked_at - .cmp(&b.looked_at) + b.draft_held + .cmp(&a.draft_held) + .then_with(|| a.looked_at.cmp(&b.looked_at)) .then_with(|| a.run_id.cmp(&b.run_id)) }); all.truncate(max); @@ -926,6 +934,9 @@ pub struct SweepReport { pub looked_at: usize, /// Installations skipped this cycle for GitHub's budget. pub skipped_installations: usize, + /// Seconds until a skipped installation may spend again + /// (`SweepGate::retry_in`). + pub retry_in: Option, /// `owner/repo#pr: act` for each pull request picked back up. pub acted: Vec, /// `owner/repo#pr` for each description the catch-up rebuilt by this @@ -1006,6 +1017,7 @@ pub async fn sweep(state: &WorkerState) -> SweepReport { } report.caught_up = catch_up(state, &mut budget, &mut clients).await; report.skipped_installations = budget.skipped(); + report.retry_in = budget.retry_in(); report } diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index e5f44b12c..5b2cab597 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -1626,7 +1626,9 @@ async fn record_hold(state: &WorkerState, team_id: &str, run_id: &str, hold: Dra return; } let before = run_hold(state, team_id, run_id).await; - let hold = hold.continuing(before.as_ref().and_then(|(_, h)| h.as_ref())); + let mut hold = hold.continuing(before.as_ref().and_then(|(_, h)| h.as_ref())); + // Which code decided it: another version decides it again at once. + hold.version = super::proof::checks_version().to_string(); let now = chrono::Utc::now().to_rfc3339(); // `:held` is a condition value, never a status written here: the write // goes through `NeedsInput::needs_input`. @@ -1888,8 +1890,13 @@ pub enum SweepStep { Skip, } -/// Pure: what the sweep does with a candidate at `now`. -pub fn sweep_step(c: &Candidate, now: chrono::DateTime) -> SweepStep { +/// Pure: what the sweep does with a candidate at `now`, run by the code of +/// `version` (`proof::checks_version`). A hold that other code decided is +/// decided again on this sweep, whatever its age: after a release a held +/// draft once waited out the hour since its last decision, the one sweep +/// that hour skipped it for GitHub's budget, and a person reset the run +/// before the fix that would have finished it ever looked. +pub fn sweep_step(c: &Candidate, now: chrono::DateTime, version: &str) -> SweepStep { let finished = matches!( c.status.as_str(), common::run_status::COMPLETED | common::run_status::SUCCESS @@ -1904,6 +1911,7 @@ pub fn sweep_step(c: &Candidate, now: chrono::DateTime) -> SweepSte // Waiting on a person for something that isn't the draft. (None, false, _) => SweepStep::Skip, (Some(h), _, _) if h.stale(RECHECK_HELD_SECS, now) => SweepStep::Decide, + (Some(h), true, _) | (Some(h), _, true) if h.other_version(version) => SweepStep::Decide, (Some(_), true, _) | (Some(_), _, true) => SweepStep::Peek, (Some(_), false, false) => SweepStep::Skip, } @@ -1946,6 +1954,9 @@ pub struct SweepReport { pub decided: usize, /// `owner/repo#pr: outcome` for each one decided. pub settled: Vec, + /// GitHub's budget skipped an installation this sweep: seconds until it + /// may spend again (`SweepGate::retry_in`). + pub retry_in: Option, } /// Finished runs (in the last [`SWEEP_WINDOW_DAYS`]) whose pull request @@ -2001,11 +2012,14 @@ pub async fn sweep(state: &WorkerState) -> SweepReport { // GitHub's budget and says a skip once per installation. let mut budget = crate::clients::github_budget::SweepGate::new(common::github_budget::caller::SWEEP_DRAFTS); + let version = super::proof::checks_version(); + // Decisions first, so a short budget goes to the drafts that need one. + let candidates = sweep_order(candidates, now, version); for c in candidates { if report.decided >= SWEEP_MAX_DECISIONS { break; } - let step = sweep_step(&c, now); + let step = sweep_step(&c, now, version); if step == SweepStep::Skip || c.installation_id == 0 || c.team_id.is_empty() { continue; } @@ -2061,9 +2075,77 @@ pub async fn sweep(state: &WorkerState) -> SweepReport { .settled .push(format!("{}/{}#{}: {outcome:?}", c.owner, c.repo, c.pr)); } + report.retry_in = budget.retry_in(); report } +/// How often the sweeps run (the `review_sweep` schedule), in seconds. +pub const SWEEP_EVERY_SECS: u64 = 15 * 60; +/// The settings item a follow-up sweep is claimed under, once per gap. +const FOLLOW_UP_PK: &str = "SWEEP"; +const FOLLOW_UP_SK: &str = "review_sweep#follow_up"; + +/// When to run the sweeps again after GitHub's budget skipped an +/// installation (`waits`: each sweep's `retry_in`): the shortest wait, when +/// it ends well before the next scheduled sweep. A skip at a quarter past +/// once waited fifteen minutes for a budget that refilled ten seconds later. +pub fn follow_up_delay(waits: &[Option]) -> Option { + let soonest = waits.iter().flatten().copied().min()?; + (soonest + 60 < SWEEP_EVERY_SECS).then_some(soonest.clamp(30, SWEEP_EVERY_SECS - 60)) +} + +/// Runs the sweeps again once the budget that skipped them refills +/// ([`follow_up_delay`]): one delayed `review_sweep` per gap, claimed so +/// several workers never send more than one. +pub async fn sweep_follow_up(state: &WorkerState, waits: &[Option]) { + let Some(delay) = follow_up_delay(waits) else { + return; + }; + if state.config.ticket_queue_url.is_empty() { + return; + } + let claimed = common::claim::claim( + &state.dynamo, + &state.config.settings_table_name, + FOLLOW_UP_PK, + FOLLOW_UP_SK, + delay + 60, + ) + .await; + if !matches!(claimed, common::claim::Claim::Won) { + return; + } + let sent = state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(serde_json::json!({"type": "review_sweep"}).to_string()) + .delay_seconds(delay as i32) + .send() + .await; + match sent { + Ok(_) => info!( + delay_secs = delay, + "GitHub's budget skipped a sweep: the sweeps run again once it refills" + ), + Err(e) => warn!(error = %e, "Could not send the follow-up sweep"), + } +} + +/// The candidates in the order the sweep takes them: those it decides +/// first (in their scan order), then those it only peeks at. +pub fn sweep_order( + candidates: Vec, + now: chrono::DateTime, + version: &str, +) -> Vec { + let (mut decide, peek): (Vec, Vec) = candidates + .into_iter() + .partition(|c| sweep_step(c, now, version) == SweepStep::Decide); + decide.extend(peek); + decide +} + #[cfg(test)] mod tests { use super::*; @@ -2501,16 +2583,20 @@ mod tests { installation_id: 1, hold: None, }; - assert_eq!(sweep_step(&c, now), SweepStep::Decide); + assert_eq!(sweep_step(&c, now, ""), SweepStep::Decide); let held = DraftHold::new(Kind::Held, vec![Reason::new("a", "")], 583, "").unwrap(); let c2 = Candidate { status: "needs_input".into(), hold: Some(held.clone()), ..c.clone() }; - assert_eq!(sweep_step(&c2, now), SweepStep::Peek); + assert_eq!(sweep_step(&c2, now, ""), SweepStep::Peek); assert_eq!( - sweep_step(&c2, now + chrono::Duration::seconds(RECHECK_HELD_SECS + 1)), + sweep_step( + &c2, + now + chrono::Duration::seconds(RECHECK_HELD_SECS + 1), + "" + ), SweepStep::Decide ); // Waiting on a person for something that isn't the draft. @@ -2519,7 +2605,7 @@ mod tests { hold: None, ..c.clone() }; - assert_eq!(sweep_step(&c3, now), SweepStep::Skip); + assert_eq!(sweep_step(&c3, now, ""), SweepStep::Skip); } #[test]