diff --git a/resources/platform-protocol-specs/worker-protocol-api.openapi.yaml b/resources/platform-protocol-specs/worker-protocol-api.openapi.yaml index 09b57f942..d8e5f0864 100644 --- a/resources/platform-protocol-specs/worker-protocol-api.openapi.yaml +++ b/resources/platform-protocol-specs/worker-protocol-api.openapi.yaml @@ -1,7 +1,7 @@ openapi: 3.1.0 info: title: durable-workflow.v2.worker-protocol-api - version: "67" + version: "68" summary: Durable Workflow worker-plane HTTP+JSON API description: > Normative OpenAPI specification for the worker-plane HTTP+JSON API: @@ -1874,6 +1874,13 @@ components: additionalProperties: true required: [supported_workflow_task_commands, workflow_task_poll_request_idempotency, workflow_memo_updates, message_streams, typed_search_attributes, condition_wait_occurrence_identity, update_validation_tasks, synchronous_update_validation, local_activities, sticky_execution] properties: + condition_wait_input_order: + type: string + const: durable_receipt_order + description: > + This Server can replay history marked for durable input ordering. + Workers that understand the marker register condition_wait_input_order. + A separate field on the workflow lease permits opening a new marked wait. condition_wait_occurrence_deadline: type: boolean description: > @@ -2452,6 +2459,20 @@ components: workflow_task_attempt: { type: integer, minimum: 1 } lease_owner: { type: string, minLength: 1 } lease_expires_at: { type: string, format: date-time } + condition_wait_input_order_authoring: + type: boolean + const: true + description: > + This lease may author a new ordered condition wait. Omission keeps + existing authoring behavior and does not disable replay of marked + history. Retried polls for the same claim preserve this field. + condition_wait_pending_input_sequence: + type: [integer, "null"] + minimum: 1 + description: > + For a marked run, the first accepted signal or update that has not + settled in the task snapshot. Null means all accepted inputs seen + by this claim have settled. Omission means no snapshot was supplied. sticky_worker_id: type: [string, "null"] description: Process identity holding this run's optional sticky affinity. @@ -3685,6 +3706,37 @@ components: description: > The original authored timeout T of the occurrence, distinct from timeout_seconds, which is the worker's remaining replay budget. + condition_wait_input_order: + type: string + const: durable_receipt_order + x-durable-workflow-server-capability: condition_wait_input_order + description: > + Requires deadline_policy occurrence and permission on the + original workflow claim. Its original timer bounds the + eligible applied effects by receipt sequence. + - if: + properties: + type: { const: resolve_condition_wait } + required: [type] + then: + required: [condition_wait_id, satisfied] + x-durable-workflow-worker-capability: condition_wait_input_order + properties: + condition_wait_id: { type: string, minLength: 1, maxLength: 191 } + satisfied: { type: boolean } + input_receipt_sequence: + type: integer + minimum: 1 + description: Receipt of the applied input that first satisfied the predicate. + competing_resolution_event_id: + type: string + minLength: 1 + maxLength: 191 + description: > + With satisfied false, selects the exact competing terminal + event identified by SelectionCandidateReady after evaluating + the earlier eligible inputs. This leaves the condition wait + itself unresolved. - if: properties: type: { const: record_local_activity } diff --git a/rust/README.md b/rust/README.md index db8dfdf1a..f3c0a93f0 100644 --- a/rust/README.md +++ b/rust/README.md @@ -342,6 +342,27 @@ definitions and takes the database out of its staged state. The trigger definer requires access to the checkpoint table for as long as the triggers are installed. +## Rolling out durable input ordering for timed waits + +Leave `DW_ORDERED_CONDITION_WAIT_AUTHORING` unset while replacing Server +processes. This lets the new Server and older versions share an existing +database before any workflow opens a wait using the new ordering. Deploy +compatible SDK workers before enabling authoring. + +Enable `DW_ORDERED_CONDITION_WAIT_AUTHORING=1` only after every Server that +can process the database uses a release that understands ordered waits. +Include maintenance processes and instances eligible to return after +failover. The setting only allows new workflow leases to open ordered +waits. Compatible Servers continue to process marked history and +compatible workers continue to replay it with authoring disabled. + +To stop opening new ordered waits, remove the setting from every Server +and let previously admitted workflow leases settle or expire. Once a +database contains marked history, any Server that may process that +database must understand the marker. Rolling back past the compatible +version requires a pre-activation database restore under the normal data +recovery process. + ## Workflow task lease loss Run descriptions, observations and lists expose `task_attention` when an diff --git a/rust/src/config_audit.rs b/rust/src/config_audit.rs index c64684649..9808c0d50 100644 --- a/rust/src/config_audit.rs +++ b/rust/src/config_audit.rs @@ -504,7 +504,8 @@ pub fn audit(environment: &BTreeMap) -> Report { fn native_only(name: &str) -> bool { matches!( name, - "DW_BIND_ADDRESS" | "DW_ENV" | "DW_RUST_EXPERIMENTAL" | "DW_RUST_MAINTENANCE_LOOP" | "DW_UPGRADE_BACKUP_FINGERPRINT" + "DW_BIND_ADDRESS" | "DW_ENV" | "DW_RUST_EXPERIMENTAL" | "DW_RUST_MAINTENANCE_LOOP" + | "DW_ORDERED_CONDITION_WAIT_AUTHORING" | "DW_UPGRADE_BACKUP_FINGERPRINT" ) || ["DW_RUST_UPGRADE_QUEUE_", "DW_SCHEMA_TEST_", "DW_TAKEOVER_TEST_", "DW_TEST_"] .iter() @@ -827,6 +828,7 @@ mod tests { ("DW_ENV_AUDIT_STRICT", "1"), ("DW_RUST_EXPERIMENTAL", "1"), ("DW_RUST_MAINTENANCE_LOOP", "1"), + ("DW_ORDERED_CONDITION_WAIT_AUTHORING", "1"), ("DW_BIND_ADDRESS", "0.0.0.0:8080"), ]; let report = audit(&environment(&shipped)); diff --git a/rust/src/runtime/backend.rs b/rust/src/runtime/backend.rs index 9599e9b20..40e9c39bd 100644 --- a/rust/src/runtime/backend.rs +++ b/rust/src/runtime/backend.rs @@ -132,6 +132,7 @@ pub(super) trait Backend: Database { const TIMER_SCHEDULE_SQL: &str = "SELECT payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='TimerScheduled' AND payload->>'timer_id'=$2 ORDER BY sequence DESC LIMIT 1"; /// The history sequence of a signal's `SignalReceived` event. const SIGNAL_RECEIVED_SEQUENCE_SQL: &str = "SELECT sequence FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='SignalReceived' AND payload->>'signal_id'=$2 ORDER BY sequence LIMIT 1"; + const ORDERED_CONDITION_HISTORY: &str = "SELECT 1 FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='ConditionWaitOpened' AND payload->>'condition_wait_input_order'='durable_receipt_order' LIMIT 1"; // PostgreSQL compares text case-sensitively. const RUN_COMMANDS_SQL: &str = super::store::run_commands_sql!( @@ -140,6 +141,7 @@ pub(super) trait Backend: Database { "substr(c.payload,1,23)='dw-external-payload:v1:'" ); const SELECTION_RESOLUTION_SQL: &str = "SELECT id,payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='SelectionResolved' AND payload->>'selection_group_id'=$2 ORDER BY sequence LIMIT 1"; + const SELECTION_CANDIDATE_SQL: &str = "SELECT payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='SelectionCandidateReady' AND payload->>'selection_group_id'=$2 ORDER BY sequence LIMIT 1"; // Frozen run command/task repair counters use each backend's actual width. const REPAIR_COUNTER_MAX: i64 = i32::MAX as i64; const RANGE_REPAIR_TASK_SQL: &str = "SELECT * FROM workflow_tasks WHERE workflow_run_id=$1 AND namespace=$2 AND task_type='workflow' AND status='failed' AND payload->>'replay_blocked'='true' ORDER BY CASE WHEN available_at IS NULL THEN 1 ELSE 0 END,available_at,created_at,id LIMIT 1"; @@ -350,6 +352,7 @@ WHERE r.status IN ('pending','running','waiting') ORDER BY t.available_order,t.id LIMIT 100 "#; const SELECTION_RESOLUTION_SQL: &str = "SELECT id,payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='SelectionResolved' AND json_extract(payload,'$.selection_group_id')=$2 ORDER BY sequence LIMIT 1"; + const SELECTION_CANDIDATE_SQL: &str = "SELECT payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='SelectionCandidateReady' AND json_extract(payload,'$.selection_group_id')=$2 ORDER BY sequence LIMIT 1"; const STREAM_ITEM_REFERENCES: &str = concat!("SELECT COUNT(*) FROM workflow_durable_stream_items WHERE stream_id=$1 AND (payload_reference IS NOT NULL OR ", super::retention::reference!("payload"), ")"); const STREAM_REFERENCES: &str = PLAIN_STREAM_REFERENCES; const RUN_STREAM_REFERENCES: &str = concat!( @@ -374,6 +377,7 @@ ORDER BY t.available_order,t.id LIMIT 100 const TIMER_TASK_SQL: &str = "SELECT id,payload FROM workflow_tasks WHERE workflow_run_id=$1 AND task_type='timer' AND status='ready' AND json_extract(payload,'$.timer_id')=$2 AND namespace=$3"; const TIMER_SCHEDULE_SQL: &str = "SELECT payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='TimerScheduled' AND json_extract(payload,'$.timer_id')=$2 ORDER BY sequence DESC LIMIT 1"; const SIGNAL_RECEIVED_SEQUENCE_SQL: &str = "SELECT sequence FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='SignalReceived' AND json_extract(payload,'$.signal_id')=$2 ORDER BY sequence LIMIT 1"; + const ORDERED_CONDITION_HISTORY: &str = "SELECT 1 FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='ConditionWaitOpened' AND json_extract(payload,'$.condition_wait_input_order')='durable_receipt_order' LIMIT 1"; const RUN_COMMANDS_SQL: &str = super::store::run_commands_sql!( "substr(s.arguments,1,30) COLLATE BINARY='dw-native-external-payload-v1:'", @@ -679,6 +683,7 @@ impl Backend for MySql { const MEMO_INHERIT_INSERT: &str = "INSERT INTO workflow_memos(workflow_run_id,workflow_instance_id,`key`,value,upserted_at_sequence,inherited_from_parent,created_at,updated_at,portable_value,portable_value_sequence) VALUES ($1,$2,$3,$4,1,true,$5,$6,$7,1)"; const MEMO_READ: &str = "SELECT `key`,value,portable_value,portable_value_sequence,upserted_at_sequence FROM workflow_memos WHERE workflow_run_id=$1 ORDER BY `key`,id LIMIT 101"; const SELECTION_RESOLUTION_SQL: &str = "SELECT id,payload FROM workflow_history_events WHERE workflow_run_id=? AND event_type='SelectionResolved' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.selection_group_id'))=? ORDER BY sequence LIMIT 1"; + const SELECTION_CANDIDATE_SQL: &str = "SELECT payload FROM workflow_history_events WHERE workflow_run_id=? AND event_type='SelectionCandidateReady' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.selection_group_id'))=? ORDER BY sequence LIMIT 1"; const BRIDGE_COMMAND: &str = "SELECT workflow_run_id,resolved_workflow_run_id FROM workflow_commands WHERE workflow_instance_id=? AND command_type=? AND status='accepted' AND BINARY JSON_UNQUOTE(JSON_EXTRACT(context,'$.server.metadata.adapter'))=BINARY ? AND BINARY JSON_UNQUOTE(JSON_EXTRACT(context,'$.server.metadata.action'))=BINARY ? AND BINARY JSON_UNQUOTE(JSON_EXTRACT(context,'$.server.metadata.idempotency_key'))=BINARY ? AND BINARY JSON_UNQUOTE(JSON_EXTRACT(context,CONCAT('$.server.metadata.',?)))=BINARY ? AND (request_id IS NULL OR BINARY request_id=BINARY ?) ORDER BY accepted_at DESC,command_sequence DESC LIMIT 1"; const REPAIR_COUNTER_MAX: i64 = u32::MAX as i64; const RANGE_REPAIR_TASK_SQL: &str = "SELECT * FROM workflow_tasks WHERE workflow_run_id=? AND namespace=? AND task_type='workflow' AND status='failed' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.replay_blocked'))='true' ORDER BY CASE WHEN available_at IS NULL THEN 1 ELSE 0 END,available_at,created_at,id LIMIT 1"; @@ -712,6 +717,7 @@ impl Backend for MySql { const TIMER_TASK_SQL: &str = "SELECT id,payload FROM workflow_tasks WHERE workflow_run_id=? AND task_type='timer' AND status='ready' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.timer_id'))=? AND BINARY namespace=BINARY ?"; const TIMER_SCHEDULE_SQL: &str = "SELECT payload FROM workflow_history_events WHERE workflow_run_id=? AND event_type='TimerScheduled' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.timer_id'))=? ORDER BY sequence DESC LIMIT 1"; const SIGNAL_RECEIVED_SEQUENCE_SQL: &str = "SELECT sequence FROM workflow_history_events WHERE workflow_run_id=? AND event_type='SignalReceived' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.signal_id'))=? ORDER BY sequence LIMIT 1"; + const ORDERED_CONDITION_HISTORY: &str = "SELECT 1 FROM workflow_history_events WHERE workflow_run_id=? AND event_type='ConditionWaitOpened' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.condition_wait_input_order'))='durable_receipt_order' LIMIT 1"; // The payload column's collation ignores case; compare bytes. const RUN_COMMANDS_SQL: &str = super::store::run_commands_sql!( @@ -736,6 +742,7 @@ impl Backend for MySql { || sql == Self::SIGNAL_RECEIVED_SEQUENCE_SQL || sql == Self::RANGE_REPAIR_TASK_SQL || sql == Self::SELECTION_RESOLUTION_SQL + || sql == Self::SELECTION_CANDIDATE_SQL || sql == Self::BRIDGE_COMMAND || sql == Self::ACTIVITY_OPEN_TASK_SQL || sql == Self::LOCAL_ACTIVITY_EXECUTIONS diff --git a/rust/src/runtime/completion_rules.rs b/rust/src/runtime/completion_rules.rs index b850dde7a..7b47e09f9 100644 --- a/rust/src/runtime/completion_rules.rs +++ b/rust/src/runtime/completion_rules.rs @@ -831,8 +831,10 @@ const READS: &[(&str, &[&str])] = &[ ("upsert_search_attributes", &["attributes", "attribute_types"]), ("upsert_memo", &["entries"]), ("open_condition_wait", &["condition_key", "condition_definition_fingerprint", "condition_wait_occurrence_id", "timeout_seconds", - "deadline_policy", "condition_wait_timeout_budget_seconds"]), + "deadline_policy", "condition_wait_timeout_budget_seconds", + super::wait_timeouts::CONDITION_INPUT_ORDER_FIELD]), ("open_signal_wait", &["signal_name", "timeout_seconds"]), + (super::wait_timeouts::RESOLVE_CONDITION_WAIT, &["condition_wait_id", "satisfied", "input_receipt_sequence", "competing_resolution_event_id"]), ]; /// `parallelMetadataValidationRules`' fields, read for the leaf commands. diff --git a/rust/src/runtime/execution.rs b/rust/src/runtime/execution.rs index ee6bace65..edb8ecd72 100644 --- a/rust/src/runtime/execution.rs +++ b/rust/src/runtime/execution.rs @@ -222,6 +222,17 @@ impl Runtime { self.structural = limits; self } + /// Allow new ordered waits on workflow tasks claimed by this runtime. + /// Existing marked waits remain replayable with the setting disabled. + pub fn with_ordered_condition_wait_authoring(mut self, enabled: bool) -> Self { + let storage = match &*self.storage { + Storage::Sqlite(store) => Storage::Sqlite(store.with_ordered_condition_wait_authoring(enabled)), + Storage::Postgres(store) => Storage::Postgres(store.with_ordered_condition_wait_authoring(enabled)), + Storage::MySql(store) => Storage::MySql(store.with_ordered_condition_wait_authoring(enabled)), + }; + self.storage = Arc::new(storage); + self + } /// The configured history page sizes (DW_HISTORY_PAGE_SIZE_DEFAULT and _MAX). pub(super) fn history_pages(&self) -> super::history_pages::HistoryPages { super::history_pages::HistoryPages { diff --git a/rust/src/runtime/selections.rs b/rust/src/runtime/selections.rs index bacb8ca37..eb4ccd970 100644 --- a/rust/src/runtime/selections.rs +++ b/rust/src/runtime/selections.rs @@ -533,7 +533,7 @@ where } // Called immediately after the member's actual terminal event under // the same transition lock; bind its physical durable history ID. - let event = Self::query("SELECT id,event_type,payload FROM workflow_history_events WHERE workflow_run_id=$1 ORDER BY sequence DESC LIMIT 1") + let event = Self::query("SELECT id,sequence,event_type,payload FROM workflow_history_events WHERE workflow_run_id=$1 ORDER BY sequence DESC LIMIT 1") .bind(run_id).fetch_one(&mut **tx).await?; if DB::string(&event, "event_type")? != event_type { return Err(refuse( @@ -547,17 +547,66 @@ where } else { member_identity(entry, identity) }; - Self::append(tx, run_id, "SelectionResolved", json!({ + let mut resolution = json!({ "selection_group_id":group_id,"selection_group_base_sequence":entry["parallel_group_base_sequence"], "selection_group_size":entry["parallel_group_size"],"member_key":entry["selection_member_key"], "member_index":entry["selection_member_index"],"member_base_sequence":entry["selection_member_base_sequence"], "member_size":entry["selection_member_size"],"operation_kind":operation_kind, "operation_identity":identity,"outcome":outcome(event_type), "resolution_event_id":DB::string(&event,"id")?,"resolution_event_type":event_type, - }), None, None).await?; + }); + if kind == "child" + && Self::ordered_selection_has_open_condition(tx, run_id, group_id).await? + { + if Self::query(DB::SELECTION_CANDIDATE_SQL).bind(run_id).bind(group_id) + .fetch_optional(&mut **tx).await?.is_none() + { + // The child terminal is authoritative. The winner waits for + // the parent's predicate over inputs received before it. + resolution["resolution_event_sequence"] = json!(DB::number(&event, "sequence")?); + Self::append(tx, run_id, "SelectionCandidateReady", resolution, None, None).await?; + } + return Ok(false); + } + Self::append(tx, run_id, "SelectionResolved", resolution, None, None).await?; Ok(true) } + async fn ordered_selection_has_open_condition( + tx: &mut Transaction<'_, DB>, + run_id: &str, + group_id: &str, + ) -> Result { + if Self::query(DB::ORDERED_CONDITION_HISTORY) + .bind(run_id).fetch_optional(&mut **tx).await?.is_none() + { + return Ok(false); + } + let waits = Self::waits(tx, run_id).await?; + Ok(waits.conditions.iter().filter(|wait| wait.is_open()) + .filter_map(|wait| waits.condition_opening(&wait.id)) + .any(|opening| super::wait_timeouts::uses_condition_input_order(&opening.payload) + && selection(&opening.payload).is_some_and(|entry| entry["parallel_group_id"] == group_id))) + } + + pub(super) async fn unresolved_selection_candidate( + tx: &mut Transaction<'_, DB>, + run_id: &str, + opening: &Value, + ) -> Result> { + let Some(group_id) = selection(opening).and_then(|entry| entry["parallel_group_id"].as_str()) else { + return Ok(None); + }; + if Self::query(DB::SELECTION_RESOLUTION_SQL) + .bind(run_id).bind(group_id).fetch_optional(&mut **tx).await?.is_some() + { + return Ok(None); + } + let candidate = Self::query(DB::SELECTION_CANDIDATE_SQL) + .bind(run_id).bind(group_id).fetch_optional(&mut **tx).await?; + candidate.map(|row| DB::document_row(&row, "payload")).transpose() + } + /// Wakes the workflow after a member's close, or returns `None` when /// published PHP's `ParallelChildGroup::shouldWakeParentOnClosure` would /// not: a successful close inside an all-of group waits until every diff --git a/rust/src/runtime/store.rs b/rust/src/runtime/store.rs index 4891be6e5..d8fc59030 100644 --- a/rust/src/runtime/store.rs +++ b/rust/src/runtime/store.rs @@ -180,6 +180,7 @@ pub(super) struct Store { pub(super) memo_codec: Arc, pub(super) memo_size_limit: Option, pub(super) history_budget: super::history_budget::Config, + pub(super) ordered_condition_wait_authoring: bool, /// How long a claimed workflow task stays leased (DW_WORKFLOW_TASK_TIMEOUT). pub(super) workflow_task_lease_seconds: i64, pub(super) workflow_task_lost_lease_attention_threshold: i64, @@ -362,6 +363,10 @@ where memo_codec: Arc::new(Semaphore::new(1)), memo_size_limit: Some(262_144), history_budget: super::history_budget::Config::default(), + ordered_condition_wait_authoring: matches!( + std::env::var("DW_ORDERED_CONDITION_WAIT_AUTHORING").as_deref(), + Ok("1" | "true") + ), workflow_task_lease_seconds: 60, workflow_task_lost_lease_attention_threshold: std::env::var("DW_V2_WORKFLOW_TASK_LOST_LEASE_ATTENTION_THRESHOLD") .ok() @@ -398,6 +403,7 @@ where memo_codec: self.memo_codec.clone(), memo_size_limit: self.memo_size_limit, history_budget: self.history_budget, + ordered_condition_wait_authoring: self.ordered_condition_wait_authoring, workflow_task_lease_seconds: self.workflow_task_lease_seconds, workflow_task_lost_lease_attention_threshold: self.workflow_task_lost_lease_attention_threshold, activity_task_lease_seconds: self.activity_task_lease_seconds, @@ -420,6 +426,13 @@ where test_continuation_gate: self.test_continuation_gate.clone(), } } + + pub(super) fn with_ordered_condition_wait_authoring(&self, enabled: bool) -> Self { + let mut store = self.in_namespace(&self.namespace); + store.ordered_condition_wait_authoring = enabled; + store + } + pub(super) async fn database_live(&self) -> bool { Self::query("SELECT 1").execute(&self.pool).await.is_ok() } @@ -1815,8 +1828,20 @@ where else { return Ok(None); }; - let started = DB::document_row(&started, "payload")?; - if super::run_observation::command_contract(Some(&started))["source"] != "durable_history" { + let mut started = DB::document_row(&started, "payload")?; + let mut durable = super::run_observation::command_contract(Some(&started))["source"] == "durable_history"; + // An ordered condition can be the first task of a run started before + // its worker registered. Its accepted completion already binds the + // worker's command declaration for the run. Use that same declaration + // to distinguish a handled signal from an input without a handler. + if !durable + && Self::query(DB::ORDERED_CONDITION_HISTORY).bind(run_id).fetch_optional(&mut **tx).await?.is_some() + { + let bound = Self::bound_contract(&mut **tx, run_id).await?; + started = super::update_contracts::effective(&started, bound.as_ref()); + durable = super::run_observation::command_contract(Some(&started))["source"] == "durable_history"; + } + if !durable { return Ok(None); } Ok(Some( @@ -1842,11 +1867,13 @@ where fn signal_can_advance( waits: &super::wait_history::Waits, declared: Option<&[String]>, + signal_id: &str, name: &str, signal_wait_id: Option<&str>, include_received: bool, ) -> bool { waits.advanceable_condition() + || waits.ordered_condition_can_consume(signal_id) || signal_wait_id.is_some_and(|signal_wait_id| waits.signal_advanceable(name, signal_wait_id, include_received)) || declared.is_some_and(|names| names.iter().any(|declared| declared == name)) } @@ -1896,6 +1923,7 @@ where if !Self::signal_can_advance( &waits, declared.as_deref(), + &DB::string(&signal, "id")?, &DB::string(&signal, "signal_name")?, DB::optional_string(&signal, "signal_wait_id")?.as_deref(), include_received, @@ -2055,7 +2083,8 @@ where // `recordSatisfiedConditionWaitForSignalResume` then satisfies the // latest open condition wait whose timeout has not fired. let condition = waits.latest_open_condition(); - if !applies && condition.is_none() { + let ordered_input = waits.ordered_condition_can_consume(signal_id); + if !applies && condition.is_none() && !ordered_input { // Core leaves the signal received and completes the task. Native // refuses such a completion, unless Core's own history explains // it: the signal names a wait the run has had, or a condition wait @@ -2070,12 +2099,12 @@ where let reason = if waits.any_current() { "signal_wait_mismatch" } else { "signal_wait_not_open" }; return Err(refuse(StatusCode::CONFLICT, reason)); } - // An undeclared signal without a wait of its own is consumed by the - // condition wait at that wait's sequence, without `SignalApplied` - // (`markConditionWaitSignalConsumed`). + // A signal without a declared handler or named wait is consumed + // without `SignalApplied`. A marked condition can also consume that + // input after its timer fired so it cannot block the eligible prefix. let record_sequence = if applies { sequence } else { condition.and_then(|wait| wait.sequence) }; let mut winner = None; - if applies || record_sequence.is_some() { + if applies || record_sequence.is_some() || ordered_input { // Arguments stored by reference were resolved before this // transaction, for exactly this reference (Server #979). let stored = DB::string(&signal, "arguments")?; @@ -2169,6 +2198,13 @@ where }; for condition in awakened { let condition_opening = waits.condition_opening(&condition.id); + if condition_opening.is_some_and(|opening| { + super::wait_timeouts::uses_condition_input_order(&opening.payload) + }) { + // The signal's application is input evidence. For a + // marked condition it does not settle the predicate. + continue; + } let mut satisfied = condition.satisfied(condition_opening, &payload); // A task that reopens the same occurrence claims no winner. let selected = super::selections::is_selection(&satisfied); @@ -2208,7 +2244,7 @@ where /// Native serves a selection directly over its waits; one nested in /// another group, or with a member wider than one sequence, stays an /// explicit unqualified shape rather than a silent divergence. - async fn claim_wait_selection( + pub(super) async fn claim_wait_selection( tx: &mut Transaction<'_, DB>, run_id: &str, group: &serde_json::Map, @@ -2793,6 +2829,13 @@ where return Ok(false); } } + // A worker must understand these outcomes for the rest of the run, + // including replay after its marked condition has already resolved. + if !supports(super::wait_timeouts::CONDITION_INPUT_ORDER_FIELD) + && Self::query(DB::ORDERED_CONDITION_HISTORY).bind(run_id).fetch_optional(&mut *connection).await?.is_some() + { + return Ok(false); + } Ok(true) } @@ -3198,6 +3241,14 @@ where "updated_at":DB::instant(&worker,"updated_at")?,"last_heartbeat_at":DB::instant(&worker,"last_heartbeat_at")?, "task_id":task_id,"run_id":run_id,"lease_owner":worker_id,"attempt":attempt}); } + let allow_ordered_condition_open = kind == "workflow" + && self.ordered_condition_wait_authoring + && super::wait_timeouts::supports_condition_input_order( + &task_payload[super::cooperative::CLAIM_KEY]["capabilities"], + ); + if allow_ordered_condition_open { + task_payload[super::cooperative::CLAIM_KEY][super::wait_timeouts::CONDITION_INPUT_AUTHORING] = json!(true); + } // `claimStatus`: a workflow claim records the replay its worker // should expect from the run's sticky affinity (Server #1017). let (sticky_worker, sticky_until, sticky_mode) = if kind == "workflow" { @@ -3303,6 +3354,9 @@ where } } else { claim["workflow_task_attempt"] = json!(attempt); + if allow_ordered_condition_open { + claim[super::wait_timeouts::CONDITION_INPUT_AUTHORING] = json!(true); + } claim["arguments"] = wire(&DB::string(&run, "arguments")?); if let Some(update_id) = task_payload["workflow_update_id"].as_str() { claim["workflow_update_id"] = json!(update_id); @@ -3374,6 +3428,13 @@ where // expected to hit its cache gets only the events after the // boundary it reported with its previous completion of the run. let capabilities = DB::optional_document_row(&worker, "capabilities")?; + if capabilities.as_ref().is_some_and(super::wait_timeouts::supports_condition_input_order) + && Self::query(DB::ORDERED_CONDITION_HISTORY).bind(&run_id).fetch_optional(&mut **tx).await?.is_some() + { + claim[super::wait_timeouts::PENDING_CONDITION_INPUT] = json!( + Self::first_pending_condition_input(&mut **tx, &run_id).await? + ); + } let suffix_worker = super::sticky_execution::takes_suffixes(capabilities.as_ref()) && super::sticky_execution::registration_supports(capabilities.as_ref(), DB::optional_document_row(&worker, "capability_manifest")?.as_ref(), "sticky_execution"); @@ -3803,6 +3864,9 @@ where .await?; // PHP releases the run and schedules its next message together. Self::enqueue_next_message(&mut tx, &run_id, &DB::string(&run, "queue")?, false).await?; + if payload["resume_source_kind"] == "workflow_signal" { + Self::enqueue_condition_evaluation(&mut tx, &run_id, &DB::string(&run, "queue")?, task_id).await?; + } let next = Self::query("SELECT id FROM workflow_tasks WHERE workflow_run_id=$1 AND task_type='workflow' AND status='ready' ORDER BY created_at DESC,id DESC LIMIT 1") .bind(&run_id) .fetch_optional(&mut *tx) @@ -3998,6 +4062,7 @@ where "timeout_seconds", "deadline_policy", "condition_wait_timeout_budget_seconds", + super::wait_timeouts::CONDITION_INPUT_ORDER_FIELD, ], )?; if command @@ -4010,10 +4075,15 @@ where // definition fingerprint are optional strings, of any form. super::wait_timeouts::timeout_for(command, "invalid_condition_timeout")?; super::wait_timeouts::occurrence_deadline(command)?; + super::wait_timeouts::validate_condition_input_order(command)?; } super::external_signals::COMMAND => { super::external_signals::validate(command)?; } + super::wait_timeouts::RESOLVE_CONDITION_WAIT => { + reject_fields(command, &["type", "condition_wait_id", "satisfied", "input_receipt_sequence", "competing_resolution_event_id"])?; + super::wait_timeouts::ConditionDecision::parse(command)?; + } "open_signal_wait" => { super::selections::fields(command, &["type", "signal_name", "timeout_seconds"])?; text(command, "signal_name")?; @@ -4401,6 +4471,12 @@ where { created.push(next); } + if (task_payload["resume_source_kind"] == "workflow_signal" + || commands.iter().any(|command| matches!(command["type"].as_str(), Some("complete_update" | "fail_update")))) + && let Some(next) = Self::enqueue_condition_evaluation(&mut tx, &run_id, &DB::string(&run, "queue")?, task_id).await? + { + created.push(next); + } Self::record_completion(&mut tx, task_id, &json!({COMPLETION_RECEIPT: {COMPLETION_REQUEST_DIGEST: completion_request_digest(&body), "created_task_ids": created}})).await?; // PHP's executor leaves every run a completed task did not close // waiting, even when the task recorded only markers or side effects. @@ -4468,6 +4544,17 @@ where created: &mut Vec, ) -> Result<()> { let Apply { run, task, task_id, run_id, attempt, limits, external, local, exceptions, start_turn, codec, grouped_condition_repeats } = *apply; + let ordered_open = super::wait_timeouts::uses_condition_input_order(command); + if ordered_open || command["type"] == super::wait_timeouts::RESOLVE_CONDITION_WAIT { + let payload = DB::document_row(task, "payload")?; + let claim = &payload[super::cooperative::CLAIM_KEY]; + if !super::wait_timeouts::supports_condition_input_order(&claim["capabilities"]) { + return Err(refuse(StatusCode::CONFLICT, "condition_wait_input_order_not_supported")); + } + if ordered_open && claim[super::wait_timeouts::CONDITION_INPUT_AUTHORING] != true { + return Err(refuse(StatusCode::CONFLICT, "condition_wait_input_order_authoring_disabled")); + } + } if command["type"] != super::local_activities::COMMAND { Self::write_local_activities(tx).await?; } @@ -4482,6 +4569,11 @@ where // does not count update events toward the next turn's sequence. sequence += 1; Self::apply_update(tx, &run, &task, command, sequence).await?; + } else if command["type"] == super::wait_timeouts::RESOLVE_CONDITION_WAIT { + let decision = super::wait_timeouts::ConditionDecision::parse(command)?; + if let Some(next) = Self::record_ordered_condition_decision(tx, run_id, &DB::string(run, "queue")?, task_id, decision).await? { + created.push(next); + } } else if command["type"] == "start_child_workflow" { Self::guard_pending(tx, &run_id, super::memo_limits::Pending::Children, &limits, task_id, attempt).await?; sequence += 1; @@ -5205,6 +5297,7 @@ where .bind(&task_id) .execute(&mut *tx) .await?; + let evaluates_receipt_prefix = super::wait_timeouts::uses_condition_input_order(&payload); Self::append( &mut tx, &run_id, @@ -5214,15 +5307,19 @@ where None, ) .await?; - Self::resolve_selection( - &mut tx, - &run_id, - &metadata, - member, - operation_id, - "TimerFired", - ) - .await?; + // The timer supplies the ordered-input boundary. A marked + // condition's outcome is decided separately from its timer fire. + if !evaluates_receipt_prefix { + Self::resolve_selection( + &mut tx, + &run_id, + &metadata, + member, + operation_id, + "TimerFired", + ) + .await?; + } Self::query("UPDATE workflow_run_timers SET status='fired',fired_at=$1 WHERE id=$2") .bind(DB::bind_time(fired_at)) .bind(&timer_id) @@ -5238,7 +5335,7 @@ where &DB::string(&timer, "queue")?, resume, &metadata, - true, + !evaluates_receipt_prefix, ) .await?; } @@ -6615,6 +6712,11 @@ fn capabilities_template() -> Value { "condition_wait_occurrence_deadline": true, "workflow_task_completion_activity_poll": true, "activity_completion_workflow_poll": true, "workflow_task_completion_workflow_poll": true}); value[super::children::CAPABILITY_EXPLICIT_ID] = json!(true); + value[super::wait_timeouts::CONDITION_INPUT_ORDER_FIELD] = json!(super::wait_timeouts::DURABLE_RECEIPT_ORDER); + value["supported_workflow_task_commands"] + .as_array_mut() + .expect("commands") + .push(json!(super::wait_timeouts::RESOLVE_CONDITION_WAIT)); value[super::continuation::CAPABILITY] = super::continuation::capability(); // Gated off until installed acceptance (Server #1201). if let Some(advertised) = super::timeout_cleanup::advertisement() { diff --git a/rust/src/runtime/wait_history.rs b/rust/src/runtime/wait_history.rs index 21b611899..abec9277b 100644 --- a/rust/src/runtime/wait_history.rs +++ b/rust/src/runtime/wait_history.rs @@ -430,6 +430,18 @@ impl Waits { self.conditions.iter().any(ConditionWait::advanceable) } + /// An ordered condition can still consume a signal received before its + /// timer, even after the timer has fired. Later signals use normal routing. + pub(super) fn ordered_condition_can_consume(&self, signal_id: &str) -> bool { + let Some(receipt) = self.received_at(signal_id) else { return false; }; + self.conditions.iter().any(|wait| { + wait.is_open() && wait.fired_at.is_none_or(|fire| receipt < fire) + && self.condition_opening(&wait.id).is_some_and(|opening| { + super::wait_timeouts::uses_condition_input_order(&opening.payload) + }) + }) + } + /// `latestOpenConditionWait`: the open condition wait with the highest /// sequence whose timeout has not fired. pub(super) fn latest_open_condition(&self) -> Option<&ConditionWait> { diff --git a/rust/src/runtime/wait_projection.rs b/rust/src/runtime/wait_projection.rs index 0627a4c15..3640d6e11 100644 --- a/rust/src/runtime/wait_projection.rs +++ b/rust/src/runtime/wait_projection.rs @@ -306,6 +306,11 @@ where Self::query("UPDATE workflow_run_waits SET status='resolved',source_status='satisfied',summary='Condition satisfied.',resume_source_kind='external_input',resume_source_id=NULL,resolved_at=$1,updated_at=$2 WHERE workflow_run_id=$3 AND wait_id=$4 AND kind='condition' AND status='open'") .bind(DB::bind_time(at)).bind(DB::bind_time(at)).bind(run_id).bind(wait_id) .execute(&mut **tx).await?; + } else if event_type == "ConditionWaitTimedOut" && super::wait_timeouts::uses_condition_input_order(payload) { + let wait_id = super::text(payload, "condition_wait_id")?; + Self::query("UPDATE workflow_run_waits SET status='resolved',source_status='timed_out',summary='Condition timed out.',resolved_at=$1,updated_at=$2 WHERE workflow_run_id=$3 AND wait_id=$4 AND kind='condition' AND status='open'") + .bind(DB::bind_time(at)).bind(DB::bind_time(at)).bind(run_id).bind(wait_id) + .execute(&mut **tx).await?; } else if payload["timer_kind"] == "condition_timeout" && matches!( event_type, diff --git a/rust/src/runtime/wait_timeouts.rs b/rust/src/runtime/wait_timeouts.rs index 64b3c9640..2d6e49912 100644 --- a/rust/src/runtime/wait_timeouts.rs +++ b/rust/src/runtime/wait_timeouts.rs @@ -12,6 +12,57 @@ use serde_json::{Value, json}; use sqlx::{ColumnIndex, Decode, Encode, Executor, IntoArguments, Type}; use std::collections::BTreeSet; +pub(super) const CONDITION_INPUT_ORDER_FIELD: &str = "condition_wait_input_order"; +pub(super) const CONDITION_INPUT_AUTHORING: &str = "condition_wait_input_order_authoring"; +pub(super) const DURABLE_RECEIPT_ORDER: &str = "durable_receipt_order"; +pub(super) const RESOLVE_CONDITION_WAIT: &str = "resolve_condition_wait"; +pub(super) const PENDING_CONDITION_INPUT: &str = "condition_wait_pending_input_sequence"; + +pub(super) struct ConditionDecision<'a> { + wait_id: &'a str, + satisfied: bool, + receipt: Option, + competing_resolution_event_id: Option<&'a str>, +} + +impl<'a> ConditionDecision<'a> { + pub(super) fn parse(command: &'a Value) -> Result { + let invalid = || refuse(StatusCode::UNPROCESSABLE_ENTITY, "invalid_condition_wait_outcome"); + let wait_id = command["condition_wait_id"].as_str() + .filter(|id| !id.is_empty() && id.len() <= 191) + .ok_or_else(invalid)?; + let satisfied = command["satisfied"].as_bool().ok_or_else(invalid)?; + let receipt = command.get("input_receipt_sequence") + .map(|value| value.as_i64().filter(|value| *value > 0).ok_or_else(invalid)) + .transpose()?; + let competing_resolution_event_id = command.get("competing_resolution_event_id") + .map(|value| value.as_str().filter(|id| !id.is_empty() && id.len() <= 191).ok_or_else(invalid)) + .transpose()?; + if (!satisfied && receipt.is_some()) || (satisfied && competing_resolution_event_id.is_some()) { + return Err(invalid()); + } + Ok(Self { wait_id, satisfied, receipt, competing_resolution_event_id }) + } +} + +pub(super) fn uses_condition_input_order(payload: &Value) -> bool { + payload[CONDITION_INPUT_ORDER_FIELD] == DURABLE_RECEIPT_ORDER +} + +pub(super) fn supports_condition_input_order(capabilities: &Value) -> bool { + capabilities.as_array().is_some_and(|flags| flags.iter().any(|flag| flag == CONDITION_INPUT_ORDER_FIELD)) +} + +pub(super) fn validate_condition_input_order(command: &Value) -> Result<()> { + if command.get(CONDITION_INPUT_ORDER_FIELD).is_none() { + return Ok(()); + } + if uses_condition_input_order(command) && command["deadline_policy"] == "occurrence" { + return Ok(()); + } + Err(refuse(StatusCode::UNPROCESSABLE_ENTITY, "invalid_condition_wait_input_order")) +} + pub(super) fn timeout(command: &Value) -> Result)>> { timeout_for(command, "invalid_signal_timeout") } @@ -79,6 +130,7 @@ pub(super) fn wait_fields(wait: &Value) -> Value { "condition_wait_occurrence_id", "condition_key", "condition_definition_fingerprint", + CONDITION_INPUT_ORDER_FIELD, "signal_wait_id", "signal_name", ] { @@ -114,6 +166,166 @@ where for<'r> i64: Decode<'r, DB>, usize: ColumnIndex, { + pub(super) async fn first_pending_condition_input( + connection: &mut DB::Connection, + run_id: &str, + ) -> Result> { + let pending = Self::query( + "SELECT received.sequence FROM workflow_history_events received + JOIN workflow_commands command ON command.id=received.workflow_command_id + AND command.resolved_workflow_run_id=received.workflow_run_id + WHERE received.workflow_run_id=$1 + AND received.event_type IN ('SignalReceived','UpdateAccepted') + AND command.status='accepted' AND command.applied_at IS NULL + ORDER BY received.sequence LIMIT 1", + ).bind(run_id).fetch_optional(connection).await?; + pending.map(|row| DB::number(&row, "sequence")).transpose() + } + + /// An input task can settle the last accepted input without evaluating + /// the workflow. Give the still-open predicate a turn over that committed + /// history when no existing workflow task will see it. + pub(super) async fn enqueue_condition_evaluation( + tx: &mut Transaction<'_, DB>, + run_id: &str, + queue: &str, + task_id: &str, + ) -> Result> { + if Self::query(DB::ORDERED_CONDITION_HISTORY).bind(run_id).fetch_optional(&mut **tx).await?.is_none() { + return Ok(None); + } + let source = Self::query( + "SELECT e.id,e.event_type FROM workflow_history_events e + JOIN workflow_runs r ON r.id=e.workflow_run_id + WHERE e.workflow_run_id=$1 AND e.workflow_task_id=$2 + AND e.event_type IN ('SignalApplied','UpdateCompleted','MessageCursorAdvanced') + AND r.status IN ('pending','running','waiting') + AND NOT EXISTS (SELECT 1 FROM workflow_tasks pending + WHERE pending.workflow_run_id=r.id AND pending.task_type='workflow' + AND pending.status IN ('ready','leased')) + ORDER BY e.sequence DESC LIMIT 1", + ).bind(run_id).bind(task_id).fetch_optional(&mut **tx).await?; + let Some(source) = source else { return Ok(None); }; + let waits = Self::waits(tx, run_id).await?; + let Some((wait, opening)) = waits.conditions.iter().filter(|wait| wait.is_open()) + .filter_map(|wait| waits.condition_opening(&wait.id).map(|opening| (wait, opening))) + .find(|(_, opening)| uses_condition_input_order(&opening.payload)) + else { return Ok(None); }; + let mut payload = wait_fields(&opening.payload); + payload["workflow_wait_kind"] = json!("condition"); + payload["open_wait_id"] = json!(wait.id); + payload["resume_source_kind"] = json!("condition_input"); + payload["resume_source_id"] = json!(DB::string(&source, "id")?); + payload["workflow_event_type"] = json!(DB::string(&source, "event_type")?); + payload["workflow_sequence"] = json!(wait.sequence); + Self::create_task(tx, run_id, queue, "workflow", payload).await.map(Some) + } + + pub(super) async fn record_ordered_condition_decision( + tx: &mut Transaction<'_, DB>, + run_id: &str, + queue: &str, + task_id: &str, + decision: ConditionDecision<'_>, + ) -> Result> { + let mismatch = || refuse(StatusCode::CONFLICT, "condition_wait_outcome_mismatch"); + let waits = Self::waits(tx, run_id).await?; + let wait = waits.conditions.iter().find(|wait| wait.id == decision.wait_id && wait.is_open()) + .ok_or_else(mismatch)?; + let opening = waits.condition_opening(&wait.id) + .filter(|opening| uses_condition_input_order(&opening.payload)) + .ok_or_else(mismatch)?; + let timeout = wait.fired_at; + let candidate = Self::unresolved_selection_candidate(tx, run_id, &opening.payload).await?; + let competing_sequence = candidate.as_ref() + .map(|candidate| candidate["resolution_event_sequence"].as_i64().ok_or_else(mismatch)) + .transpose()?; + let selection_boundary = timeout.into_iter().chain(competing_sequence).min(); + if let Some(event_id) = decision.competing_resolution_event_id { + let mut candidate = candidate.filter(|value| value["resolution_event_id"] == event_id) + .ok_or_else(mismatch)?; + let boundary = competing_sequence.filter(|sequence| Some(*sequence) == selection_boundary) + .ok_or_else(mismatch)?; + Self::guard_condition_prefix(tx, run_id, boundary).await?; + candidate.as_object_mut().unwrap().remove("resolution_event_sequence"); + Self::append(tx, run_id, "SelectionResolved", candidate, Some(task_id), None).await?; + let metadata = super::selections::selection(&opening.payload).ok_or_else(mismatch)?; + return Self::selection_resume(tx, run_id, queue, json!({ + "resume_source_kind":"condition_outcome", "resume_source_id":wait.id, + "workflow_wait_kind":"condition", "open_wait_id":wait.id, "condition_wait_id":wait.id, + "workflow_event_type":"SelectionResolved", "workflow_sequence":wait.sequence, + }), metadata, true).await; + } + if (!decision.satisfied && timeout.is_none()) + || (decision.satisfied && timeout.is_some() && decision.receipt.is_none()) + || (!decision.satisfied && timeout != selection_boundary) + { + return Err(mismatch()); + } + if let Some(receipt) = decision.receipt { + if selection_boundary.is_some_and(|boundary| receipt >= boundary) { + return Err(mismatch()); + } + // The received position is canonical even if the same task applied + // the signal or ran the update after the timer. Failed updates have + // no UpdateApplied event. + let evidence = Self::query( + "SELECT 1 FROM workflow_history_events received + JOIN workflow_history_events applied + ON applied.workflow_run_id=received.workflow_run_id + AND applied.workflow_command_id=received.workflow_command_id + WHERE received.workflow_run_id=$1 AND received.sequence=$2 + AND ((received.event_type='SignalReceived' AND applied.event_type='SignalApplied') + OR (received.event_type='UpdateAccepted' AND applied.event_type='UpdateApplied')) LIMIT 1", + ).bind(run_id).bind(receipt).fetch_optional(&mut **tx).await?; + if evidence.is_none() { + return Err(mismatch()); + } + } + let prefix_end = if decision.satisfied { decision.receipt } else { timeout }; + if let Some(boundary) = prefix_end { + Self::guard_condition_prefix(tx, run_id, boundary).await?; + } + let group = super::activity_metadata::payload_for_path(&opening.payload); + let mut payload = wait_fields(&opening.payload); + payload.as_object_mut().unwrap().extend(group.clone()); + let sequence = wait.sequence.ok_or_else(mismatch)?; + payload["sequence"] = json!(sequence); + if let Some(receipt) = decision.receipt { + payload["input_receipt_sequence"] = json!(receipt); + } + if let Some(fire) = timeout { + payload["timer_fired_sequence"] = json!(fire); + payload["timer_id"] = json!(wait.timer_id().ok_or_else(mismatch)?); + } + let event = if decision.satisfied { "ConditionWaitSatisfied" } else { "ConditionWaitTimedOut" }; + Self::append(tx, run_id, event, payload, Some(task_id), None).await?; + let winner = Self::claim_wait_selection(tx, run_id, &group, "condition", &wait.id, event).await?; + if timeout.is_none() { + Self::cancel_wait_timeout(tx, run_id, + &json!({"sequence":sequence,"condition_wait_id":wait.id}), task_id, now()).await?; + } + if let Some(winner) = winner { + return Self::selection_resume(tx, run_id, queue, json!({ + "workflow_wait_kind":"condition","open_wait_id":wait.id, + "condition_wait_id":wait.id,"resume_source_kind":"condition_outcome", + "resume_source_id":wait.id,"workflow_event_type":event,"workflow_sequence":sequence, + }), &winner, true).await; + } + Ok(None) + } + + async fn guard_condition_prefix( + tx: &mut Transaction<'_, DB>, + run_id: &str, + boundary: i64, + ) -> Result<()> { + if Self::first_pending_condition_input(&mut **tx, run_id).await?.is_some_and(|pending| pending < boundary) { + return Err(refuse(StatusCode::CONFLICT, "condition_wait_input_pending")); + } + Ok(()) + } + /// A terminal run cannot fire its remaining wait timeouts. Settle their /// physical rows without adding the cancellation events that published PHP /// omits for ordinary completion, failure and continuation. Authored timers @@ -228,6 +440,13 @@ where return Err(super::all_groups::invalid()); } let mismatch = || refuse(StatusCode::CONFLICT, "condition_wait_occurrence_mismatch"); + if chain.iter().any(|wait| { + waits.condition_opening(&wait.id).is_some_and(|opening| { + opening.payload[CONDITION_INPUT_ORDER_FIELD] != command[CONDITION_INPUT_ORDER_FIELD] + }) + }) { + return Err(mismatch()); + } let unavailable = || refuse(StatusCode::CONFLICT, "condition_wait_anchor_unavailable"); let Some(budget) = budget else { // Omitting the policy on an anchored chain is a mismatch. diff --git a/rust/tests/execution/occurrence_deadlines.rs b/rust/tests/execution/occurrence_deadlines.rs index c0e81a3b3..f5017f2c1 100644 --- a/rust/tests/execution/occurrence_deadlines.rs +++ b/rust/tests/execution/occurrence_deadlines.rs @@ -15,6 +15,7 @@ fn anchored(occurrence: &str, remaining: i64, budget: i64) -> Value { async fn author(app: &Router, namespace: &str, worker: &str) -> Value { let response = namespaces::scoped(app, namespace, "POST", "/api/worker/register", json!({ "worker_id":worker,"task_queue":"test","runtime":"php","supported_workflow_types":["echo"],"supported_activity_types":[], + "capabilities":["condition_wait_input_order"], "workflow_command_contracts":{"echo":{"signals":["payload"],"signal_contracts":[{"name":"payload","parameters":[{ "name":"value","position":0,"type":"int","required":true,"variadic":false,"default_available":false,"allows_null":false}]}]}} })).await; @@ -30,12 +31,41 @@ async fn claim(app: &Router, namespace: &str) -> Value { response.1["task"].clone() } +async fn claim_with_request_id(app: &Router, request_id: &str) -> Value { + let (status, result) = request(app, "POST", "/api/worker/workflow-tasks/poll", json!({ + "worker_id":"deadline-worker", "task_queue":"test", "timeout_seconds":5, "poll_request_id":request_id, + })).await; + assert_eq!(status, StatusCode::OK, "{result}"); + assert!(result["task"].is_object(), "{result}"); + result["task"].clone() +} + async fn finish(app: &Router, namespace: &str, task: &Value, commands: Value) -> (StatusCode, Value) { namespaces::scoped(app, namespace, "POST", &format!("/api/worker/workflow-tasks/{}/complete", task["task_id"].as_str().unwrap()), completion(task, commands)).await } +async fn await_next_input(app: &Router, namespace: &str, task: &Value) { + let (status, result) = namespaces::scoped(app, namespace, "POST", + &format!("/api/worker/workflow-tasks/{}/fail", task["task_id"].as_str().unwrap()), + json!({"lease_owner":task["lease_owner"],"workflow_task_attempt":task["workflow_task_attempt"], + "failure":{"type":"WorkflowTaskWaitingForHistory","message":"Waiting for the next accepted input."}}), + ).await; + assert_eq!(status, StatusCode::OK, "{result}"); + assert_eq!(result["outcome"], "waiting_for_history"); +} + +async fn claim_input(app: &Router, namespace: &str, kind: &str) -> Value { + let mut task = claim(app, namespace).await; + if task["resume_source_kind"] == "timer" { + await_next_input(app, namespace, &task).await; + task = claim(app, namespace).await; + } + assert_eq!(task["resume_source_kind"], kind); + task +} + async fn history(app: &Router, namespace: &str, run: &Value) -> Vec { let response = namespaces::scoped(app, namespace, "GET", &format!("/api/workflows/{}/runs/{}/history", run["workflow_id"].as_str().unwrap(), run["run_id"].as_str().unwrap()), @@ -61,7 +91,7 @@ fn instant(value: &Value) -> chrono::DateTime { async fn setup(namespace: &str) -> (TestDatabase, Runtime, Router) { let database = TestDatabase::new().await; - let runtime = database.open().await.unwrap(); + let runtime = database.open().await.unwrap().with_ordered_condition_wait_authoring(true); let app = router(runtime.clone()); if namespace != "default" { namespaces::create(&app, namespace).await; @@ -71,6 +101,53 @@ async fn setup(namespace: &str) -> (TestDatabase, Runtime, Router) { (database, runtime, app) } +#[tokio::test] +async fn authoring_is_bound_to_the_claim_and_can_be_disabled_while_a_wait_replays() { + let namespace = "default"; + let (database, runtime, enabled) = setup(namespace).await; + let disabled = router(runtime.clone().with_ordered_condition_wait_authoring(false)); + let legacy = namespaces::start_scoped(&disabled, namespace, "legacy-while-upgrading").await; + let task = claim_with_request_id(&disabled, "legacy-authoring-claim").await; + assert!(task.get("condition_wait_input_order_authoring").is_none()); + let repeated = claim_with_request_id(&enabled, "legacy-authoring-claim").await; + assert_eq!(repeated["task_id"], task["task_id"]); + assert_eq!(repeated["workflow_task_attempt"], task["workflow_task_attempt"]); + assert!(repeated.get("condition_wait_input_order_authoring").is_none()); + let mut command = anchored("gate:0", 240, 240); + command["condition_wait_input_order"] = json!("durable_receipt_order"); + let prefix = history(&disabled, namespace, &legacy).await; + let (status, result) = finish(&enabled, namespace, &task, json!([command])).await; + assert_eq!(status, StatusCode::CONFLICT, "{result}"); + assert_eq!(result["reason"], "condition_wait_input_order_authoring_disabled"); + assert_eq!(history(&disabled, namespace, &legacy).await, prefix); + let (status, result) = finish(&disabled, namespace, &task, json!([anchored("gate:0", 240, 240)])).await; + assert_eq!(status, StatusCode::OK, "{result}"); + + let run = namespaces::start_scoped(&enabled, namespace, "ordered-after-upgrade").await; + let task = claim_with_request_id(&enabled, "ordered-authoring-claim").await; + assert_eq!(task["condition_wait_input_order_authoring"], true); + let repeated = claim_with_request_id(&disabled, "ordered-authoring-claim").await; + assert_eq!(repeated["task_id"], task["task_id"]); + assert_eq!(repeated["workflow_task_attempt"], task["workflow_task_attempt"]); + assert_eq!(repeated["condition_wait_input_order_authoring"], true); + let mut command = anchored("gate:0", 0, 0); + command["condition_wait_input_order"] = json!("durable_receipt_order"); + let (status, result) = finish(&disabled, namespace, &task, json!([command])).await; + assert_eq!(status, StatusCode::OK, "{result}"); + let fired = wait_for_fire(&disabled, namespace, &run, 1).await; + let replay = claim(&disabled, namespace).await; + assert!(replay.get("condition_wait_input_order_authoring").is_none()); + assert_eq!(replay.get("condition_wait_pending_input_sequence"), Some(&Value::Null)); + let (status, result) = finish(&disabled, namespace, &replay, json!([{ + "type":"resolve_condition_wait","condition_wait_id":fired[0]["condition_wait_id"],"satisfied":false, + }])).await; + assert_eq!(status, StatusCode::OK, "{result}"); + let events = history(&disabled, namespace, &run).await; + assert_eq!(payloads(&events, "ConditionWaitTimedOut").len(), 1); + runtime.close().await; + database.remove().await; +} + /// Open the first anchored wait of `occurrence`, returning the run and A. async fn open(app: &Router, namespace: &str, name: &str, occurrence: &str, budget: i64) -> (Value, Value) { let run = namespaces::start_scoped(app, namespace, name).await; @@ -120,6 +197,330 @@ async fn the_cluster_advertises_the_occurrence_deadline() { database.remove().await; } +#[tokio::test] +async fn a_condition_occurrence_cannot_change_its_input_order_policy() { + for marked in [false, true] { + let namespace = "default"; + let (database, runtime, app) = setup(namespace).await; + let run = namespaces::start_scoped(&app, namespace, "per-occurrence-input-order").await; + let opening = claim(&app, namespace).await; + let mut command = anchored("receipt-order:0", 60, 60); + if marked { + command["condition_wait_input_order"] = json!("durable_receipt_order"); + } + assert_eq!( + finish(&app, namespace, &opening, json!([command.clone()])).await.0, + StatusCode::OK, + ); + + signal(&app, namespace, &run).await; + let wake = claim(&app, namespace).await; + if marked { + command.as_object_mut().unwrap().remove("condition_wait_input_order"); + } else { + command["condition_wait_input_order"] = json!("durable_receipt_order"); + } + let before = history(&app, namespace, &run).await; + let (status, result) = finish(&app, namespace, &wake, json!([command])).await; + assert_eq!(status, StatusCode::CONFLICT, "{result}"); + assert_eq!(result["reason"], "condition_wait_occurrence_mismatch"); + assert_eq!(history(&app, namespace, &run).await, before); + runtime.close().await; + database.remove().await; + } +} + +#[tokio::test] +async fn applying_a_signal_does_not_settle_a_condition_with_receipt_order() { + let namespace = "default"; + let (database, runtime, app) = setup(namespace).await; + let run = namespaces::start_scoped(&app, namespace, "ordered-predicate-wake").await; + let initial = claim(&app, namespace).await; + let mut command = anchored("receipt-order:0", 60, 60); + command["condition_wait_input_order"] = json!("durable_receipt_order"); + let (status, result) = finish(&app, namespace, &initial, json!([command.clone()])).await; + assert_eq!(status, StatusCode::OK, "{result}"); + + signal(&app, namespace, &run).await; + let wake = claim(&app, namespace).await; + let (status, result) = finish(&app, namespace, &wake, json!([command])).await; + assert_eq!(status, StatusCode::OK, "{result}"); + let events = history(&app, namespace, &run).await; + assert_eq!(payloads(&events, "SignalApplied").len(), 1); + assert_eq!(payloads(&events, "ConditionWaitOpened").len(), 1); + assert!(payloads(&events, "ConditionWaitSatisfied").is_empty()); + assert!(payloads(&events, "TimerCancelled").is_empty()); + runtime.close().await; + database.remove().await; +} + +#[tokio::test] +async fn acknowledging_the_last_signal_wakes_the_ordered_predicate() { + let namespace = "default"; + let database = TestDatabase::new().await; + let runtime = database.open().await.unwrap().with_ordered_condition_wait_authoring(true); + let app = router(runtime.clone()); + let run = namespaces::start_scoped(&app, namespace, "ordered-signal-recheck").await; + let events = history(&app, namespace, &run).await; + let started = &payloads(&events, "WorkflowStarted")[0]; + assert!(started.get("declared_signals").is_none()); + author(&app, namespace, "deadline-worker").await; + let initial = claim(&app, namespace).await; + let mut command = anchored("receipt-order:0", 60, 60); + command["condition_wait_input_order"] = json!("durable_receipt_order"); + assert_eq!(finish(&app, namespace, &initial, json!([command])).await.0, StatusCode::OK); + signal(&app, namespace, &run).await; + let task = claim_input(&app, namespace, "workflow_signal").await; + let events = history(&app, namespace, &run).await; + let receipt = &events.iter().find(|e| e["event_type"] == "SignalReceived").unwrap()["sequence"]; + assert_eq!(task["condition_wait_pending_input_sequence"], *receipt); + await_next_input(&app, namespace, &task).await; + let task = claim(&app, namespace).await; + assert_eq!(task["resume_source_kind"], "condition_input"); + assert_eq!(task.get("condition_wait_pending_input_sequence"), Some(&Value::Null)); + let (status, result) = finish(&app, namespace, &task, json!([{ + "type":"resolve_condition_wait", "condition_wait_id":task["condition_wait_id"], + "satisfied":true, "input_receipt_sequence":receipt, + }])).await; + assert_eq!(status, StatusCode::OK, "{result}"); + let events = history(&app, namespace, &run).await; + assert_eq!(payloads(&events, "SignalApplied").len(), 1); + assert_eq!(payloads(&events, "ConditionWaitSatisfied").len(), 1); + assert_eq!(payloads(&events, "TimerCancelled").len(), 1); + assert_eq!(poll(&app, "deadline-worker", "workflow").await, Value::Null); + runtime.close().await; + database.remove().await; +} + +#[tokio::test] +async fn an_ordered_timeout_waits_for_early_input_and_excludes_late_receipts() { + for early in [true, false] { + let namespace = "default"; + let (database, runtime, app) = setup(namespace).await; + let run = namespaces::start_scoped(&app, namespace, "ordered-receipt-boundary").await; + let initial = claim(&app, namespace).await; + let mut command = anchored("receipt-order:0", 2, 2); + command["condition_wait_input_order"] = json!("durable_receipt_order"); + let (status, result) = finish(&app, namespace, &initial, json!([command])).await; + assert_eq!(status, StatusCode::OK, "{result}"); + if early { + signal(&app, namespace, &run).await; + signal(&app, namespace, &run).await; + } + wait_for_fire(&app, namespace, &run, 1).await; + if !early { + signal(&app, namespace, &run).await; + } + + let prefix = history(&app, namespace, &run).await; + let event = |kind: &str| prefix.iter().find(|event| event["event_type"] == kind).unwrap(); + let wait = &event("ConditionWaitOpened")["payload"]["condition_wait_id"]; + let receipt = &event("SignalReceived")["sequence"]; + let timer = &event("TimerFired")["sequence"]; + assert_eq!(receipt.as_i64() < timer.as_i64(), early); + let wake = if early { claim_input(&app, namespace, "workflow_signal").await } else { claim(&app, namespace).await }; + let timeout = json!([{"type":"resolve_condition_wait","condition_wait_id":wait,"satisfied":false}]); + let decision = json!([{ + "type":"resolve_condition_wait", "condition_wait_id":wait, "satisfied":true, + "input_receipt_sequence":receipt, + }]); + if early { + let (status, result) = finish(&app, namespace, &wake, timeout).await; + assert_eq!(status, StatusCode::CONFLICT, "{result}"); + assert_eq!(result["reason"], "condition_wait_input_pending"); + assert_eq!(history(&app, namespace, &run).await, prefix); + await_next_input(&app, namespace, &wake).await; + let second = claim_input(&app, namespace, "workflow_signal").await; + let (status, result) = finish(&app, namespace, &second, decision).await; + assert_eq!(status, StatusCode::OK, "{result}"); + let history = history(&app, namespace, &run).await; + assert_eq!(payloads(&history, "SignalApplied").len(), 2); + let result = payloads(&history, "ConditionWaitSatisfied"); + assert_eq!(result.len(), 1); + assert_eq!(result[0]["input_receipt_sequence"], *receipt); + } else { + let (status, result) = finish(&app, namespace, &wake, decision).await; + assert_eq!(status, StatusCode::CONFLICT, "{result}"); + assert_eq!(result["reason"], "condition_wait_outcome_mismatch"); + assert_eq!(history(&app, namespace, &run).await, prefix); + let (status, result) = finish(&app, namespace, &wake, json!([{ + "type":"resolve_condition_wait", "condition_wait_id":wait, "satisfied":true, + }])).await; + assert_eq!(status, StatusCode::CONFLICT, "{result}"); + assert_eq!(result["reason"], "condition_wait_outcome_mismatch"); + assert_eq!(history(&app, namespace, &run).await, prefix); + let (status, result) = finish(&app, namespace, &wake, timeout).await; + assert_eq!(status, StatusCode::OK, "{result}"); + let result = payloads(&history(&app, namespace, &run).await, "ConditionWaitTimedOut"); + assert_eq!(result.len(), 1); + assert_eq!(result[0]["timer_fired_sequence"], *timer); + } + runtime.close().await; + database.remove().await; + } +} + +#[tokio::test] +async fn unhandled_signal_receipts_cannot_strand_an_ordered_timeout() { + let namespace = "default"; + let database = TestDatabase::new().await; + let runtime = database.open().await.unwrap().with_ordered_condition_wait_authoring(true); + let app = router(runtime.clone()); + let (status, registered) = request(&app, "POST", "/api/worker/register", json!({ + "worker_id":"deadline-worker","task_queue":"test","runtime":"php", + "supported_workflow_types":["echo"],"capabilities":["condition_wait_input_order"], + })).await; + assert_eq!(status, StatusCode::CREATED, "{registered}"); + let run = namespaces::start_scoped(&app, namespace, "ordered-receipt-without-handler").await; + let initial = claim(&app, namespace).await; + let mut command = anchored("receipt-order:0", 2, 2); + command["condition_wait_input_order"] = json!("durable_receipt_order"); + assert_eq!(finish(&app, namespace, &initial, json!([command])).await.0, StatusCode::OK); + signal(&app, namespace, &run).await; + signal(&app, namespace, &run).await; + wait_for_fire(&app, namespace, &run, 1).await; + let first = claim_input(&app, namespace, "workflow_signal").await; + await_next_input(&app, namespace, &first).await; + let second = claim_input(&app, namespace, "workflow_signal").await; + let events = history(&app, namespace, &run).await; + let wait = &payloads(&events, "ConditionWaitOpened")[0]["condition_wait_id"]; + let (status, result) = finish(&app, namespace, &second, json!([{ + "type":"resolve_condition_wait", "condition_wait_id":wait, "satisfied":false, + }])).await; + assert_eq!(status, StatusCode::OK, "{result}"); + let events = history(&app, namespace, &run).await; + assert!(payloads(&events, "SignalApplied").is_empty()); + assert_eq!(payloads(&events, "ConditionWaitTimedOut").len(), 1); + runtime.close().await; + database.remove().await; +} + +#[tokio::test] +async fn after_fire_only_a_successful_update_can_supply_receipt_evidence() { + for (succeeds, resolves_same_turn) in [(true, true), (true, false), (false, true)] { + let namespace = "default"; + let database = TestDatabase::new().await; + let runtime = database.open().await.unwrap().with_ordered_condition_wait_authoring(true); + let app = router(runtime.clone()); + let (status, registered) = request(&app, "POST", "/api/worker/register", json!({ + "worker_id":"deadline-worker","task_queue":"test","runtime":"php","supported_workflow_types":["echo"], + "capabilities":["workflow_updates","condition_wait_input_order"],"workflow_command_contracts":{"echo":{ + "signals":[],"updates":["set"],"update_validators":[],"update_contracts":[{"name":"set", + "parameters":[{"name":"value","type":"int","required":true,"variadic":false, + "default_available":false,"allows_null":false}]}] + }}, + })).await; + assert_eq!(status, StatusCode::CREATED, "{registered}"); + let workflow = "ordered-update-evidence"; + let run = namespaces::start_scoped(&app, namespace, workflow).await; + let initial = claim(&app, namespace).await; + let mut command = anchored("receipt-order:0", 2, 2); + command["condition_wait_input_order"] = json!("durable_receipt_order"); + assert_eq!(finish(&app, namespace, &initial, json!([command])).await.0, StatusCode::OK); + let (status, update) = request(&app, "POST", &format!("/api/workflows/{workflow}/update/set"), json!({ + "input":envelope(Payload::Array(vec![Payload::Long(1)])),"wait_for":"accepted", + })).await; + assert_eq!(status, StatusCode::ACCEPTED, "{update}"); + wait_for_fire(&app, namespace, &run, 1).await; + let task = claim_input(&app, namespace, "workflow_update").await; + assert_eq!(task["workflow_update_id"], update["update_id"]); + let prefix = history(&app, namespace, &run).await; + let event = |kind: &str| prefix.iter().find(|event| event["event_type"] == kind).unwrap(); + let wait = &event("ConditionWaitOpened")["payload"]["condition_wait_id"]; + let receipt = &event("UpdateAccepted")["sequence"]; + let fire = &event("TimerFired")["sequence"]; + assert!(receipt.as_i64() < fire.as_i64()); + assert_eq!(task["condition_wait_pending_input_sequence"], *receipt); + let chosen = json!({"type":"resolve_condition_wait", "condition_wait_id":wait, + "satisfied":true, "input_receipt_sequence":receipt}); + if succeeds { + let completed = json!({"type":"complete_update", "update_id":update["update_id"], + "result":envelope(Payload::Long(1))}); + let (status, result) = if resolves_same_turn { + finish(&app, namespace, &task, json!([completed, chosen])).await + } else { + let timer = claim(&app, namespace).await; + assert_eq!(timer["resume_source_kind"], "timer"); + assert_eq!(timer["condition_wait_pending_input_sequence"], *receipt); + await_next_input(&app, namespace, &timer).await; + let (status, result) = finish(&app, namespace, &task, json!([completed])).await; + assert_eq!(status, StatusCode::OK, "{result}"); + let evaluation = claim(&app, namespace).await; + assert_eq!(evaluation["resume_source_kind"], "condition_input"); + assert_eq!(evaluation.get("condition_wait_pending_input_sequence"), Some(&Value::Null)); + finish(&app, namespace, &evaluation, json!([chosen])).await + }; + assert_eq!(status, StatusCode::OK, "{result}"); + let events = history(&app, namespace, &run).await; + let applied = events.iter().find(|event| event["event_type"] == "UpdateApplied").unwrap(); + assert!(fire.as_i64() < applied["sequence"].as_i64()); + let outcome = payloads(&events, "ConditionWaitSatisfied"); + assert_eq!(outcome.len(), 1); + assert_eq!(outcome[0]["input_receipt_sequence"], *receipt); + } else { + let failed = json!({"type":"fail_update", "update_id":update["update_id"], "message":"handler failed"}); + let (status, result) = finish(&app, namespace, &task, json!([failed.clone(), chosen])).await; + assert_eq!(status, StatusCode::CONFLICT, "{result}"); + assert_eq!(result["reason"], "condition_wait_outcome_mismatch"); + assert_eq!(history(&app, namespace, &run).await, prefix); + let (status, result) = finish(&app, namespace, &task, json!([failed, { + "type":"resolve_condition_wait", "condition_wait_id":wait, "satisfied":false, + }])).await; + assert_eq!(status, StatusCode::OK, "{result}"); + let events = history(&app, namespace, &run).await; + let outcomes = payloads(&events, "UpdateCompleted"); + assert_eq!(outcomes.len(), 1); + assert_eq!(outcomes[0]["update_id"], update["update_id"]); + assert!(outcomes[0]["failure_id"].is_string()); + assert!(payloads(&events, "UpdateApplied").is_empty()); + assert_eq!(payloads(&events, "ConditionWaitTimedOut").len(), 1); + } + runtime.close().await; + database.remove().await; + } +} + +#[tokio::test] +async fn ordered_condition_history_stays_with_capable_workers_after_resolution() { + let namespace = "default"; + let (database, runtime, app) = setup(namespace).await; + let legacy = "legacy-deadline-worker"; + register(&app, legacy, json!(["echo"]), json!([])).await; + let mut command = anchored("receipt-order:0", 0, 0); + command["condition_wait_input_order"] = json!("durable_receipt_order"); + + let unmarked = namespaces::start_scoped(&app, namespace, "ordered-condition-claim-guard").await; + let old = poll(&app, legacy, "workflow").await; + let before = history(&app, namespace, &unmarked).await; + let (status, result) = finish(&app, namespace, &old, json!([command.clone()])).await; + assert_eq!(status, StatusCode::CONFLICT, "{result}"); + assert_eq!(result["reason"], "condition_wait_input_order_not_supported"); + assert_eq!(history(&app, namespace, &unmarked).await, before); + assert_eq!(finish(&app, namespace, &old, json!([{ + "type":"complete_workflow","result":envelope(Payload::Boolean(true)), + }])).await.0, StatusCode::OK); + + let marked = namespaces::start_scoped(&app, namespace, "ordered-condition-history-guard").await; + let initial = claim(&app, namespace).await; + assert_eq!(finish(&app, namespace, &initial, json!([command])).await.0, StatusCode::OK); + let fired = wait_for_fire(&app, namespace, &marked, 1).await; + assert_eq!(poll(&app, legacy, "workflow").await, Value::Null); + let wake = claim(&app, namespace).await; + let (status, result) = finish(&app, namespace, &wake, json!([{ + "type":"resolve_condition_wait", "condition_wait_id":fired[0]["condition_wait_id"], "satisfied":false, + }, {"type":"start_timer","delay_seconds":0}])).await; + assert_eq!(status, StatusCode::OK, "{result}"); + wait_for_fire(&app, namespace, &marked, 2).await; + assert_eq!(poll(&app, legacy, "workflow").await, Value::Null); + let wake = claim(&app, namespace).await; + assert_eq!(wake["run_id"], marked["run_id"]); + assert_eq!(finish(&app, namespace, &wake, json!([{ + "type":"complete_workflow","result":envelope(Payload::Boolean(false)), + }])).await.0, StatusCode::OK); + runtime.close().await; + database.remove().await; +} + /// Several false wakes, each reopened after a delay (S→R latency), keep the /// exact same A for the reopened wait's deadline and timer, while /// `timeout_seconds`/`delay_seconds` keep the authored remaining budget. diff --git a/rust/tests/execution/selections.rs b/rust/tests/execution/selections.rs index 416e80b43..752733916 100644 --- a/rust/tests/execution/selections.rs +++ b/rust/tests/execution/selections.rs @@ -1,5 +1,78 @@ use super::*; +#[tokio::test] +async fn ordered_selection_commits_the_exact_child_candidate_without_waiting_for_the_timer() { + let database = TestDatabase::new().await; + let runtime = database.open().await.unwrap().with_ordered_condition_wait_authoring(true); + let app = router(runtime.clone()); + let worker = "ordered-selection-parent"; + let (status, registration) = request(&app, "POST", "/api/worker/register", json!({ + "worker_id":worker,"task_queue":"test","runtime":"rust", + "supported_workflow_types":["echo"],"supported_activity_types":[], + "capabilities":["condition_wait_input_order"], + "workflow_command_contracts":{"echo":{"signals":["approve"],"queries":[],"updates":[]}} + })).await; + assert_eq!(status, StatusCode::CREATED, "{registration}"); + register(&app, "selection-child-worker", json!(["selection-child"]), json!([])).await; + let started = start(&app, "ordered-selection-child-first").await; + let parent = poll(&app, worker, "workflow").await; + let condition = json!({ + "type":"open_condition_wait", "condition_wait_occurrence_id":"approval:0", + "condition_key":"approval", "condition_definition_fingerprint":"approval-v1", + "timeout_seconds":240, "deadline_policy":"occurrence", + "condition_wait_timeout_budget_seconds":240, "condition_wait_input_order":"durable_receipt_order", + }); + let child_command = child_and_signal_selection()[0].clone(); + let commands = selection_pair(1, "mixed", [ + (child_command, "child", "child"), + (condition, "approval", "condition"), + ]); + let (status, result) = finish_task(&app, &parent, commands).await; + assert_eq!(status, StatusCode::OK, "{result}"); + + let child = poll(&app, "selection-child-worker", "workflow").await; + let (status, result) = finish_task(&app, &child, + json!([{"type":"complete_workflow","result":envelope(Payload::Long(7))}])).await; + assert_eq!(status, StatusCode::OK, "{result}"); + let history = || run_history(&app, &started["workflow_id"], &started["run_id"]); + let prefix = history().await; + let events = prefix.as_array().unwrap(); + let event = |kind: &str| events.iter().find(|event| event["event_type"] == kind).unwrap(); + let opened = &event("ConditionWaitOpened")["payload"]; + let terminal = event("ChildRunCompleted"); + let candidate = &event("SelectionCandidateReady")["payload"]; + assert_eq!(candidate["resolution_event_sequence"], terminal["sequence"]); + let event_id = database.selection_history_id( + started["run_id"].as_str().unwrap(), terminal["sequence"].as_i64().unwrap(), + ).await; + assert_eq!(candidate["resolution_event_id"], event_id); + assert!(events.iter().all(|event| event["event_type"] != "SelectionResolved")); + + let resumed = poll(&app, worker, "workflow").await; + let decide = |candidate_id: &str| json!([{ + "type":"resolve_condition_wait", "condition_wait_id":opened["condition_wait_id"], + "satisfied":false, "competing_resolution_event_id":candidate_id, + }]); + let (status, result) = finish_task(&app, &resumed, decide("unrelated-event")).await; + assert_eq!(status, StatusCode::CONFLICT, "{result}"); + assert_eq!(result["reason"], "condition_wait_outcome_mismatch"); + assert_eq!(history().await, prefix); + + let (status, result) = finish_task(&app, &resumed, decide(&event_id)).await; + assert_eq!(status, StatusCode::OK, "{result}"); + let done = history().await; + let resolved = done.as_array().unwrap(); + let winner = resolved.iter().find(|event| event["event_type"] == "SelectionResolved").unwrap(); + assert_eq!(winner["payload"]["operation_identity"], child["run_id"]); + assert_eq!(winner["payload"]["resolution_event_id"], event_id); + assert!(resolved.iter().all(|event| !matches!(event["event_type"].as_str(), + Some("TimerFired" | "ConditionWaitTimedOut" | "ConditionWaitSatisfied")))); + let replay = poll(&app, worker, "workflow").await; + assert_eq!(replay["run_id"], started["run_id"], "{replay}"); + runtime.close().await; + database.remove().await; +} + #[tokio::test] async fn cancellation_retains_original_timer_selection_metadata_across_reopen() { let database = TestDatabase::new().await; @@ -558,6 +631,121 @@ async fn false_selected_condition_wake_reuses_the_member_and_then_can_win() { database.remove().await; } +#[tokio::test] +async fn ordered_selected_condition_keeps_the_timeout_boundary_without_claiming_a_winner() { + for marked in [false, true] { + let database = TestDatabase::new().await; + let runtime = database.open().await.unwrap().with_ordered_condition_wait_authoring(true); + let app = router(runtime.clone()); + let worker = "ordered-condition-worker"; + let (status, registered) = request(&app, "POST", "/api/worker/register", json!({ + "worker_id":worker,"task_queue":"test","runtime":"php", + "supported_workflow_types":["echo"],"supported_activity_types":[], + "capabilities":["condition_wait_input_order"], + "workflow_command_contracts":{"echo":{"signals":["approve"],"queries":[],"updates":[]}} + })).await; + assert_eq!(status, StatusCode::CREATED, "{registered}"); + let workflow = "ordered-condition-selection"; + let started = start(&app, workflow).await; + let task = poll(&app, worker, "workflow").await; + let mut commands = nested_child_selection(true); + let condition = &mut commands[2]; + condition["type"] = json!("open_condition_wait"); + condition.as_object_mut().unwrap().remove("signal_name"); + condition["selection_member_kind"] = json!("condition"); + condition["parallel_group_path"][0]["selection_member_kind"] = json!("condition"); + condition["condition_wait_occurrence_id"] = json!("approval:0"); + condition["condition_key"] = json!("approval"); + condition["condition_definition_fingerprint"] = json!("approval-v1"); + condition["timeout_seconds"] = json!(2); + condition["deadline_policy"] = json!("occurrence"); + condition["condition_wait_timeout_budget_seconds"] = json!(2); + if marked { + condition["condition_wait_input_order"] = json!("durable_receipt_order"); + } + + let history = || run_history(&app, &started["workflow_id"], &started["run_id"]); + let prefix = history().await; + let mut invalid = commands.clone(); + invalid[2]["condition_wait_input_order"] = json!("unsupported"); + let (status, result) = finish_task(&app, &task, invalid).await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{result}"); + assert_eq!(result["reason"], "invalid_condition_wait_input_order"); + assert_eq!(history().await, prefix); + let (status, result) = finish_task(&app, &task, commands).await; + assert_eq!(status, StatusCode::OK, "{result}"); + + let (status, signal) = request( + &app, + "POST", + &format!("/api/workflows/{workflow}/signal/approve"), + json!([]), + ) + .await; + assert_eq!(status, StatusCode::ACCEPTED, "{signal}"); + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10); + let events = loop { + let observed = history().await; + if observed.as_array().unwrap().iter().any(|event| event["event_type"] == "TimerFired") { + break observed; + } + assert!(tokio::time::Instant::now() < deadline, "condition timer did not fire"); + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + }; + let events = events.as_array().unwrap(); + let event = |kind: &str| events.iter().find(|event| event["event_type"] == kind).unwrap(); + let opened = &event("ConditionWaitOpened")["payload"]; + let scheduled = &event("TimerScheduled")["payload"]; + let fired = event("TimerFired"); + assert!(event("SignalReceived")["sequence"].as_i64() < fired["sequence"].as_i64()); + assert_eq!(scheduled["condition_wait_id"], opened["condition_wait_id"]); + assert_eq!(fired["payload"]["condition_wait_id"], opened["condition_wait_id"]); + assert_eq!(fired["payload"]["timer_id"], scheduled["timer_id"]); + assert_eq!(scheduled["fire_at"], opened["occurrence_deadline_at"]); + for payload in [opened, scheduled, &fired["payload"]] { + assert_eq!(payload.get("condition_wait_input_order").and_then(Value::as_str), + marked.then_some("durable_receipt_order")); + } + let winner = events.iter().find(|event| event["event_type"] == "SelectionResolved"); + if marked { + assert!(winner.is_none()); + } else { + assert_eq!(winner.unwrap()["payload"]["resolution_event_type"], "TimerFired"); + } + assert!(events.iter().all(|event| event["event_type"] != "SignalApplied")); + let resumed = poll(&app, worker, "workflow").await; + assert_eq!(resumed["run_id"], started["run_id"]); + if marked { + let decision = |receipt: &Value| json!([{ + "type":"resolve_condition_wait", "condition_wait_id":opened["condition_wait_id"], + "satisfied":true, "input_receipt_sequence":receipt, + }]); + let prefix = history().await; + let (status, result) = finish_task(&app, &resumed, decision(&fired["sequence"])).await; + assert_eq!(status, StatusCode::CONFLICT, "{result}"); + assert_eq!(result["reason"], "condition_wait_outcome_mismatch"); + assert_eq!(history().await, prefix); + let receipt = &event("SignalReceived")["sequence"]; + let (status, result) = finish_task(&app, &resumed, decision(receipt)).await; + assert_eq!(status, StatusCode::OK, "{result}"); + let resolved = history().await; + let resolved = resolved.as_array().unwrap(); + let resolved_event = |kind: &str| resolved.iter().find(|event| event["event_type"] == kind).unwrap(); + let applied = resolved_event("SignalApplied"); + let satisfied = resolved_event("ConditionWaitSatisfied"); + let selected = resolved_event("SelectionResolved"); + assert!(applied["sequence"].as_i64() < satisfied["sequence"].as_i64()); + assert!(satisfied["sequence"].as_i64() < selected["sequence"].as_i64()); + assert_eq!(satisfied["payload"]["input_receipt_sequence"], *receipt); + assert_eq!(satisfied["payload"]["timer_fired_sequence"], fired["sequence"]); + assert_eq!(selected["payload"]["resolution_event_type"], "ConditionWaitSatisfied"); + assert_eq!(selected["payload"]["operation_identity"], opened["condition_wait_id"]); + } + runtime.close().await; + database.remove().await; + } +} + async fn debug(app: &Router, started: &Value) -> Value { let (status, value) = request( app,