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
9 changes: 8 additions & 1 deletion docs/rust-server-port.md
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,14 @@ 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 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`)
Expand Down
12 changes: 11 additions & 1 deletion rust/src/runtime/continuations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Result<Vec<_>>>()?;
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::<Result<Vec<_>>>()?;
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);
Expand All @@ -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");
Expand Down
12 changes: 3 additions & 9 deletions rust/src/runtime/run_observation_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,16 +254,10 @@ where

async fn observed_timeout_cleanup(&self, run_id: &str, status: &str, started: Option<&Value>) -> Result<Option<Value>> {
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(
Expand Down
85 changes: 85 additions & 0 deletions rust/src/runtime/timeout_cleanup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,27 @@ pub(super) fn observation(event_type: &str, payload: &Value) -> Option<Value> {
Some(Value::Object(observed))
}

/// 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 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, ")"
)
};
}

/// 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 {
Expand Down Expand Up @@ -188,6 +209,70 @@ 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<Option<Value>> {
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. 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<std::collections::BTreeMap<String, Value>> {
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();
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")?);
}
for (run, status) in runs {
if candidates.contains(run)
&& 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<Option<i64>> {
let started = Self::query("SELECT payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='WorkflowStarted' ORDER BY sequence LIMIT 1")
Expand Down
10 changes: 9 additions & 1 deletion rust/src/runtime/visibility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Result<Vec<_>>>()?;
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"));
Expand All @@ -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 =
Expand Down
63 changes: 63 additions & 0 deletions rust/tests/execution/timeout_cleanup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
}
}

Expand All @@ -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.
Expand All @@ -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.
Expand All @@ -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;
}
}

Expand Down Expand Up @@ -525,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]
Expand All @@ -543,6 +603,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;
Expand All @@ -563,6 +624,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;
Expand All @@ -580,6 +642,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
Expand Down
Loading