diff --git a/changelog.d/394.fixed.md b/changelog.d/394.fixed.md new file mode 100644 index 00000000..eb2a095d --- /dev/null +++ b/changelog.d/394.fixed.md @@ -0,0 +1,7 @@ +- A team run whose worker was lost, restarted or terminated by the runtime is no longer + retried when the team-run loop or the outcome reconciler sees the failed step before the + platform closes the run: the "without retry" decision is now read from the stored + execution error, also across API restarts, and nothing runs after that step in a workflow. + Refreshing a terminated worker launch no longer reports a failure (event, audit entry, + failed team step) for an execution that another path had already ended, including one that + succeeded (#394). diff --git a/crates/orbit-api/src/handlers/teams.rs b/crates/orbit-api/src/handlers/teams.rs index ae2cfd07..1cc4a8f9 100644 --- a/crates/orbit-api/src/handlers/teams.rs +++ b/crates/orbit-api/src/handlers/teams.rs @@ -2184,6 +2184,21 @@ fn run_definition(run: &TeamRun) -> Option { } async fn advance_claimed(state: &AppState, run: TeamRun) -> anyhow::Result<()> { + // A step whose worker went away may have had side effects, so the run ends without + // a retry and nothing runs after that step. The reaper and the launch poller apply + // that through `fail_team_run_for_execution`, but this tick can see the failed + // execution first, or the API may have restarted in between (#394). Decide from the + // stored execution so whichever path gets here first ends the run the same way. + if let Some(execution) = state + .store + .team_run_execution_failed_with(run.id, &ended_without_retry_codes()) + .await? + { + fail_team_run_for_execution(state, &execution).await?; + if state.store.get_team_run(run.org_id, run.id).await?.status != "running" { + return Ok(()); + } + } if let Some(definition) = run_definition(&run) { if let Some(workflow) = definition.workflow() { return crate::team_workflow::advance(state, &run, &definition, workflow).await; @@ -2264,6 +2279,20 @@ pub(crate) fn execution_error_message(execution: &ExecutionRecord) -> String { .unwrap_or_else(|| "worker failed".into()) } +/// Error codes of executions the platform ended because their worker went away: a lost +/// worker or boot (`worker_lost`), a runtime termination (`worker_oom`, `worker_evicted`, +/// `worker_exited`) or a harness that stopped reporting (`harness_unresponsive`). Their +/// outcome is unknown, so their team run is neither continued nor retried (#343, #394). +/// `worker_did_not_start` is not one of them: nothing ran, so the queue may retry it. +pub(crate) fn ended_without_retry_codes() -> Vec<&'static str> { + orbit_contracts::WorkerTerminationReason::ALL + .iter() + .copied() + .filter(|code| *code != "worker_did_not_start") + .chain(["harness_unresponsive"]) + .collect() +} + /// Fail the team run whose current step owns an execution ended by the platform (worker /// restart, lost heartbeat or expired lease). Both writes are conditional, so repeated /// calls from the heartbeat and reaper paths are safe. @@ -2531,3 +2560,26 @@ mod prompt_separation_tests { assert_eq!(configured_goal(&input), "goal"); } } + +#[cfg(test)] +mod ended_without_retry_tests { + use super::ended_without_retry_codes; + + #[test] + fn lost_and_terminated_workers_end_without_retry_but_a_worker_that_never_started_does_not() { + let codes = ended_without_retry_codes(); + for code in [ + "worker_lost", + "worker_oom", + "worker_evicted", + "worker_exited", + "harness_unresponsive", + ] { + assert!(codes.contains(&code), "{code}"); + } + // Nothing ran, so the queue keeps its retry (#399), also once it is a termination + // reason of its own. + assert!(!codes.contains(&"worker_did_not_start")); + assert!(!codes.contains(&"harness_error")); + } +} diff --git a/crates/orbit-api/src/handlers/worker_launches.rs b/crates/orbit-api/src/handlers/worker_launches.rs index 247e8b9c..88d2a76e 100644 --- a/crates/orbit-api/src/handlers/worker_launches.rs +++ b/crates/orbit-api/src/handlers/worker_launches.rs @@ -247,13 +247,12 @@ async fn fail_worker_executions( .await; let ended = match finished { Ok(Some(ended)) => ended, - Ok(None) => { - // Another path already ended it; still make sure the team run is closed. - let mut ended = execution.clone(); - ended.status = orbit_domain::ExecutionStatus::Failed.as_str().into(); - ended.error = Some(data.clone()); - ended - } + // Another path already ended it (the worker reported its result, the reaper + // or a concurrent refresh of this launch failed it). Report nothing: this call + // did not fail it, and the execution may have succeeded. A run it belongs to + // is still closed without retry by the team poller, which reads the stored + // error code (#394). + Ok(None) => continue, Err(error) => { tracing::warn!(execution_id = %execution.id, %error, "could not fail execution for terminated worker"); continue; diff --git a/crates/orbit-api/src/team_outcomes.rs b/crates/orbit-api/src/team_outcomes.rs index c9d8a0f9..345e3779 100644 --- a/crates/orbit-api/src/team_outcomes.rs +++ b/crates/orbit-api/src/team_outcomes.rs @@ -105,7 +105,22 @@ async fn close_queue_loop_inner( None => None, }; - let retry = retry_allowed && status == "failed" && item.max_attempts > item.attempts + 1; + let mut retry = retry_allowed && status == "failed" && item.max_attempts > item.attempts + 1; + // Durable form of the "without retry" decision (#394): a run that lost a worker is + // not retried even when it reaches this through the team poller or the outcome + // reconciler instead of `close_queue_loop_without_retry`. + if retry + && state + .store + .team_run_execution_failed_with( + run.id, + &crate::handlers::teams::ended_without_retry_codes(), + ) + .await? + .is_some() + { + retry = false; + } let outcome = match status { "succeeded" => "done", "failed" if retry => "retry", diff --git a/crates/orbit-api/tests/api_integration.rs b/crates/orbit-api/tests/api_integration.rs index 8cd27309..06bfb353 100644 --- a/crates/orbit-api/tests/api_integration.rs +++ b/crates/orbit-api/tests/api_integration.rs @@ -7270,6 +7270,239 @@ async fn launcher_termination_fails_work_and_never_retries_it() { } } +/// Queue item status, attempts and attached run, for retry assertions. +async fn queue_state(app: &TestApp, item: Uuid) -> (String, i32, Option) { + let queue = app + .store + .get_team_queue_item(app.org_id, item) + .await + .unwrap(); + (queue.status, queue.attempts, queue.team_run_id) +} + +/// #394: the platform failed a team step's execution because its worker went away, and +/// the team poller sees the failed execution before `report_ended_execution` closes the run +/// without retry (or the API restarted in between, so that never happens). The queue item +/// must still end terminal without a retry; an ordinary failure keeps its retry. +#[tokio::test] +async fn a_lost_worker_run_is_not_retried_when_the_team_poller_sees_it_first() { + let Some(app) = test_app_with_license(true, Some(licensed(&["teams"], json!({})))).await else { + return; + }; + let token = worker_token(&app.store, app.org_id, "poller-first").await; + for (code, error, retried) in [ + ( + "worker_lost", + orbit_store::workers::worker_lost_error(), + false, + ), + ( + "harness_unresponsive", + orbit_store::workers::harness_unresponsive_error(), + false, + ), + ( + "worker_oom", + json!({ "code": "worker_oom", "message": "OOMKilled", "retryable": false }), + false, + ), + // Control: a run whose step failed in the harness keeps its queue retry. + ( + "harness_error", + json!({ "code": "harness_error", "message": "the agent failed" }), + true, + ), + ] { + let worker_id = format!("poller-first-{}", Uuid::now_v7()); + let (item, run_id, execution_id) = team_work_on_worker(&app, &token, &worker_id).await; + app.store + .mark_execution_running(execution_id, None) + .await + .unwrap(); + // Only the store transaction of the reaper or launch poller ran. + app.store + .finish_execution( + execution_id, + orbit_domain::ExecutionStatus::Failed, + None, + Some(&error), + None, + None, + ) + .await + .unwrap() + .unwrap(); + let run = app.store.get_team_run(app.org_id, run_id).await.unwrap(); + orbit_api::handlers::teams::advance(&app.state, run) + .await + .unwrap(); + + let run = app.store.get_team_run(app.org_id, run_id).await.unwrap(); + assert_eq!(run.status, "failed", "{code}"); + let step = app.store.current_team_step(run_id).await.unwrap().unwrap(); + assert_eq!(step.status, "failed", "{code}"); + let (status, attempts, attached) = queue_state(&app, item).await; + if retried { + // A retry puts the item back to `pending`, counts the attempt and detaches it. + assert_eq!( + (status.as_str(), attempts, attached), + ("pending", 1, None), + "{code}" + ); + } else { + assert_eq!( + (status.as_str(), attempts, attached), + ("failed", 0, Some(run_id)), + "{code}" + ); + } + } +} + +/// #394: the run was already failed but the API stopped before closing its queue item, so +/// the outcome reconciler closes it later. That path must not retry a lost worker's run. +#[tokio::test] +async fn the_outcome_reconciler_does_not_retry_a_lost_worker_run() { + let Some(app) = test_app_with_license(true, Some(licensed(&["teams"], json!({})))).await else { + return; + }; + let token = worker_token(&app.store, app.org_id, "reconciler").await; + let worker_id = format!("reconciler-{}", Uuid::now_v7()); + let (item, run_id, execution_id) = team_work_on_worker(&app, &token, &worker_id).await; + app.store + .finish_execution( + execution_id, + orbit_domain::ExecutionStatus::Failed, + None, + Some(&orbit_store::workers::worker_restarted_error()), + None, + None, + ) + .await + .unwrap() + .unwrap(); + app.store + .finish_team_run(run_id, "failed", None, Some("worker restarted")) + .await + .unwrap() + .unwrap(); + assert_eq!(queue_state(&app, item).await.0, "running"); + + orbit_api::handlers::teams::reconcile_team_outcomes(&app.state) + .await + .unwrap(); + assert_eq!( + queue_state(&app, item).await, + ("failed".to_string(), 0, Some(run_id)) + ); +} + +/// #394: refreshes of a terminated launch run from the termination poller on every replica +/// and from the Workers page, so two can overlap, and the worker's own `succeeded` report +/// can land between a refresh listing the execution and failing it. Only the call that +/// failed the execution reports it: an execution that succeeded gets no termination event, +/// audit entry or failed team run, and a failed one gets exactly one of each. +#[tokio::test] +async fn overlapping_launch_refreshes_report_only_the_failure_they_caused() { + let mut outcomes = std::collections::BTreeMap::::new(); + for round in 0..8 { + // One app per round: the launch helper creates a uniquely named worker profile. + let Some(app) = test_app_with_license(true, Some(licensed(&["teams"], json!({})))).await + else { + return; + }; + let token = worker_token(&app.store, app.org_id, "overlapping").await; + let worker_id = format!("overlapping-{}", Uuid::now_v7()); + let (item, run_id, execution_id) = team_work_on_worker(&app, &token, &worker_id).await; + app.store + .mark_execution_running(execution_id, None) + .await + .unwrap(); + let launch = live_launch_for_worker(&app, &worker_id, "kubernetes").await; + let url = mock_launcher_status(json!({ + "status": "failed", + "runtimeId": "orbit-worker-abc123", + "workerId": worker_id, + "error": "worker pod was terminated (OOMKilled)", + "termination": { + "reason": "worker_oom", + "workerName": "orbit-worker-abc123", + "detail": "OOMKilled", + }, + })) + .await; + let mut state = app.state.clone(); + state.launcher_url = Some(url); + state.launcher_token = Some("launcher-token".into()); + let router = build_router(state); + let path = format!("/api/v1/worker-launches/{}", launch.id); + let complete = async { + // Vary where the worker's report lands relative to the two refreshes. + tokio::time::sleep(std::time::Duration::from_millis(round * 3)).await; + app.store + .finish_execution( + execution_id, + orbit_domain::ExecutionStatus::Succeeded, + Some(&json!({ "text": "done" })), + None, + None, + None, + ) + .await + .unwrap() + }; + let (first, second, _) = tokio::join!( + send(&router, get(&path)), + send(&router, get(&path)), + complete + ); + assert_eq!(first.0, StatusCode::OK, "{}", first.1); + assert_eq!(second.0, StatusCode::OK, "{}", second.1); + + let run = app.store.get_team_run(app.org_id, run_id).await.unwrap(); + orbit_api::handlers::teams::advance(&app.state, run) + .await + .unwrap(); + + let execution = app + .store + .get_execution(app.org_id, execution_id) + .await + .unwrap(); + let reported = execution_events(&app, &execution_id.to_string(), "&kind=error") + .await + .into_iter() + .filter(|event| event["data"]["code"] == "worker_oom") + .count(); + let (rows, _) = app + .store + .list_audit_logs(app.org_id, 100, None, Some("worker.oom_killed")) + .await + .unwrap(); + let audited = rows + .iter() + .filter(|row| row.target_id == Some(execution_id)) + .count(); + let run = app.store.get_team_run(app.org_id, run_id).await.unwrap(); + let (queue, attempts, _) = queue_state(&app, item).await; + match execution.status.as_str() { + "succeeded" => { + assert_eq!((reported, audited), (0, 0), "round {round}"); + assert_eq!(run.status, "succeeded", "round {round}"); + assert_eq!(queue, "succeeded", "round {round}"); + } + "failed" => { + assert_eq!((reported, audited), (1, 1), "round {round}"); + assert_eq!(run.status, "failed", "round {round}"); + assert_eq!((queue.as_str(), attempts), ("failed", 0), "round {round}"); + } + other => panic!("round {round}: execution is {other}"), + } + *outcomes.entry(execution.status).or_default() += 1; + } + eprintln!("overlapping refresh outcomes: {outcomes:?}"); +} + #[tokio::test] async fn termination_poller_ends_dispatched_work_without_the_workers_page() { let Some(app) = test_app(true).await else { diff --git a/crates/orbit-store/src/team_queue.rs b/crates/orbit-store/src/team_queue.rs index ddd884d7..a7156c26 100644 --- a/crates/orbit-store/src/team_queue.rs +++ b/crates/orbit-store/src/team_queue.rs @@ -330,6 +330,31 @@ impl Store { Ok(result.rows_affected() == 1) } + /// The earliest failed execution of `run_id` whose error code is one of `codes`. + /// + /// The API passes the codes of executions the platform ended because their worker went + /// away (#343): their side effects are unknown, so the run must be neither continued + /// nor retried. Reading this from the execution rows, not from whichever code path saw + /// the failure first, keeps that decision across races and API restarts (#394). + pub async fn team_run_execution_failed_with( + &self, + run_id: Uuid, + codes: &[&str], + ) -> StoreResult> { + Ok(sqlx::query_as::<_, crate::ExecutionRecord>( + r#" + SELECT * FROM executions + WHERE team_run_id = $1 AND status = 'failed' AND error->>'code' = ANY($2) + ORDER BY finished_at ASC NULLS LAST, created_at ASC + LIMIT 1 + "#, + ) + .bind(run_id) + .bind(codes) + .fetch_optional(&self.pool) + .await?) + } + /// Terminal runs whose queue item is still `running`: the outcome was never /// (fully) applied and must be retried. pub async fn list_team_runs_pending_outcome( diff --git a/docs/architecture/agent-teams.md b/docs/architecture/agent-teams.md index 8682d0bd..d27c3f35 100644 --- a/docs/architecture/agent-teams.md +++ b/docs/architecture/agent-teams.md @@ -212,7 +212,14 @@ issue through the connector: | cancelled | claim label removed | — | The queue item records `succeeded`, `failed` or `cancelled` accordingly, and failures -respect `maxAttempts`. Operators can retry, requeue or cancel an item from the UI or +respect `maxAttempts`. A run is never retried automatically when one of its executions was +ended by the platform because its worker went away (`worker_lost`, `worker_oom`, +`worker_evicted`, `worker_exited` or `harness_unresponsive`): its side effects are unknown, +so its item ends `failed` and an operator decides whether to run it again. Nothing runs after +such a step either, even through a workflow's "failed" line. The decision is read from the +stored execution error, so it holds whichever path (reaper, launch poller, team-run loop or +outcome reconciler) handles the run first, and across API restarts. `worker_did_not_start` +is not in that list: nothing ran, so the item keeps its retry. Operators can retry, requeue or cancel an item from the UI or `POST …/queue/{item_id}/{retry|requeue|cancel}`: | Action | Allowed from | Effect | diff --git a/docs/guide/worker-profiles.md b/docs/guide/worker-profiles.md index b9ba803e..3f66dd8b 100644 --- a/docs/guide/worker-profiles.md +++ b/docs/guide/worker-profiles.md @@ -117,8 +117,9 @@ stopping profiles needs `settings:write`. `worker_exited` (non-zero exit) or `worker_lost` (node/pod gone). Exit code 137 alone is SIGKILL, not OOM. Every in-flight execution on that worker fails with the same reason, pod name, restart count, exit code and termination time; team runs are not retried - automatically. The API polls live launches every 15 seconds, so this happens even when - nobody has the Workers page open + automatically. Only executions that were still in flight are reported: one that finished + first (for example with its own `succeeded` result) keeps its result. The API polls live + launches every 15 seconds, so this happens even when nobody has the Workers page open The profile can also generate copy-paste Docker/Compose/Kubernetes bootstrap output with a scoped token. Generating bootstrap output (an explicit **Generate** button in the dialog)