Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion lambda/stuck-run-cleanup/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
),
Expand Down Expand Up @@ -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)

Expand Down
19 changes: 19 additions & 0 deletions lambda/tests/test_stuck_run_cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)."""

Expand Down
51 changes: 51 additions & 0 deletions services/common/src/run_ending.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::Mutex<std::collections::BTreeSet<String>>> =
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<String> {
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
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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()
Expand Down
10 changes: 10 additions & 0 deletions services/worker/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -466,18 +466,26 @@ async fn handle_message_inner(state: Arc<WorkerState>, 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;
Expand Down Expand Up @@ -653,7 +661,9 @@ async fn handle_message_inner(state: Arc<WorkerState>, 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
Expand Down
Loading