From 3d7211a15089bccecfd3686a75f9f3d7f975e2a2 Mon Sep 17 00:00:00 2001 From: Richard McDaniel <1130888+rmcdaniel@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:58:28 +0000 Subject: [PATCH 1/2] Carry the timeout cleanup outcome in native run lists GET /api/workflows and GET /api/workflows/{workflow_id}/runs now return the bounded run observation's timeout_cleanup on each listed run that recorded cleanup, and omit it otherwise, as embedded Workflow's run summary does (workflow#863): outcome running with the cause, kind, start and deadlines while cleanup is open, then the outcome recorded on the terminal event. Native lists read workflow_runs and history, not the summary table, so this needs no schema change. The value comes from the same event the observation reads (newest of the type observation_event chooses), now one shared helper. Reads stay bounded per page: a closed run's terminal event is its newest, so its lookup stops at once; an open run can only be in cleanup while it holds a cooperative request, which one query checks for the whole page; completed runs read nothing. The describe divergence notes that, like the observation, the lists return embedded's shape from the release after 3.30.0. Co-Authored-By: Claude Opus 5.5 --- docs/rust-server-port.md | 6 +- rust/src/runtime/continuations.rs | 12 ++- rust/src/runtime/run_observation_store.rs | 12 +-- rust/src/runtime/timeout_cleanup.rs | 73 +++++++++++++++++++ rust/src/runtime/visibility.rs | 10 ++- rust/tests/execution/timeout_cleanup.rs | 28 +++++++ .../server-parity/native-divergences.json | 4 +- 7 files changed, 131 insertions(+), 14 deletions(-) diff --git a/docs/rust-server-port.md b/docs/rust-server-port.md index 5a4b0e6c6..8638b6a7d 100644 --- a/docs/rust-server-port.md +++ b/docs/rust-server-port.md @@ -605,7 +605,11 @@ contract fixture before its correction. and closes `WorkflowTimedOut`, `WorkflowTerminated` or `WorkflowCancelled` with the embedded 2.29.0 `timeout_cleanup` outcome. Children opt in on their own, and describe reports the cleanup state; both are registered - native divergences. Cluster info and worker responses advertise + native divergences. The bounded run observation and both run lists + (`GET /api/workflows`, `GET /api/workflows/{workflow_id}/runs`) return + embedded's portable `timeout_cleanup`, omitted when nothing was recorded; + a list reads it for the whole page in one history query, so it needs no + schema change (workflow#863). Cluster info and worker responses advertise `timeout_cleanup: {supported: true, version: 1}`, after the contract vectors 1 to 12 passed against published native with the published PHP SDK 3.31.0 worker (`scripts/conformance/timeout-cleanup/run.sh`) diff --git a/rust/src/runtime/continuations.rs b/rust/src/runtime/continuations.rs index 7fffe7978..418e14770 100644 --- a/rust/src/runtime/continuations.rs +++ b/rust/src/runtime/continuations.rs @@ -238,7 +238,13 @@ where let current = DB::string(rows.last().expect("one run"), "id")?; let fleet = self.fleet_snapshots(super::store::now()).await?; let run_ids = rows.iter().map(|row| DB::string(row, "id")).collect::>>()?; - let mut attention = self.task_attention_for_runs(&mut *self.pool.acquire().await?, &run_ids).await?; + let mut connection = self.pool.acquire().await?; + let mut attention = self.task_attention_for_runs(&mut connection, &run_ids).await?; + let run_statuses = rows.iter().zip(&run_ids) + .map(|(row, run)| Ok((run.clone(), DB::string(row, "status")?))) + .collect::>>()?; + let mut timeout_cleanup = Self::timeout_cleanup_for_runs(&mut connection, &run_statuses).await?; + drop(connection); let mut runs = Vec::with_capacity(rows.len()); for (row, run) in rows.into_iter().zip(run_ids) { let task_attention = attention.remove(&run).unwrap_or(Value::Null); @@ -258,6 +264,10 @@ where "started_at":super::task_queues::json_time(DB::optional_instant(&row,"started_at")?), "closed_at":super::task_queues::json_time(DB::optional_instant(&row,"closed_at")?),"memo":memo, "task_attention": task_attention}); + // workflow#863: the observation's value; absent when none was recorded. + if let Some(cleanup) = timeout_cleanup.remove(&run) { + entry[super::timeout_cleanup::STARTED_KEY] = cleanup; + } // `formatRunListEntry` leaves a Waterline v1 projection's memo out. if DB::optional_string(&row, "import_source")?.as_deref() == Some(super::waterline_import::IMPORT_SOURCE) { entry.as_object_mut().expect("run entry").remove("memo"); diff --git a/rust/src/runtime/run_observation_store.rs b/rust/src/runtime/run_observation_store.rs index 339103077..ea3c3fcb1 100644 --- a/rust/src/runtime/run_observation_store.rs +++ b/rust/src/runtime/run_observation_store.rs @@ -254,16 +254,10 @@ where async fn observed_timeout_cleanup(&self, run_id: &str, status: &str, started: Option<&Value>) -> Result> { let opted_in = started.is_some_and(|started| started[super::timeout_cleanup::STARTED_KEY].is_object()); - let Some(event_type) = super::timeout_cleanup::observation_event(status).filter(|_| opted_in) else { + if !opted_in { return Ok(None); - }; - let row = Self::query("SELECT payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type=$2 ORDER BY sequence DESC LIMIT 1") - .bind(run_id).bind(event_type).fetch_optional(&self.pool).await?; - let Some(row) = row else { - return Ok(None); - }; - let payload = DB::optional_document_row(&row, "payload")?.unwrap_or(Value::Null); - Ok(super::timeout_cleanup::observation(event_type, &payload)) + } + Self::observed_timeout_cleanup_event(&mut *self.pool.acquire().await?, run_id, status).await } async fn observation_history( diff --git a/rust/src/runtime/timeout_cleanup.rs b/rust/src/runtime/timeout_cleanup.rs index 8355fbbec..aaa920cbd 100644 --- a/rust/src/runtime/timeout_cleanup.rs +++ b/rust/src/runtime/timeout_cleanup.rs @@ -151,6 +151,19 @@ pub(super) fn observation(event_type: &str, payload: &Value) -> Option { Some(Value::Object(observed)) } +/// The open runs of a list page that hold a cooperative cancellation +/// request. Cleanup entry always records the engine's request on the run, +/// and nothing clears it while the run is open. +macro_rules! requested_runs { + ($members:literal) => { + concat!( + "SELECT id FROM workflow_runs WHERE cancellation_request_command_id IS NOT NULL AND id IN (", + $members, + ")" + ) + }; +} + /// A registration that delivers the typed timeout interruption: it lists /// the capability and its manifest supports version 1. pub(super) fn worker_supports(capabilities: &Value, manifest: &Value) -> bool { @@ -188,6 +201,66 @@ pub(super) struct Closing { } store_methods! { + /// The bounded run observation's `timeout_cleanup` for a run in + /// `status`, read from the newest event `observation_event` chooses, as + /// embedded `TimeoutCleanup::observe` does. The caller applies the + /// opt-in check. + pub(super) async fn observed_timeout_cleanup_event(connection: &mut DB::Connection, run_id: &str, status: &str) + -> Result> { + let Some(event_type) = observation_event(status) else { + return Ok(None); + }; + let row = Self::query("SELECT payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type=$2 ORDER BY sequence DESC LIMIT 1") + .bind(run_id).bind(event_type).fetch_optional(&mut *connection).await?; + let Some(row) = row else { + return Ok(None); + }; + let payload = DB::optional_document_row(&row, "payload")?.unwrap_or(Value::Null); + Ok(observation(event_type, &payload)) + } + + /// Run lists' `timeout_cleanup` (workflow#863): the bounded run + /// observation's value for each listed run that has one, keyed by run + /// id. A list passes each run's id and status. Only an opted-in run + /// records cleanup entry or a terminal `timeout_cleanup` outcome, so the + /// observation's `WorkflowStarted` check adds nothing here. Reads stay + /// bounded: a closed run's terminal event is its newest, and only an open + /// run that holds a cooperative request (one query for the page) can be + /// in cleanup. A completed run reports nothing and reads nothing. + pub(super) async fn timeout_cleanup_for_runs(connection: &mut DB::Connection, runs: &[(String, String)]) + -> Result> { + let open: Vec<&str> = runs.iter() + .filter(|(_, status)| matches!(status.as_str(), "pending" | "running" | "waiting")) + .map(|(run, _)| run.as_str()) + .collect(); + let mut requested = std::collections::BTreeSet::new(); + if !open.is_empty() { + let sql = match DB::NAME { + "PostgreSQL" => requested_runs!("SELECT jsonb_array_elements_text(CAST($1 AS jsonb))"), + "MySQL" => requested_runs!( + "SELECT ids.id FROM JSON_TABLE($1, '$[*]' COLUMNS (id VARCHAR(255) COLLATE utf8mb4_unicode_ci PATH '$')) ids" + ), + _ => requested_runs!("SELECT value FROM json_each($1)"), + }; + let ids = serde_json::to_string(&open)?; + for row in Self::query(sql).bind(ids.as_str()).fetch_all(&mut *connection).await? { + requested.insert(DB::string(&row, "id")?); + } + } + let mut observed = std::collections::BTreeMap::new(); + for (run, status) in runs { + let candidate = match status.as_str() { + "failed" | "cancelled" | "terminated" => true, + "pending" | "running" | "waiting" => requested.contains(run), + _ => false, + }; + if candidate && let Some(value) = Self::observed_timeout_cleanup_event(&mut *connection, run, status).await? { + observed.insert(run.clone(), value); + } + } + Ok(observed) + } + /// The allowance the run was admitted with, from its `WorkflowStarted`. pub(super) async fn timeout_cleanup_allowance(tx: &mut Transaction<'_, DB>, run_id: &str) -> Result> { let started = Self::query("SELECT payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='WorkflowStarted' ORDER BY sequence LIMIT 1") diff --git a/rust/src/runtime/visibility.rs b/rust/src/runtime/visibility.rs index e045f9aa8..98653d497 100644 --- a/rust/src/runtime/visibility.rs +++ b/rust/src/runtime/visibility.rs @@ -526,14 +526,18 @@ where let page = &rows[..rows.len().min(filter.limit as usize)]; let run_ids = page.iter().map(|row| DB::string(row, "id")).collect::>>()?; let mut open_run_ids = Vec::new(); + let mut run_statuses = Vec::with_capacity(run_ids.len()); for (row, run_id) in page.iter().zip(&run_ids) { - if status_bucket(&DB::string(row, "status")?)? == "running" { + let status = DB::string(row, "status")?; + if status_bucket(&status)? == "running" { open_run_ids.push(run_id.clone()); } + run_statuses.push((run_id.clone(), status)); } let mut unsupported_ready = self.unsupported_ready_tasks_for_runs(&open_run_ids, super::store::now()).await?; let mut connection = self.pool.acquire().await?; let mut attention = self.task_attention_for_runs(&mut connection, &run_ids).await?; + let mut timeout_cleanup = Self::timeout_cleanup_for_runs(&mut connection, &run_statuses).await?; for (row, run_id) in page.iter().zip(run_ids) { if DB::optional_string(row, "compatibility")?.is_some() { return Err(refuse(StatusCode::CONFLICT, "unqualified_build_visibility")); @@ -558,6 +562,10 @@ where if let Some(task) = unsupported_ready.remove(&run_id) { workflow["unsupported_ready_task"] = task; } + // workflow#863: the observation's value; absent when none was recorded. + if let Some(cleanup) = timeout_cleanup.remove(&run_id) { + workflow[super::timeout_cleanup::STARTED_KEY] = cleanup; + } workflows.push(workflow); } let next = diff --git a/rust/tests/execution/timeout_cleanup.rs b/rust/tests/execution/timeout_cleanup.rs index f7b4b8107..d154bd543 100644 --- a/rust/tests/execution/timeout_cleanup.rs +++ b/rust/tests/execution/timeout_cleanup.rs @@ -102,6 +102,26 @@ fn dump(scenario: &str, history: &Value) { } } +/// workflow#863: both run lists carry the bounded run observation's +/// `timeout_cleanup`, and omit it whenever the observation does. +async fn assert_listed(app: &Router, workflow: &str, run: &Value, present: bool) { + let run_id = run.as_str().unwrap(); + let (status, observed) = request(app, "GET", &format!("/api/workflows/{workflow}/runs/{run_id}/observation"), Value::Null).await; + assert_eq!(status, StatusCode::OK, "{observed}"); + let expected = observed.get("timeout_cleanup"); + assert_eq!(expected.is_some(), present, "{workflow}: {observed}"); + let (status, page) = request(app, "GET", "/api/workflows?page_size=200", Value::Null).await; + assert_eq!(status, StatusCode::OK, "{page}"); + let listed = page["workflows"].as_array().unwrap().iter().find(|item| item["run_id"] == *run) + .unwrap_or_else(|| panic!("{workflow}: not listed in {page}")); + assert_eq!(listed.get("timeout_cleanup"), expected, "{workflow}: {listed}"); + let (status, runs) = request(app, "GET", &format!("/api/workflows/{workflow}/runs"), Value::Null).await; + assert_eq!(status, StatusCode::OK, "{runs}"); + let entry = runs["runs"].as_array().unwrap().iter().find(|item| item["run_id"] == *run) + .unwrap_or_else(|| panic!("{workflow}: not in {runs}")); + assert_eq!(entry.get("timeout_cleanup"), expected, "{workflow}: {entry}"); +} + fn terminal<'a>(history: &'a Value, kind: &str) -> &'a Value { let events = events_of(history, kind); assert_eq!(events.len(), 1, "{kind}: {history}"); @@ -188,6 +208,7 @@ async fn a_start_without_the_option_keeps_the_hard_timeout_unchanged() { let (_, observed) = request(&app, "GET", &format!("/api/workflows/tc-default/runs/{}/observation", run.as_str().unwrap()), Value::Null).await; assert_eq!(observed["status"], "failed", "{observed}"); assert!(observed.get("timeout_cleanup").is_none(), "{observed}"); + assert_listed(&app, "tc-default", &run, false).await; } // Vectors 1 and 6, the idle wake and the audited user request. @@ -339,6 +360,7 @@ async fn cleanup_failures_are_linked_and_the_interruption_marker_is_a_closed_set } let (_, described) = request(&app, "GET", &format!("/api/workflows/{workflow}"), Value::Null).await; assert_eq!((described["status"].as_str(), described["closed_reason"].as_str()), (Some("failed"), Some("timed_out"))); + assert_listed(&app, workflow, &run, true).await; } } @@ -359,6 +381,7 @@ async fn cleanup_expires_at_the_hard_deadline_without_a_worker() { assert!(timed_out["timeout_cleanup"]["started_at"].is_string()); assert!(timed_out["message"].as_str().unwrap().ends_with("Timeout cleanup did not finish before the hard deadline.")); assert!(cleanup_poll(&app, "cleanup-worker").await.is_null()); + assert_listed(&app, "tc-expired", &run, true).await; } // A hard deadline that passes before cleanup was entered also expires it. @@ -375,6 +398,7 @@ async fn a_hard_deadline_before_detection_expires_without_entering() { assert_eq!(cleanup["outcome"], "expired"); assert!(cleanup.get("started_at").is_none(), "{cleanup}"); assert_eq!(cleanup["cleanup_deadline_at"], "2000-01-01T00:00:00+00:00"); + assert_listed(&app, "tc-late", &started["run_id"], true).await; } // Vector 4: terminate and hard cancel preempt cleanup. @@ -395,6 +419,7 @@ async fn terminate_and_hard_cancel_preempt_cleanup() { assert_eq!(closed["timeout_cleanup"]["timeout_kind"], "execution"); let (_, observed) = request(&app, "GET", &format!("/api/workflows/{workflow}/runs/{}/observation", run.as_str().unwrap()), Value::Null).await; assert_eq!(observed["timeout_cleanup"], closed["timeout_cleanup"], "{observed}"); + assert_listed(&app, workflow, &run, true).await; } } @@ -543,6 +568,7 @@ async fn the_earliest_hard_deadline_names_the_kind_and_describe_follows_the_stat let observation = format!("/api/workflows/tc-run-kind/runs/{}/observation", run.as_str().unwrap()); let (_, observed) = request(&app, "GET", &observation, Value::Null).await; assert!(observed.get("timeout_cleanup").is_none(), "nothing recorded while armed: {observed}"); + assert_listed(&app, "tc-run-kind", &run, false).await; assert_eq!(described["timeout_cleanup"]["allowance_seconds"], ALLOWANCE); assert_eq!(described["timeout_cleanup"]["timeout_kind"], "run"); let first = cleanup_poll(&app, "cleanup-worker").await; @@ -563,6 +589,7 @@ async fn the_earliest_hard_deadline_names_the_kind_and_describe_follows_the_stat assert_eq!(observed["timeout_cleanup"], json!({"outcome": "running", "cause": "timeout", "timeout_kind": "run", "started_at": entered["detected_at"], "work_deadline_at": entered["work_deadline_at"], "cleanup_deadline_at": entered["cleanup_deadline_at"]}), "{observed}"); + assert_listed(&app, "tc-run-kind", &run, true).await; assert_eq!(view["started_at"], entered["detected_at"]); assert_eq!(view["cleanup_deadline_at"], json!(iso)); let task = cleanup_poll(&app, "cleanup-worker").await; @@ -580,6 +607,7 @@ async fn the_earliest_hard_deadline_names_the_kind_and_describe_follows_the_stat let (_, observed) = request(&app, "GET", &observation, Value::Null).await; assert_eq!(observed["timeout_cleanup"], timed_out["timeout_cleanup"], "{observed}"); assert_eq!(observed["timeout_cleanup"]["outcome"], "completed"); + assert_listed(&app, "tc-run-kind", &run, true).await; } // Vector 6 and worker replacement: the task holding the cleanup turn moves diff --git a/scripts/conformance/server-parity/native-divergences.json b/scripts/conformance/server-parity/native-divergences.json index 34a59991c..699473134 100644 --- a/scripts/conformance/server-parity/native-divergences.json +++ b/scripts/conformance/server-parity/native-divergences.json @@ -73,8 +73,8 @@ "since": "native 3.14.0", "applies_to": ["timeout-cleanup"], "published_php": "Published PHP does not admit timeout cleanup on service starts. Embedded Workflow 2.40.0 describe and run detail return timeout_cleanup only once cleanup is recorded: {outcome: running, cause: timeout, timeout_kind, started_at, work_deadline_at, cleanup_deadline_at} while it is open, then the terminal event's {outcome, timeout_kind, started_at, cleanup_deadline_at, finished_at, failure_id}, omitting absent fields; with nothing recorded the field is omitted.", - "native": "Describe and run detail of an opted-in run always carry timeout_cleanup {state, cause, allowance_seconds, timeout_kind, work_deadline_at, cleanup_deadline_at, started_at, outcome, failure_id}, with null for absent values. state is armed before the work deadline is noticed and not_entered when the run closed without entering cleanup, where embedded omits the field; cancellation_cleanup_running while cleanup is open, with outcome running from the release after 3.29.0 (null before); finished with the recorded outcome, without finished_at. A run without the opt-in has no timeout_cleanup key. From the release after 3.29.0 the bounded run observation is not part of this divergence: it returns embedded's shape.", - "harness": "No recorded corpus run opts in, so no comparator changes. The all-backend execution tests cover every describe state and outcome and the observation's absent, running and finished shapes." + "native": "Describe and run detail of an opted-in run always carry timeout_cleanup {state, cause, allowance_seconds, timeout_kind, work_deadline_at, cleanup_deadline_at, started_at, outcome, failure_id}, with null for absent values. state is armed before the work deadline is noticed and not_entered when the run closed without entering cleanup, where embedded omits the field; cancellation_cleanup_running while cleanup is open, with outcome running from the release after 3.29.0 (null before); finished with the recorded outcome, without finished_at. A run without the opt-in has no timeout_cleanup key. From the release after 3.29.0 the bounded run observation is not part of this divergence: it returns embedded's shape. Nor, from the release after 3.30.0, are the run lists: GET /api/workflows and GET /api/workflows/{workflow_id}/runs carry the observation's timeout_cleanup on each listed run that recorded cleanup and omit it otherwise (workflow#863).", + "harness": "No recorded corpus run opts in, so no comparator changes. The all-backend execution tests cover every describe state and outcome, and the observation's and both run lists' absent, running and finished shapes." }, { "id": "child-timeout-cleanup-opt-in", From ff6714739587888533ecf068712b19136f3dd0b9 Mon Sep 17 00:00:00 2001 From: Richard McDaniel <1130888+rmcdaniel@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:23:02 +0000 Subject: [PATCH 2/2] Gate listed cleanup lookups on the opt-in, once per page Review of the run-list change: every failed, cancelled or terminated run on a page read its history for the observation's event, and with no index on event_type an ordinary WorkflowFailed run scanned its whole history looking for WorkflowTimedOut. One query per page now selects the candidates. It joins each run's WorkflowStarted (unique (run, sequence) seeks: it is the first event, or the second after StartAccepted), keeps runs whose payload carries a timeout_cleanup object (per-backend JSON type predicates), and of those the closed runs and the open runs holding a cooperative request or imported (an embedded import does not copy the request). Only the candidates read the observation's event. This is the observation's own opt-in gate, so lists equal it exactly. A new test lists an ordinary failed run and an opted-in run cancelled before its work deadline without the key, on the same page as a run in cleanup. The port document describes the reads as they are, and the divergence entry says lists omit the key when absent, unlike their task_attention: null. Co-Authored-By: Claude Opus 5.5 --- docs/rust-server-port.md | 9 +- rust/src/runtime/timeout_cleanup.rs | 84 +++++++++++-------- rust/tests/execution/timeout_cleanup.rs | 35 ++++++++ .../server-parity/native-divergences.json | 2 +- 4 files changed, 90 insertions(+), 40 deletions(-) diff --git a/docs/rust-server-port.md b/docs/rust-server-port.md index 8638b6a7d..ce7e1abe2 100644 --- a/docs/rust-server-port.md +++ b/docs/rust-server-port.md @@ -607,9 +607,12 @@ contract fixture before its correction. their own, and describe reports the cleanup state; both are registered native divergences. The bounded run observation and both run lists (`GET /api/workflows`, `GET /api/workflows/{workflow_id}/runs`) return - embedded's portable `timeout_cleanup`, omitted when nothing was recorded; - a list reads it for the whole page in one history query, so it needs no - schema change (workflow#863). Cluster info and worker responses advertise + embedded's portable `timeout_cleanup`, omitted when nothing was recorded. + A list reads it with no schema change (workflow#863): one query per page + selects the opted-in runs that can report cleanup (closed runs that may + carry an outcome, and open runs holding a cooperative request or + imported), and each of those reads one history event, the newest of the + observation's type. Cluster info and worker responses advertise `timeout_cleanup: {supported: true, version: 1}`, after the contract vectors 1 to 12 passed against published native with the published PHP SDK 3.31.0 worker (`scripts/conformance/timeout-cleanup/run.sh`) diff --git a/rust/src/runtime/timeout_cleanup.rs b/rust/src/runtime/timeout_cleanup.rs index aaa920cbd..f3c6de2cc 100644 --- a/rust/src/runtime/timeout_cleanup.rs +++ b/rust/src/runtime/timeout_cleanup.rs @@ -151,15 +151,23 @@ pub(super) fn observation(event_type: &str, payload: &Value) -> Option { Some(Value::Object(observed)) } -/// The open runs of a list page that hold a cooperative cancellation -/// request. Cleanup entry always records the engine's request on the run, -/// and nothing clears it while the run is open. -macro_rules! requested_runs { - ($members:literal) => { +/// The runs of a list page that can report timeout cleanup: opted in (a +/// `WorkflowStarted.timeout_cleanup` object) and either closed in a way that can carry an outcome, or open and +/// holding a cooperative request. Cleanup entry always records the engine's +/// request on the run, and nothing clears it while the run is open. An +/// imported run is let through, since an import does not copy the request. +/// `WorkflowStarted` is a run's first event, or its second after +/// `StartAccepted`, on every native and embedded start, child, retry, +/// continuation and redrive, so it is read by unique `(run, sequence)` seeks. +macro_rules! cleanup_candidates { + ($opted_in:literal, $members:literal) => { concat!( - "SELECT id FROM workflow_runs WHERE cancellation_request_command_id IS NOT NULL AND id IN (", - $members, - ")" + "SELECT r.id FROM workflow_runs r JOIN workflow_history_events e", + " ON e.workflow_run_id=r.id AND e.sequence IN (1,2) AND e.event_type='WorkflowStarted'", + " WHERE ", $opted_in, + " AND (r.status IN ('failed','cancelled','terminated') OR (r.status IN ('pending','running','waiting')", + " AND (r.cancellation_request_command_id IS NOT NULL OR r.import_source IS NOT NULL)))", + " AND r.id IN (", $members, ")" ) }; } @@ -221,40 +229,44 @@ store_methods! { /// Run lists' `timeout_cleanup` (workflow#863): the bounded run /// observation's value for each listed run that has one, keyed by run - /// id. A list passes each run's id and status. Only an opted-in run - /// records cleanup entry or a terminal `timeout_cleanup` outcome, so the - /// observation's `WorkflowStarted` check adds nothing here. Reads stay - /// bounded: a closed run's terminal event is its newest, and only an open - /// run that holds a cooperative request (one query for the page) can be - /// in cleanup. A completed run reports nothing and reads nothing. + /// id. A list passes each run's id and status. One query selects the + /// page's candidates with the observation's opt-in check (see + /// `cleanup_candidates`); only those read the observation's event, which + /// for a timed-out, cancelled or terminated run is its newest. Ordinary, + /// armed and completed runs read nothing more. pub(super) async fn timeout_cleanup_for_runs(connection: &mut DB::Connection, runs: &[(String, String)]) -> Result> { - let open: Vec<&str> = runs.iter() - .filter(|(_, status)| matches!(status.as_str(), "pending" | "running" | "waiting")) + let mut observed = std::collections::BTreeMap::new(); + let listed: Vec<&str> = runs.iter() + .filter(|(_, status)| observation_event(status).is_some()) .map(|(run, _)| run.as_str()) .collect(); - let mut requested = std::collections::BTreeSet::new(); - if !open.is_empty() { - let sql = match DB::NAME { - "PostgreSQL" => requested_runs!("SELECT jsonb_array_elements_text(CAST($1 AS jsonb))"), - "MySQL" => requested_runs!( - "SELECT ids.id FROM JSON_TABLE($1, '$[*]' COLUMNS (id VARCHAR(255) COLLATE utf8mb4_unicode_ci PATH '$')) ids" - ), - _ => requested_runs!("SELECT value FROM json_each($1)"), - }; - let ids = serde_json::to_string(&open)?; - for row in Self::query(sql).bind(ids.as_str()).fetch_all(&mut *connection).await? { - requested.insert(DB::string(&row, "id")?); - } + if listed.is_empty() { + return Ok(observed); + } + let sql = match DB::NAME { + "PostgreSQL" => cleanup_candidates!( + "jsonb_typeof(CAST(e.payload AS jsonb)->'timeout_cleanup')='object'", + "SELECT jsonb_array_elements_text(CAST($1 AS jsonb))" + ), + "MySQL" => cleanup_candidates!( + "JSON_TYPE(JSON_EXTRACT(e.payload,'$.timeout_cleanup'))='OBJECT'", + "SELECT ids.id FROM JSON_TABLE($1, '$[*]' COLUMNS (id VARCHAR(255) COLLATE utf8mb4_unicode_ci PATH '$')) ids" + ), + _ => cleanup_candidates!( + "CASE WHEN json_valid(e.payload) THEN json_type(e.payload,'$.timeout_cleanup') END='object'", + "SELECT value FROM json_each($1)" + ), + }; + let ids = serde_json::to_string(&listed)?; + let mut candidates = std::collections::BTreeSet::new(); + for row in Self::query(sql).bind(ids.as_str()).fetch_all(&mut *connection).await? { + candidates.insert(DB::string(&row, "id")?); } - let mut observed = std::collections::BTreeMap::new(); for (run, status) in runs { - let candidate = match status.as_str() { - "failed" | "cancelled" | "terminated" => true, - "pending" | "running" | "waiting" => requested.contains(run), - _ => false, - }; - if candidate && let Some(value) = Self::observed_timeout_cleanup_event(&mut *connection, run, status).await? { + if candidates.contains(run) + && let Some(value) = Self::observed_timeout_cleanup_event(&mut *connection, run, status).await? + { observed.insert(run.clone(), value); } } diff --git a/rust/tests/execution/timeout_cleanup.rs b/rust/tests/execution/timeout_cleanup.rs index d154bd543..e94e9c67f 100644 --- a/rust/tests/execution/timeout_cleanup.rs +++ b/rust/tests/execution/timeout_cleanup.rs @@ -550,6 +550,41 @@ async fn a_claim_or_a_completion_that_first_notices_the_work_deadline_enters_cle assert_eq!(resumed["cancellation_request"]["request_id"], terminal(&history, "WorkflowTimeoutCleanupStarted")["workflow_command_id"]); } +// workflow#863: a list page mixes runs that report cleanup with an ordinary +// failed run and an opted-in run cancelled before its work deadline; only +// the run that recorded cleanup carries the key. +#[tokio::test] +async fn run_lists_report_cleanup_only_for_runs_that_recorded_it() { + let database = TestDatabase::new().await; + let app = router(database.open().await.unwrap()); + cleanup_worker(&app, "cleanup-worker", true).await; + + let (status, failed) = start_with(&app, "tc-list-failed", json!({"execution_timeout_seconds": 600})).await; + assert_eq!(status, StatusCode::CREATED, "{failed}"); + let task = cleanup_poll(&app, "cleanup-worker").await; + let (status, body) = cleanup_finish(&app, &task, json!([{"type": "fail_workflow", "message": "ordinary failure", + "exception_class": "RuntimeException"}])).await; + assert_eq!(status, StatusCode::OK, "{body}"); + let history = run_history(&app, &json!("tc-list-failed"), &failed["run_id"]).await; + assert_eq!(events_of(&history, "WorkflowFailed").len(), 1, "{history}"); + + let (status, cancelled) = start_with(&app, "tc-list-cancelled", json!({"execution_timeout_seconds": 600, + "timeout_cleanup_seconds": ALLOWANCE})).await; + assert_eq!(status, StatusCode::CREATED, "{cancelled}"); + let task = cleanup_poll(&app, "cleanup-worker").await; + let (status, body) = cleanup_finish(&app, &task, json!([{"type": "start_timer", "delay_seconds": 3600}])).await; + assert_eq!(status, StatusCode::OK, "{body}"); + let (status, body) = request(&app, "POST", "/api/workflows/tc-list-cancelled/cancel", json!({"reason": "operator"})).await; + assert_eq!(status, StatusCode::OK, "{body}"); + let history = run_history(&app, &json!("tc-list-cancelled"), &cancelled["run_id"]).await; + assert!(terminal(&history, "WorkflowCancelled").get("timeout_cleanup").is_none()); + + let (running, _) = idle_in_cleanup(&app, "tc-list-running").await; + assert_listed(&app, "tc-list-failed", &failed["run_id"], false).await; + assert_listed(&app, "tc-list-cancelled", &cancelled["run_id"], false).await; + assert_listed(&app, "tc-list-running", &running, true).await; +} + // Vector 9: the run deadline is earlier, so cleanup is for kind `run` and // ends at the run deadline. Describe follows the state. #[tokio::test] diff --git a/scripts/conformance/server-parity/native-divergences.json b/scripts/conformance/server-parity/native-divergences.json index 699473134..3bab32406 100644 --- a/scripts/conformance/server-parity/native-divergences.json +++ b/scripts/conformance/server-parity/native-divergences.json @@ -73,7 +73,7 @@ "since": "native 3.14.0", "applies_to": ["timeout-cleanup"], "published_php": "Published PHP does not admit timeout cleanup on service starts. Embedded Workflow 2.40.0 describe and run detail return timeout_cleanup only once cleanup is recorded: {outcome: running, cause: timeout, timeout_kind, started_at, work_deadline_at, cleanup_deadline_at} while it is open, then the terminal event's {outcome, timeout_kind, started_at, cleanup_deadline_at, finished_at, failure_id}, omitting absent fields; with nothing recorded the field is omitted.", - "native": "Describe and run detail of an opted-in run always carry timeout_cleanup {state, cause, allowance_seconds, timeout_kind, work_deadline_at, cleanup_deadline_at, started_at, outcome, failure_id}, with null for absent values. state is armed before the work deadline is noticed and not_entered when the run closed without entering cleanup, where embedded omits the field; cancellation_cleanup_running while cleanup is open, with outcome running from the release after 3.29.0 (null before); finished with the recorded outcome, without finished_at. A run without the opt-in has no timeout_cleanup key. From the release after 3.29.0 the bounded run observation is not part of this divergence: it returns embedded's shape. Nor, from the release after 3.30.0, are the run lists: GET /api/workflows and GET /api/workflows/{workflow_id}/runs carry the observation's timeout_cleanup on each listed run that recorded cleanup and omit it otherwise (workflow#863).", + "native": "Describe and run detail of an opted-in run always carry timeout_cleanup {state, cause, allowance_seconds, timeout_kind, work_deadline_at, cleanup_deadline_at, started_at, outcome, failure_id}, with null for absent values. state is armed before the work deadline is noticed and not_entered when the run closed without entering cleanup, where embedded omits the field; cancellation_cleanup_running while cleanup is open, with outcome running from the release after 3.29.0 (null before); finished with the recorded outcome, without finished_at. A run without the opt-in has no timeout_cleanup key. From the release after 3.29.0 the bounded run observation is not part of this divergence: it returns embedded's shape. Nor, from the release after 3.30.0, are the run lists: GET /api/workflows and GET /api/workflows/{workflow_id}/runs carry the observation's timeout_cleanup on each listed run that recorded cleanup and omit it otherwise (workflow#863). Like describe and the observation, and unlike the lists' always-present task_attention: null, the key is omitted when absent; clients should treat an absent and a null timeout_cleanup alike.", "harness": "No recorded corpus run opts in, so no comparator changes. The all-backend execution tests cover every describe state and outcome, and the observation's and both run lists' absent, running and finished shapes." }, {