diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index cd499f74..ebac09b1 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -91,6 +91,14 @@ MAX_STEP_QUEUED_HOURS = int(os.environ.get("MAX_STEP_QUEUED_HOURS", "6")) ROUND_SWEEP_GRACE_SECONDS = 300 +# A run whose plan still owes a repository (services/common/src/plan_repos.rs, +# `plan_owed`) and that sits in "running" with no step is the worker's own +# plan sweep's to restart (services/worker/src/passes/plan_continue.rs, +# ORPHAN_LEASE_SECS, 20 minutes): this sweep leaves it alone for longer, and +# still ends it past this if the worker never did. A test there reads it. +PLAN_OWED_FIELD = "plan_owed" +MAX_PLAN_ORPHAN_MINUTES = 60 + # The absolute ceiling of a run. Mirrors services/worker/src/passes/run_ceiling.rs # (a test there reads these lines). The worker refuses a run over it at its one # entry point and at every model call; this reads the same counts from outside @@ -492,6 +500,21 @@ def step_queued(run, now): return now < queued + timedelta(hours=MAX_STEP_QUEUED_HOURS) +def plan_owed_wait(run, now): + """True while a "running" run that owes a repository of its plan is the + worker's plan sweep's to restart, not this sweep's to end.""" + try: + owed = int(run.get(PLAN_OWED_FIELD) or 0) + except (TypeError, ValueError): + owed = 0 + if owed <= 0: + return False + updated = _parse_time(run.get("updated_at") or run.get("created_at")) + if updated is None: + return False + return now < updated + timedelta(minutes=MAX_PLAN_ORPHAN_MINUTES) + + def over_ceiling(run): """(code, what) when the run is over its ceiling, else None.""" def num(name): @@ -733,7 +756,7 @@ def handler(event, context): }, "ProjectionExpression": ( "team_id, run_id, created_at, updated_at, title, current_pass, pass_history, #s, " - "step_queued_at, ceil_passes, ceil_continuations, ceil_worked_secs, ceil_spend_usd, " + "step_queued_at, plan_owed, ceil_passes, ceil_continuations, ceil_worked_secs, ceil_spend_usd, " "#round, pr_number, pr_url, error_message, #q, #w, #r, #oc, #notes, " + ", ".join(WAIT_FIELDS) ), @@ -771,6 +794,10 @@ def handler(event, context): if status == "running" and step_queued(item, now): # Its next step is queued and hasn't started. continue + if status == "running" and plan_owed_wait(item, now): + # Its plan owes a repository: the worker's plan sweep + # queues that step first. + continue if updated and updated < cutoff: stuck_runs.append(item) diff --git a/lambda/tests/test_stuck_run_cleanup.py b/lambda/tests/test_stuck_run_cleanup.py index 4d8ad0ba..a30fb8ee 100644 --- a/lambda/tests/test_stuck_run_cleanup.py +++ b/lambda/tests/test_stuck_run_cleanup.py @@ -220,6 +220,25 @@ def test_no_step_queued(self): self.assertFalse(sweep.step_queued({"updated_at": self.at(30)}, self.NOW)) +class PlanOwed(unittest.TestCase): + NOW = StepQueued.NOW + + def at(self, minutes_ago): + return (self.NOW - sweep.timedelta(minutes=minutes_ago)).isoformat() + + def test_a_run_owing_part_of_its_plan_is_the_workers_to_restart_first(self): + run = {"updated_at": self.at(30), "plan_owed": 1} + self.assertTrue(sweep.plan_owed_wait(run, self.NOW)) + + def test_past_the_longer_wait_it_is_swept_as_usual(self): + run = {"updated_at": self.at(61), "plan_owed": 1} + self.assertFalse(sweep.plan_owed_wait(run, self.NOW)) + + def test_nothing_owed_is_swept_as_usual(self): + self.assertFalse(sweep.plan_owed_wait({"updated_at": self.at(30)}, self.NOW)) + self.assertFalse(sweep.plan_owed_wait({"updated_at": self.at(30), "plan_owed": 0}, self.NOW)) + + class WaitingOnAPerson(unittest.TestCase): """A needs_input run never waits for nothing (services/common/src/run_wait.rs).""" diff --git a/services/common/src/run_ending.rs b/services/common/src/run_ending.rs index 9df3d77d..df5c999b 100644 --- a/services/common/src/run_ending.rs +++ b/services/common/src/run_ending.rs @@ -325,6 +325,37 @@ pub struct Write { /// is not held. pub const PLAN_GATE: &str = "(attribute_not_exists(#plan_owed) OR #plan_owed = :plan_owed_none)"; +/// Runs this process asked a done or waiting ending for since the last +/// [`take_gated`]: the step that asked reads, once it ends, whether the +/// gate refused it (the run still running with nothing queued) and queues +/// what the plan owes (`plan_continue::after_step`). +static GATED: std::sync::LazyLock>> = + std::sync::LazyLock::new(Default::default); + +fn note_gated(w: &Write) { + if let Some((_, run_id)) = w.sri.split_once('#') { + if !run_id.is_empty() { + if let Ok(mut g) = GATED.lock() { + // Only a worker step drains it: a process that never does + // (the gateway) keeps a bounded few. + if g.len() >= 256 { + g.clear(); + } + g.insert(run_id.to_string()); + } + } + } +} + +/// The runs a gated ending was asked for since the last call, and forgets +/// them. +pub fn take_gated() -> Vec { + GATED + .lock() + .map(|mut g| std::mem::take(&mut *g).into_iter().collect()) + .unwrap_or_default() +} + impl Write { pub fn status(&self) -> &'static str { self.status @@ -674,6 +705,7 @@ impl EndWrite for UpdateItemFluentBuilder { .expression_attribute_values(status_value, w.status_attr()) .expression_attribute_values(":sri", w.sri_attr()); if w.plan_gate { + note_gated(w); let cond = match b.get_condition_expression().clone() { Some(c) if !c.trim().is_empty() => format!("({c}) AND {PLAN_GATE}"), _ => PLAN_GATE.to_string(), @@ -1168,6 +1200,25 @@ mod tests { evidence: "the branch rule requires 1 approval from a person".into(), }), ); + // A gated ending asked for is remembered for the step that asked. + let asked = gate( + "R-gated-note", + &delivered( + st::COMPLETED, + 41, + "https://github.com/acme/bookstore-infra/pull/41", + ), + ); + let _ = offline_update() + .update_expression("SET #s = :s, status_run_id = :sri") + .run_status(":s", &asked); + let _ = offline_update() + .update_expression("SET #s = :s, status_run_id = :sri") + .run_status(":s", &working(Working::Running, "R-not-gated-note")); + let taken = take_gated(); + assert!(taken.contains(&"R-gated-note".to_string()), "{taken:?}"); + assert!(!taken.contains(&"R-not-gated-note".to_string())); + assert!(!take_gated().contains(&"R-gated-note".to_string())); for w in [&done, &waiting] { assert!(w.plan_gated()); let b = offline_update() diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index a0b4d04f..d74496f9 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -466,18 +466,26 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe match message { models::WorkerMessage::Ticket(msg) => { info!(team_id = %msg.team_id, ticket_id = %msg.ticket_id, "Starting ticket run"); + let started = passes::plan_continue::step_began(); + let team_id = msg.team_id.clone(); if let Err(e) = passes::orchestrate_ticket(&state, msg).await { // Already handled there: the run is failed with this reason // and the ticket told (a test holds orchestrate_ticket to it). error!(error = %common::run_fail::error_text(&*e), "Ticket run failed"); } + // An ending the end gate refused while the plan owes a + // repository leaves the run running with no step: the owed + // step is queued now (`plan_continue::after_step`). + passes::plan_continue::after_step(&state, &team_id, &started).await; } models::WorkerMessage::Feedback(msg) => { info!(team_id = %msg.team_id, run_id = %msg.run_id, "Processing feedback"); let team_id = msg.team_id.clone(); let run_id = msg.run_id.clone(); let retry_msg = msg.clone(); + let started = passes::plan_continue::step_began(); let round = passes::feedback::run(&state, msg).await; + passes::plan_continue::after_step(&state, &team_id, &started).await; // What people wrote on the ticket while the round worked is // read now, never left for the next event. passes::ticket_comments::after_round(&state, &team_id, &run_id).await; @@ -653,7 +661,9 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe info!(team_id = %msg.team_id, run_id = %msg.run_id, "Resuming run from webhook event"); let (team_id, run_id) = (msg.team_id.clone(), msg.run_id.clone()); let waiting = msg.clone(); + let started = passes::plan_continue::step_began(); let resumed = passes::resume::run(&state, msg).await; + passes::plan_continue::after_step(&state, &team_id, &started).await; passes::ticket_comments::after_round(&state, &team_id, &run_id).await; if let Err(e) = resumed { // GitHub refusing for a while (its hourly limit, a 5xx, no diff --git a/services/worker/src/passes/plan_continue.rs b/services/worker/src/passes/plan_continue.rs index 2b914f44..c8ece252 100644 --- a/services/worker/src/passes/plan_continue.rs +++ b/services/worker/src/passes/plan_continue.rs @@ -18,6 +18,12 @@ //! repository (and runs from before the record kept the plan: finished, //! with their own review asking for changes) are picked up the same way. //! +//! - [`after_step`]: a step whose done or waiting ending the end gate +//! refused leaves the run "running" with nothing queued: the owed step is +//! queued as that step ends. The sweep is the backstop: a "running" run +//! that owes a repository, with no step queued and no write for +//! [`ORPHAN_LEASE_SECS`], gets its step queued ([`orphaned`]). +//! //! Each continuation is claimed on the run (`plan_continues`, bounded by //! [`MAX_CONTINUES`]), so two deciders never start two steps, and a //! repository that can't be built ends the run with a typed stop rather @@ -39,6 +45,23 @@ pub const CONTINUES_FIELD: &str = "plan_continues"; /// The code version the sweep last read a run's plan for (runs from before /// the record kept it are read once per version). pub const CHECKED_FIELD: &str = "plan_checked_version"; +/// The run record's time its next step was queued (`steps::mark_queued`). +pub const STEP_QUEUED_FIELD: &str = "step_queued_at"; +/// How long a "running" run that owes a repository may go without a write +/// and with no step queued before the sweep reads it as having no step: a +/// step's own time (the worker's 15 minutes) and some. The stuck-run sweep +/// (`lambda/stuck-run-cleanup`) leaves such a run to this one for longer +/// (a test reads both). +pub const ORPHAN_LEASE_SECS: i64 = 20 * 60; + +/// What a claim on a "running" run must still find: no step queued since +/// `since` (the step that just ended started then, or the run's last write), +/// and, from the sweep, no write since the one it read. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct NoStep { + pub since: String, + pub updated: Option, +} /// What the run's plan asks now. #[derive(Debug, Clone, PartialEq, Eq)] @@ -149,12 +172,29 @@ pub async fn record(state: &WorkerState, team_id: &str, run_id: &str, plan: &Pla /// Claims one continuation: the run goes back to running, once per /// decider. False when another decision took it, or the bound is reached. -/// A claim whose step can't be queued is put back ([`release`]). -async fn claim(state: &WorkerState, item: &HashMap) -> bool { +/// A claim whose step can't be queued is put back ([`release`]). A +/// "running" run is claimed only while it has no step (`no_step`). +async fn claim( + state: &WorkerState, + item: &HashMap, + no_step: Option<&NoStep>, +) -> bool { let team_id = s(item, "team_id"); let run_id = s(item, "run_id"); let was = s(item, "status"); - let res = state + let mut cond = "#s = :was AND attribute_not_exists(guard_open) \ + AND (attribute_not_exists(#c) OR #c < :max)" + .to_string(); + let mut extra: Vec<(&str, AttributeValue)> = Vec::new(); + if let Some(ns) = no_step { + cond.push_str(" AND (attribute_not_exists(#q) OR #q < :since)"); + extra.push((":since", attr_s(&ns.since))); + if let Some(u) = &ns.updated { + cond.push_str(" AND updated_at = :upd"); + extra.push((":upd", attr_s(u))); + } + } + let mut req = state .dynamo .update_item() .table_name(&state.config.runs_table_name) @@ -164,10 +204,7 @@ async fn claim(state: &WorkerState, item: &HashMap) -> b "SET #s = :run, status_run_id = :sri, current_pass = :cp, updated_at = :t, \ #c = if_not_exists(#c, :zero) + :one REMOVE waiting_on, wait_reminded_at", ) - .condition_expression( - "#s = :was AND attribute_not_exists(guard_open) \ - AND (attribute_not_exists(#c) OR #c < :max)", - ) + .condition_expression(cond) .expression_attribute_names("#s", "status") .expression_attribute_names("#c", CONTINUES_FIELD) .expression_attribute_values(":run", attr_s(common::run_status::RUNNING)) @@ -180,9 +217,14 @@ async fn claim(state: &WorkerState, item: &HashMap) -> b .expression_attribute_values(":was", attr_s(was)) .expression_attribute_values(":zero", attr_n(0)) .expression_attribute_values(":one", attr_n(1)) - .expression_attribute_values(":max", attr_n(u64::from(MAX_CONTINUES))) - .send() - .await; + .expression_attribute_values(":max", attr_n(u64::from(MAX_CONTINUES))); + if no_step.is_some() { + req = req.expression_attribute_names("#q", STEP_QUEUED_FIELD); + } + for (k, v) in extra { + req = req.expression_attribute_values(k, v); + } + let res = req.send().await; match res { Ok(_) => true, Err(e) => { @@ -332,6 +374,7 @@ async fn start( item: &HashMap, plan: &PlanRepos, why: &str, + no_step: Option<&NoStep>, ) -> bool { let Some((mut msg, _)) = super::recheck::message_of(item) else { warn!( @@ -353,7 +396,7 @@ async fn start( info!(run_id, reason = %reason, "The rest of the plan waits for the usage limit"); return false; } - if !claim(state, item).await { + if !claim(state, item, no_step).await { return false; } super::checkpoint_back_to_plan(state, &msg.team_id, &run_id).await; @@ -413,6 +456,93 @@ pub async fn continue_if_owed(state: &WorkerState, team_id: &str, run_id: &str, continue_item(state, &item, why).await } +/// A "running" run whose plan still owes a repository and that has no step: +/// none was queued since `since`. Pure: the tests read it. +pub fn no_step_since( + item: &HashMap, + plan: &PlanRepos, + since: &str, +) -> bool { + s(item, "status") == common::run_status::RUNNING + && matches!(plan.next(), Next::Build(_)) + && !since.is_empty() + && s(item, STEP_QUEUED_FIELD) < since +} + +/// The sweep's backstop: a "running" run that owes a repository, with no +/// step queued after its last write, and no write for [`ORPHAN_LEASE_SECS`] +/// (no step can still be working on it). Pure: the tests read it. +pub fn orphaned( + item: &HashMap, + plan: &PlanRepos, + now: chrono::DateTime, +) -> Option { + let updated = s(item, "updated_at"); + let at = chrono::DateTime::parse_from_rfc3339(updated).ok()?; + let quiet = now.signed_duration_since(at.with_timezone(&chrono::Utc)); + (quiet.num_seconds() >= ORPHAN_LEASE_SECS && no_step_since(item, plan, updated)).then(|| { + NoStep { + since: updated.to_string(), + updated: Some(updated.to_string()), + } + }) +} + +/// A step begins: endings asked for before it (by other messages) are not +/// its own. Returns its start time for [`after_step`]. +pub fn step_began() -> String { + let _ = common::run_ending::take_gated(); + chrono::Utc::now().to_rfc3339() +} + +/// After a step ends (it started at `started`): each run it asked a done +/// or waiting ending for (`run_ending::take_gated`) that is still running +/// with nothing queued since, while its plan owes a repository, had that +/// ending refused by the end gate (`run_ending::PLAN_GATE`) and has no +/// step. The owed step is queued now. Returns how many were queued. +pub async fn after_step(state: &WorkerState, team_id: &str, started: &str) -> usize { + let mut queued = 0; + for run_id in common::run_ending::take_gated() { + if team_id.is_empty() { + continue; + } + let Ok(out) = 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)) + .consistent_read(true) + .send() + .await + else { + continue; + }; + let Some(item) = out.item else { continue }; + let Some(plan) = of_item(&item) else { continue }; + if !no_step_since(&item, &plan, started) || !wants_continue(&item, &plan) { + continue; + } + warn!(run_id, owed = ?plan.owed(), "The end gate refused the step's ending and nothing is queued: queuing what the plan owes"); + let ns = NoStep { + since: started.to_string(), + updated: None, + }; + if start( + state, + &item, + &plan, + "the step's ending waited for the rest of the plan", + Some(&ns), + ) + .await + { + queued += 1; + } + } + queued +} + async fn continue_item( state: &WorkerState, item: &HashMap, @@ -424,17 +554,29 @@ async fn continue_item( if !matches!(plan.next(), Next::Build(_)) { return Owed::Nothing; } + let status = s(item, "status"); + // "Running" past the lease with nothing queued: no step is on it (its + // ending was refused by the end gate and nothing queued the next one). + if status == common::run_status::RUNNING { + if let Some(ns) = orphaned(item, &plan, chrono::Utc::now()) { + if wants_continue(item, &plan) + && start(state, item, &plan, "it was running with no step", Some(&ns)).await + { + return Owed::Building; + } + } + } // A step is working on it already. if [ common::run_status::RUNNING, common::run_status::QUEUED, common::run_status::PENDING, ] - .contains(&s(item, "status")) + .contains(&status) { return Owed::Building; } - if wants_continue(item, &plan) && start(state, item, &plan, why).await { + if wants_continue(item, &plan) && start(state, item, &plan, why, None).await { return Owed::Building; } if spent(item, &plan) { @@ -576,6 +718,89 @@ mod tests { } } + #[test] + fn a_running_run_with_no_step_is_found_after_its_step_and_by_the_sweep() { + let plan = PlanRepos::of_tasks("acme/bookstore-api", TASKS).unwrap(); + let mut run = item("running", &plan, &[("acme/bookstore-infra", 41)]); + run.insert("updated_at".into(), attr_s("2026-12-03T10:05:00+00:00")); + // The step started at 10:00 and queued nothing: its done write was + // refused, and the run has no step. + let started = "2026-12-03T10:00:00+00:00"; + assert!(no_step_since(&run, &plan, started)); + // A step that queued the next one leaves it alone. + let mut handed = run.clone(); + handed.insert( + STEP_QUEUED_FIELD.into(), + attr_s("2026-12-03T10:04:00+00:00"), + ); + assert!(!no_step_since(&handed, &plan, started)); + // Nothing owed, or not running: nothing to do. + let both = item( + "running", + &plan, + &[("acme/bookstore-infra", 41), ("acme/bookstore-api", 12)], + ); + assert!(!no_step_since(&both, &of_item(&both).unwrap(), started)); + let done = item("completed", &plan, &[("acme/bookstore-infra", 41)]); + assert!(!no_step_since(&done, &plan, started)); + + // The sweep: past the lease with no step queued after the last write. + let at = |m: i64| { + chrono::DateTime::parse_from_rfc3339("2026-12-03T10:05:00+00:00") + .unwrap() + .with_timezone(&chrono::Utc) + + chrono::Duration::minutes(m) + }; + assert_eq!(orphaned(&run, &plan, at(5)), None); + let ns = orphaned(&run, &plan, at(ORPHAN_LEASE_SECS / 60)).unwrap(); + assert_eq!(ns.since, "2026-12-03T10:05:00+00:00"); + assert_eq!(ns.updated.as_deref(), Some("2026-12-03T10:05:00+00:00")); + // A step queued after the last write is waiting for the queue. + let mut queued = run.clone(); + queued.insert( + STEP_QUEUED_FIELD.into(), + attr_s("2026-12-03T10:06:00+00:00"), + ); + assert_eq!(orphaned(&queued, &plan, at(60)), None); + // A step queued before the last write started and is gone. + let mut died = run.clone(); + died.insert( + STEP_QUEUED_FIELD.into(), + attr_s("2026-12-03T09:50:00+00:00"), + ); + assert!(orphaned(&died, &plan, at(60)).is_some()); + + // Wired: every step that can end a run checks it, and the sweep + // reads a running run before calling it building. + let main = include_str!("../main.rs"); + assert!( + main.matches("passes::plan_continue::after_step(&state, &team_id, &started)") + .count() + >= 3 + ); + assert_eq!( + main.matches("let started = passes::plan_continue::step_began();") + .count(), + main.matches("passes::plan_continue::after_step(").count() + ); + let src = include_str!("plan_continue.rs"); + let body = &src[src.find("async fn continue_item(").unwrap()..]; + assert!( + body.find("orphaned(item, &plan").unwrap() + < body + .find("return Owed::Building;\n }\n if wants") + .unwrap() + ); + // The stuck-run sweep leaves such a run to this one for longer. + let lambda = include_str!("../../../../lambda/stuck-run-cleanup/handler.py"); + let minutes: i64 = lambda + .lines() + .find_map(|l| l.strip_prefix("MAX_PLAN_ORPHAN_MINUTES = ")) + .and_then(|v| v.trim().parse().ok()) + .expect("the stuck-run sweep names its wait"); + assert!(ORPHAN_LEASE_SECS < minutes * 60); + } + #[test] fn a_claim_whose_step_isnt_queued_is_put_back_as_the_record_had_it() { let plan = PlanRepos::of_tasks("acme/bookstore-api", TASKS).unwrap();